@metamask-previews/kyc-controller 0.0.0-preview-7cfd8be → 0.0.0-preview-a3cea003b
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -3
- package/dist/KycController-method-action-types.cjs.map +1 -1
- package/dist/KycController-method-action-types.d.cts +48 -2
- package/dist/KycController-method-action-types.d.cts.map +1 -1
- package/dist/KycController-method-action-types.d.mts +48 -2
- package/dist/KycController-method-action-types.d.mts.map +1 -1
- package/dist/KycController-method-action-types.mjs.map +1 -1
- package/dist/KycController.cjs +469 -12
- package/dist/KycController.cjs.map +1 -1
- package/dist/KycController.d.cts +109 -5
- package/dist/KycController.d.cts.map +1 -1
- package/dist/KycController.d.mts +109 -5
- package/dist/KycController.d.mts.map +1 -1
- package/dist/KycController.mjs +469 -12
- package/dist/KycController.mjs.map +1 -1
- package/dist/KycService-method-action-types.cjs.map +1 -1
- package/dist/KycService-method-action-types.d.cts +38 -2
- package/dist/KycService-method-action-types.d.cts.map +1 -1
- package/dist/KycService-method-action-types.d.mts +38 -2
- package/dist/KycService-method-action-types.d.mts.map +1 -1
- package/dist/KycService-method-action-types.mjs.map +1 -1
- package/dist/KycService.cjs +177 -22
- package/dist/KycService.cjs.map +1 -1
- package/dist/KycService.d.cts +97 -12
- package/dist/KycService.d.cts.map +1 -1
- package/dist/KycService.d.mts +97 -12
- package/dist/KycService.d.mts.map +1 -1
- package/dist/KycService.mjs +178 -23
- package/dist/KycService.mjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -5
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +5 -5
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +49 -10
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +49 -10
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/package.json +1 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Action,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n UserStorageControllerPerformGetStorageAction,\n UserStorageControllerPerformSetStorageAction,\n} from '@metamask/profile-sync-controller/user-storage';\nimport type { Json } from '@metamask/utils';\nimport { x25519 } from '@noble/curves/ed25519';\n\nimport { decryptCredentials, generateKeyPair } from './crypto.js';\nimport type { EncryptedCredentialsEnvelope, X25519KeyPair } from './crypto.js';\nimport { toBase64Url } from './encoding.js';\nimport type { KycControllerMethodActions } from './KycController-method-action-types.js';\nimport type { KycServiceMethodActions } from './KycService-method-action-types.js';\nimport type {\n KycDisclaimer,\n KycPhase,\n KycProduct,\n KycSessionStatus,\n KycSumSubLauncher,\n KycSumSubStatus,\n} from './types.js';\nimport { deriveClientMaterial } from './ukyc/deriveClientMaterial.js';\nimport { verifyJwtChain } from './ukyc/jwtChain.js';\nimport { getOrCreateLocalUserSecret } from './ukyc/localUserSecret.js';\nimport type { UkycLocalUserSecretStore } from './ukyc/localUserSecret.js';\nimport { signStorageAccessToken } from './ukyc/storageAccessToken.js';\nimport { wrapEncryptionKey } from './ukyc/wrapEncryptionKey.js';\n\n// === GENERAL ===\n\nexport const controllerName = 'KycController';\n\nconst FRAMES_BASE_URL = 'https://blocks.moonpay.com/platform/v1';\nconst CHANNEL_CHECK = 'ch_1';\nconst CHANNEL_AUTH = 'ch_2';\nconst CHANNEL_RESET = 'ch_reset';\n\n// Placeholder credentials for the SumSub sub-flow. These are demo values that\n// must be replaced with real UKYC-issued material before production use.\nconst MOCK_JWT_TOKEN = 'mock-jwt-token';\n\n// Lifetime of the read-only `ukyc_capability_token` minted when creating a\n// UKYC session. The storage-and-auth spec requires the token's `expires_at` to\n// cover the KYC session's expected lifetime — including the provider journey —\n// rather than a fixed short window, so this is a session-scoped window.\nconst UKYC_CAPABILITY_TOKEN_TTL_MS = 4 * 60 * 60 * 1000;\n\n// The SumSub SDK status that signals the applicant finished the flow\n// successfully. Any other resolution (abandonment, failure, or a non-success\n// outcome) must not be recorded as `complete`.\nconst SUMSUB_COMPLETED_STATUS = 'Completed';\n\n// Phases that represent an active vendor-session flow (tokens issued and/or\n// Check/Auth frames in progress). A repeat `initialize` while in one of these\n// must not restart the session and disrupt the in-flight flow.\nconst IN_PROGRESS_PHASES: KycPhase[] = [\n 'session',\n 'check',\n 'auth',\n 'form',\n 'submit',\n];\n\n// How often to poll the UKYC session status after the SumSub SDK completes,\n// until a terminal status is reached. Overridable via the constructor.\nconst DEFAULT_SESSION_STATUS_POLL_INTERVAL_MS = 15_000;\n\n// UKYC status values. `kycStatus` (the relay-side decision) and `finalStatus`\n// (the vendor-side outcome) draw from the same vocabulary, so they are defined\n// once here and composed into the sets/checks below rather than repeated as\n// literals.\nconst KYC_STATUSES = {\n approved: 'approved',\n completed: 'completed',\n rejected: 'rejected',\n failed: 'failed',\n blocked: 'blocked',\n pending: 'pending',\n} as const;\n\n// `finalStatus` values that end the polling loop. Anything else (e.g.\n// `KYC_STATUSES.pending`) keeps polling.\nconst TERMINAL_SESSION_STATUSES: ReadonlySet<string> = new Set([\n KYC_STATUSES.approved,\n KYC_STATUSES.completed,\n KYC_STATUSES.rejected,\n KYC_STATUSES.failed,\n KYC_STATUSES.blocked,\n]);\n\n// Terminal `finalStatus` values that represent a successful verification. Any\n// other terminal status resolves the sub-flow to `failed`.\nconst SUCCESSFUL_SESSION_STATUSES: ReadonlySet<string> = new Set([\n KYC_STATUSES.approved,\n KYC_STATUSES.completed,\n]);\n\n// Session creation can report that the applicant is already approved on the\n// relay (`kycStatus === KYC_STATUSES.approved`) while the vendor is still\n// finalizing its decision (`finalStatus === KYC_STATUSES.pending`, a\n// non-terminal status). In that case there is nothing left for the applicant\n// to do, so the sub-flow stops before launching the SDK and surfaces this\n// message.\nconst VENDOR_PROCESSING_MESSAGE =\n 'Your KYC has been submitted and is being processed by the vendor.';\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link KycController}.\n */\nexport type KycControllerState = {\n /** Current phase of the identity flow. */\n phase: KycPhase;\n /** Human-readable status message for the current phase. */\n statusMessage: string;\n /** The current error message, or `null`. */\n error: string | null;\n\n /** Email associated with the session (sourced from the account). */\n email: string | null;\n\n /** ISO-8601 timestamp of the customer's terms acceptance (persisted). */\n termsAcceptedAt: string | null;\n /** IDs of the disclaimers the customer accepted (persisted). */\n acceptedDisclaimerIds: string[];\n\n /** Disclaimers fetched for the current country. */\n disclaimers: KycDisclaimer[];\n /** Error encountered while loading disclaimers, or `null`. */\n disclaimersError: string | null;\n\n /** Resolved ISO 3166-1 alpha-3 country code. */\n geoCountry: string | null;\n\n /** Vendor session token (not persisted, not logged). */\n sessionToken: string | null;\n /** Vendor access token (not persisted, not logged). */\n accessToken: string | null;\n /** Vendor customer id, used for the SumSub hand-off. */\n moonpayCustomerId: string | null;\n\n /**\n * The product the current flow is running for. Captured at `initialize`\n * (or `acceptTermsAndStartSession`) and used to automatically run the\n * KYC-required check once authentication completes. `null` outside a\n * product-scoped flow (in which case the flow stops at `form` and the\n * consumer drives the check manually).\n */\n activeProduct: KycProduct | null;\n\n /** Cached \"is KYC required\" result per product (persisted). */\n kycRequiredByProduct: Partial<Record<KycProduct, boolean>>;\n /** ISO-8601 timestamp of the last KYC-required check (persisted). */\n lastCheckedAt: string | null;\n\n /** SumSub document-verification sub-flow state. */\n sumsub: {\n status: KycSumSubStatus;\n result: Json | null;\n sessionId: string | null;\n applicantAccessToken: string | null;\n /**\n * The latest UKYC session status, populated while polling after the SDK\n * completes. `null` until the first successful poll.\n */\n sessionStatus: KycSessionStatus | null;\n };\n};\n\nconst kycControllerMetadata = {\n phase: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n statusMessage: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n error: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n email: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: false,\n },\n termsAcceptedAt: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: false,\n },\n acceptedDisclaimerIds: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: false,\n },\n disclaimers: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: true,\n },\n disclaimersError: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n geoCountry: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n sessionToken: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: false,\n },\n accessToken: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: false,\n },\n moonpayCustomerId: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: false,\n },\n activeProduct: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n kycRequiredByProduct: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: true,\n },\n lastCheckedAt: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: false,\n },\n sumsub: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: true,\n },\n} satisfies StateMetadata<KycControllerState>;\n\n/**\n * Constructs the default {@link KycController} state.\n *\n * @returns The default state.\n */\nexport function getDefaultKycControllerState(): KycControllerState {\n return {\n phase: 'idle',\n statusMessage: '',\n error: null,\n email: null,\n termsAcceptedAt: null,\n acceptedDisclaimerIds: [],\n disclaimers: [],\n disclaimersError: null,\n geoCountry: null,\n sessionToken: null,\n accessToken: null,\n moonpayCustomerId: null,\n activeProduct: null,\n kycRequiredByProduct: {},\n lastCheckedAt: null,\n sumsub: {\n status: 'idle',\n result: null,\n sessionId: null,\n applicantAccessToken: null,\n sessionStatus: null,\n },\n };\n}\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'initialize',\n 'loadDisclaimers',\n 'acceptTermsAndStartSession',\n 'clearSavedTerms',\n 'handleFrameMessage',\n 'buildCheckFrameUrl',\n 'buildAuthFrameUrl',\n 'buildResetFrameUrl',\n 'checkKycRequired',\n 'getKycStatus',\n 'startSumSub',\n 'getSessionStatus',\n 'reset',\n] as const;\n\nexport type KycControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n KycControllerState\n>;\n\nexport type KycControllerActions =\n | KycControllerGetStateAction\n | KycControllerMethodActions;\n\ntype AllowedActions =\n | KycServiceMethodActions\n | UserStorageControllerPerformGetStorageAction\n | UserStorageControllerPerformSetStorageAction;\n\nexport type KycControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n KycControllerState\n>;\n\nexport type KycControllerEvents = KycControllerStateChangeEvent;\n\ntype AllowedEvents = never;\n\nexport type KycControllerMessenger = Messenger<\n typeof controllerName,\n KycControllerActions | AllowedActions,\n KycControllerEvents | AllowedEvents\n>;\n\n/**\n * Options for constructing a {@link KycController}.\n */\nexport type KycControllerOptions = {\n messenger: KycControllerMessenger;\n state?: Partial<KycControllerState>;\n /**\n * Platform adapter that presents the SumSub SDK. Injected by each client so\n * the controller stays platform-agnostic.\n */\n sumsubLauncher: KycSumSubLauncher;\n /**\n * How often, in milliseconds, to poll the UKYC session status after the\n * SumSub SDK completes. Defaults to\n * {@link DEFAULT_SESSION_STATUS_POLL_INTERVAL_MS}.\n */\n sessionStatusPollIntervalMs?: number;\n};\n\n/**\n * The shape of a message posted by a Check/Auth frame.\n */\ntype FrameMessage = {\n meta?: { channelId?: string };\n kind?: string;\n payload?: {\n status?:\n | 'active'\n | 'connectionRequired'\n | 'termsAcceptanceRequired'\n | 'pending'\n | 'unavailable'\n | 'failed';\n credentials?: EncryptedCredentialsEnvelope | string;\n customer?: { id?: string };\n };\n};\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * `KycController` orchestrates the vendor-backed KYC / identity-verification\n * flow (MoonPay identity + SumSub documents) behind a vendor-neutral, per\n * product surface used by ramps and card. It owns all state, HTTP\n * orchestration (via `KycService`), crypto, and the frame message protocol;\n * platform-specific presentation (WebView/iframe, SumSub SDK) is injected.\n */\nexport class KycController extends BaseController<\n typeof controllerName,\n KycControllerState,\n KycControllerMessenger\n> {\n readonly #sumsubLauncher: KycSumSubLauncher;\n\n /** Ephemeral X25519 keypair for the frame key exchange (never persisted). */\n readonly #keypair: X25519KeyPair;\n\n /** Auth-frame client token, kept out of state. */\n #authClientToken: string | null = null;\n\n /**\n * Monotonic flow generation. Incremented by {@link reset} so in-flight async\n * work (e.g. the KYC-required check) can detect that it was superseded and\n * avoid writing stale results onto a reset controller.\n */\n #generation = 0;\n\n /** Interval, in milliseconds, between session-status polls. */\n readonly #sessionStatusPollIntervalMs: number;\n\n /** Handle for the scheduled next session-status poll, or `null`. */\n #pollTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * Monotonic polling token. Bumped by {@link #stopPolling} (called on reset, a\n * new sub-flow, and once a terminal status is reached) so an in-flight poll\n * `tick` can detect it was superseded and neither write state nor schedule a\n * follow-up. This closes the gap where clearing the timer alone would still\n * let an already-awaiting request finish and reschedule.\n */\n #pollToken = 0;\n\n /**\n * Constructs a new {@link KycController}.\n *\n * @param options - The constructor options.\n * @param options.messenger - The messenger suited for this controller.\n * @param options.state - Partial initial state; merged over defaults.\n * @param options.sumsubLauncher - The platform SumSub launcher adapter.\n * @param options.sessionStatusPollIntervalMs - How often to poll the UKYC\n * session status after the SumSub SDK completes.\n */\n constructor({\n messenger,\n state,\n sumsubLauncher,\n sessionStatusPollIntervalMs = DEFAULT_SESSION_STATUS_POLL_INTERVAL_MS,\n }: KycControllerOptions) {\n super({\n messenger,\n metadata: kycControllerMetadata,\n name: controllerName,\n state: { ...getDefaultKycControllerState(), ...state },\n });\n\n this.#sumsubLauncher = sumsubLauncher;\n this.#sessionStatusPollIntervalMs = sessionStatusPollIntervalMs;\n this.#keypair = generateKeyPair();\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Builds an adapter over `UserStorageController` that the platform-agnostic\n * `getOrCreateLocalUserSecret` helper uses to persist/load the UKYC\n * `local_user_secret`.\n *\n * @returns The Encrypted User Storage adapter.\n */\n #localUserSecretStore(): UkycLocalUserSecretStore {\n return {\n get: async (\n path: string,\n entropySourceId?: string,\n ): Promise<string | null> =>\n this.messenger.call(\n 'UserStorageController:performGetStorage',\n path as `${string}.${string}`,\n entropySourceId,\n ),\n set: async (\n path: string,\n value: string,\n entropySourceId?: string,\n ): Promise<void> =>\n this.messenger.call(\n 'UserStorageController:performSetStorage',\n path as `${string}.${string}`,\n value,\n entropySourceId,\n ),\n };\n }\n\n /**\n * Resolves persisted terms + geolocation, and auto-creates a session when\n * terms are already accepted and an email is available.\n *\n * @param params - Optional parameters.\n * @param params.email - The account email to associate with the session.\n * @param params.product - The consuming feature the flow runs for. When\n * provided, the controller automatically runs the KYC-required check once\n * authentication completes (and chains into document verification when KYC\n * is required). When omitted, the flow stops at `form` and the consumer must\n * call `checkKycRequired` manually.\n */\n async initialize(params?: {\n email?: string;\n product?: KycProduct;\n }): Promise<void> {\n // A repeat `initialize` while a session flow is already in progress must\n // not tear it down: creating a new vendor session clears the tokens and\n // forces `phase` back through `session`/`check`, breaking an in-flight\n // Check/Auth frame flow. Leave the active flow untouched and let the\n // consumer drive it (or call `reset` first to start over).\n if (IN_PROGRESS_PHASES.includes(this.state.phase)) {\n return;\n }\n\n // `initialize` starts a fresh flow, so `activeProduct` is always reset to\n // this call's product (or `null`). Otherwise a prior run's product could\n // linger and cause `#continueAfterAuthentication` to auto-run the check /\n // sub-flow when the caller intended the manual (product-less) flow.\n this.#applyUpdate((state) => {\n if (params?.email) {\n state.email = params.email;\n }\n state.activeProduct = params?.product ?? null;\n });\n\n // Capture the flow generation so a `reset()` landing while the async\n // geolocation / session steps below are in flight cannot write results\n // onto an idle controller.\n const generation = this.#generation;\n\n // Resolve country for display; non-blocking.\n try {\n const country = await this.messenger.call('KycService:getGeoCountry');\n this.#updateIfCurrent(generation, (state) => {\n state.geoCountry = country;\n });\n } catch {\n // Ignore; disclaimers loading will surface a country error if needed.\n }\n\n const hasTerms =\n Boolean(this.state.termsAcceptedAt) &&\n this.state.acceptedDisclaimerIds.length > 0;\n\n if (hasTerms && this.state.email) {\n await this.#createSession();\n return;\n }\n\n this.#applyUpdate((state) => {\n state.phase = 'terms';\n });\n await this.loadDisclaimers();\n }\n\n /**\n * Loads the disclaimers for the resolved (or provided) country.\n *\n * @param params - Optional parameters.\n * @param params.country - ISO 3166-1 alpha-3 country code override.\n */\n async loadDisclaimers(params?: { country?: string }): Promise<void> {\n // Capture the flow generation so a `reset()` landing while the geo /\n // disclaimers requests are in flight cannot write results onto an idle\n // controller.\n const generation = this.#generation;\n try {\n const country =\n params?.country ??\n this.state.geoCountry ??\n (await this.messenger.call('KycService:getGeoCountry'));\n if (country !== this.state.geoCountry) {\n this.#updateIfCurrent(generation, (state) => {\n state.geoCountry = country;\n });\n }\n const disclaimers = await this.messenger.call(\n 'KycService:fetchDisclaimers',\n { country },\n );\n this.#updateIfCurrent(generation, (state) => {\n state.disclaimers = disclaimers;\n state.disclaimersError = null;\n });\n } catch (error) {\n this.#updateIfCurrent(generation, (state) => {\n state.disclaimersError = `Failed to load disclaimers: ${String(error)}`;\n });\n }\n }\n\n /**\n * Captures terms acceptance for the currently loaded disclaimers and creates\n * a session.\n *\n * @param params - Optional parameters.\n * @param params.email - The account email to associate with the session.\n * @param params.product - The consuming feature the flow runs for. See\n * {@link initialize} for how the product drives the automatic post\n * authentication continuation.\n */\n async acceptTermsAndStartSession(params?: {\n email?: string;\n product?: KycProduct;\n }): Promise<void> {\n const termsAcceptedAt = new Date().toISOString();\n const disclaimerIds = this.state.disclaimers.map(\n (disclaimer) => disclaimer.id,\n );\n this.#applyUpdate((state) => {\n if (params?.email) {\n state.email = params.email;\n }\n if (params?.product) {\n state.activeProduct = params.product;\n }\n state.termsAcceptedAt = termsAcceptedAt;\n state.acceptedDisclaimerIds = disclaimerIds;\n });\n await this.#createSession();\n }\n\n /**\n * Creates a vendor session from the currently stored terms + email.\n */\n async #createSession(): Promise<void> {\n const { email, termsAcceptedAt, acceptedDisclaimerIds } = this.state;\n if (!email) {\n this.#fail('Missing email for session creation.');\n return;\n }\n if (!termsAcceptedAt || acceptedDisclaimerIds.length === 0) {\n this.#fail('Missing terms acceptance for session creation.');\n return;\n }\n\n // A new session invalidates any authentication carried over from a prior\n // session. Clear the stale session token, access token, and auth-frame\n // client token so `buildCheckFrameUrl` cannot return a URL bound to an old\n // (or, on failure, invalid) session token, `buildAuthFrameUrl` cannot\n // return a URL tied to an old client token, and `checkKycRequired` cannot\n // run with an access token from an earlier authentication. The Check/Auth\n // frames re-populate these for the new session. Because `sessionToken` is\n // cleared here and only re-set on success, a failed creation leaves it\n // `null` rather than resurrecting the previous session.\n // Capture the flow generation so a `reset()` landing while the create\n // request is in flight cannot resurrect a session (success) or overwrite\n // the now-idle controller (failure). The synchronous update below runs\n // before any `await`, so it needs no guard.\n const generation = this.#generation;\n this.#authClientToken = null;\n this.#applyUpdate((state) => {\n state.error = null;\n state.phase = 'session';\n state.statusMessage = 'Creating session...';\n state.sessionToken = null;\n state.accessToken = null;\n });\n\n try {\n const { sessionToken } = await this.messenger.call(\n 'KycService:createSession',\n { email, termsAcceptedAt, disclaimerIds: acceptedDisclaimerIds },\n );\n this.#updateIfCurrent(generation, (state) => {\n state.sessionToken = sessionToken;\n state.phase = 'check';\n state.statusMessage = 'Authenticating via Check frame...';\n });\n } catch (error) {\n console.error('Session creation failed:', error);\n // A reset() superseded this flow while the request was in flight; leave\n // the idle controller alone rather than forcing it back to `terms`.\n if (this.#generation !== generation) {\n return;\n }\n // Invalidate the stored acceptance so the customer can retry. Also clear\n // `activeProduct` so a later `acceptTermsAndStartSession` that omits a\n // product cannot auto-run the KYC check / SumSub chain for this failed\n // flow's product — matching how `initialize` starts from a clean product.\n this.#applyUpdate((state) => {\n this.#clearAcceptedTerms(state);\n state.activeProduct = null;\n state.error = `Session creation failed: ${String(error)}`;\n state.statusMessage =\n 'Session creation failed — accept the terms to try again.';\n state.phase = 'terms';\n });\n await this.loadDisclaimers();\n }\n }\n\n /**\n * Clears the persisted terms acceptance.\n */\n clearSavedTerms(): void {\n this.#applyUpdate((state) => {\n this.#clearAcceptedTerms(state);\n });\n }\n\n /**\n * Clears the stored terms acceptance on the given draft state. Shared by the\n * paths that must invalidate acceptance — explicit clear, vendor terms\n * update, and session-creation failure — so they stay in sync. This is a\n * targeted invalidation and, unlike {@link reset}, deliberately leaves the\n * rest of the flow (geolocation, disclaimers, phase) untouched.\n *\n * @param state - The state to mutate.\n */\n #clearAcceptedTerms(state: KycControllerState): void {\n state.termsAcceptedAt = null;\n state.acceptedDisclaimerIds = [];\n }\n\n /**\n * Handles a message posted by a Check/Auth frame and advances the flow.\n *\n * The transport-agnostic caller (WebView on mobile, iframe on web) forwards\n * the raw message and injects the returned `reply` back into the frame.\n *\n * @param params - The parameters.\n * @param params.message - The raw message posted by the frame.\n * @returns An object whose optional `reply` should be posted back.\n */\n async handleFrameMessage(params: {\n message: unknown;\n }): Promise<{ reply?: unknown }> {\n const payload = params.message as FrameMessage | undefined;\n\n if (!payload) {\n return {};\n }\n\n if (payload.kind === 'handshake') {\n const channelId = payload.meta?.channelId;\n return { reply: { version: 2, meta: { channelId }, kind: 'ack' } };\n }\n\n if (payload.kind !== 'complete') {\n return {};\n }\n\n const channelId = payload.meta?.channelId;\n\n // Only honor a Check/Auth `complete` for the frame the flow is currently\n // waiting on. This drops stale or duplicate messages — e.g. a late post\n // after `reset()` (phase `idle`) or after the flow already advanced past\n // this frame — so they cannot resurrect tokens or rewind `phase` on a\n // controller that has moved on. Frame messages are external input and,\n // unlike the async steps, are not covered by the `#generation` guard.\n let expectedPhase: KycPhase | null = null;\n if (channelId === CHANNEL_CHECK) {\n expectedPhase = 'check';\n } else if (channelId === CHANNEL_AUTH) {\n expectedPhase = 'auth';\n }\n if (!expectedPhase || this.state.phase !== expectedPhase) {\n return {};\n }\n\n const status = payload.payload?.status;\n const credsEnvelope = payload.payload?.credentials;\n\n const customerId = payload.payload?.customer?.id ?? null;\n if (customerId) {\n this.#applyUpdate((state) => {\n state.moonpayCustomerId = customerId;\n });\n }\n\n if (!status) {\n return {};\n }\n\n let accessToken: string | undefined;\n let clientToken: string | undefined;\n if (credsEnvelope) {\n try {\n const { credentials } = decryptCredentials(\n credsEnvelope,\n this.#keypair.privateKey,\n );\n accessToken = credentials.accessToken;\n clientToken = credentials.clientToken;\n } catch (error) {\n this.#fail(`Failed to decrypt frame credentials: ${String(error)}`);\n return {};\n }\n }\n\n if (channelId === CHANNEL_CHECK) {\n await this.#handleCheckOutcome(status, accessToken, clientToken);\n return {};\n }\n\n // channelId === CHANNEL_AUTH, guaranteed by the expectedPhase guard above.\n await this.#handleAuthOutcome(status, accessToken);\n return {};\n }\n\n /**\n * Applies a Check-frame outcome.\n *\n * @param status - The frame status.\n * @param accessToken - The decrypted access token, if any.\n * @param clientToken - The decrypted client token, if any.\n */\n async #handleCheckOutcome(\n status: NonNullable<FrameMessage['payload']>['status'],\n accessToken?: string,\n clientToken?: string,\n ): Promise<void> {\n if (status === 'active' && accessToken) {\n this.#applyUpdate((state) => {\n state.accessToken = accessToken;\n state.phase = 'form';\n state.statusMessage = 'Already authenticated. Review to submit.';\n });\n await this.#continueAfterAuthentication();\n return;\n }\n if (status === 'connectionRequired' && clientToken) {\n this.#authClientToken = clientToken;\n this.#applyUpdate((state) => {\n state.phase = 'auth';\n state.statusMessage = 'Verify your email via OTP in the Auth frame.';\n });\n return;\n }\n if (status === 'termsAcceptanceRequired') {\n this.#requireTermsReacceptance();\n return;\n }\n this.#fail(`Check frame returned status: ${status}`);\n }\n\n /**\n * Applies an Auth-frame outcome.\n *\n * @param status - The frame status.\n * @param accessToken - The decrypted access token, if any.\n */\n async #handleAuthOutcome(\n status: NonNullable<FrameMessage['payload']>['status'],\n accessToken?: string,\n ): Promise<void> {\n if (status === 'active' && accessToken) {\n this.#applyUpdate((state) => {\n state.accessToken = accessToken;\n state.phase = 'form';\n state.statusMessage = 'Authenticated. Review to submit.';\n });\n await this.#continueAfterAuthentication();\n return;\n }\n if (status === 'termsAcceptanceRequired') {\n this.#requireTermsReacceptance();\n return;\n }\n this.#fail(`Auth frame returned status: ${status}`);\n }\n\n /**\n * Continues the flow once authentication has completed (phase `form`).\n *\n * When the flow is scoped to a product (see {@link initialize}), the\n * KYC-required check runs automatically, and — when KYC is required — the\n * document-verification sub-flow is launched. When no product is set, this is\n * a no-op and the flow stays at `form` for the consumer to drive manually.\n *\n * Errors are already recorded on state by `checkKycRequired` (`error`\n * phase) and `startSumSub` (`sumsub.status = 'failed'`); this method swallows\n * them so it can be awaited safely from the frame-message handler.\n */\n async #continueAfterAuthentication(): Promise<void> {\n const product = this.state.activeProduct;\n if (!product) {\n return;\n }\n\n // Re-entry protection lives at the frame boundary: `handleFrameMessage`\n // only honors a Check/Auth `complete` while `phase` matches, and both\n // outcome handlers move `phase` to `form` before awaiting this method. A\n // duplicate or late `complete` therefore lands after the phase moved on and\n // is dropped before it can start a second continuation. Any writes here are\n // additionally guarded by `#generation` (see `checkKycRequired` /\n // `startSumSub`) so a `reset()` mid-continuation cannot corrupt state.\n const kycRequired = await this.checkKycRequired({ product });\n if (!kycRequired) {\n return;\n }\n\n try {\n await this.startSumSub();\n } catch {\n // `startSumSub` already records `sumsub.status = 'failed'`; swallow the\n // rethrown error (e.g. SDK unavailable) so the awaited continuation\n // resolves cleanly rather than surfacing as an unhandled rejection.\n }\n }\n\n /**\n * Invalidates stored terms and returns to the terms phase.\n */\n #requireTermsReacceptance(): void {\n this.#applyUpdate((state) => {\n this.#clearAcceptedTerms(state);\n state.phase = 'terms';\n state.statusMessage =\n 'The vendor updated its Terms of Use — please re-accept.';\n });\n }\n\n /**\n * Builds the Check-frame URL, or `null` when no session exists yet.\n *\n * @returns The Check-frame URL or `null`.\n */\n buildCheckFrameUrl(): string | null {\n if (!this.state.sessionToken) {\n return null;\n }\n const url = new URL(`${FRAMES_BASE_URL}/check-connection`);\n url.searchParams.set('sessionToken', this.state.sessionToken);\n url.searchParams.set('publicKey', this.#keypair.publicKeyHex);\n url.searchParams.set('channelId', CHANNEL_CHECK);\n url.searchParams.set('skipKyc', 'true');\n return url.toString();\n }\n\n /**\n * Builds the Auth-frame URL, or `null` when no client token is available.\n *\n * @returns The Auth-frame URL or `null`.\n */\n buildAuthFrameUrl(): string | null {\n if (!this.#authClientToken) {\n return null;\n }\n const url = new URL(`${FRAMES_BASE_URL}/auth`);\n url.searchParams.set('clientToken', this.#authClientToken);\n url.searchParams.set('publicKey', this.#keypair.publicKeyHex);\n url.searchParams.set('channelId', CHANNEL_AUTH);\n return url.toString();\n }\n\n /**\n * Builds the Reset-frame URL.\n *\n * @returns The Reset-frame URL.\n */\n buildResetFrameUrl(): string {\n const url = new URL(`${FRAMES_BASE_URL}/reset`);\n url.searchParams.set('channelId', CHANNEL_RESET);\n return url.toString();\n }\n\n /**\n * Checks whether KYC is required for a product and caches the result.\n *\n * @param params - The parameters.\n * @param params.product - The consuming feature.\n * @param params.country - Optional alpha-3 country override.\n * @returns Whether KYC is required.\n */\n async checkKycRequired(params: {\n product: KycProduct;\n country?: string;\n }): Promise<boolean> {\n const { accessToken } = this.state;\n if (!accessToken) {\n this.#fail('Missing accessToken — repeat the authentication step.');\n return false;\n }\n const country = params.country ?? this.state.geoCountry;\n if (!country) {\n this.#fail('Missing country for KYC-required check.');\n return false;\n }\n\n // Capture the flow generation so we can detect a `reset()` that happens\n // while the HTTP call is in flight and avoid writing stale results.\n const generation = this.#generation;\n\n this.#applyUpdate((state) => {\n state.phase = 'submit';\n state.statusMessage = 'Checking KYC status...';\n });\n\n try {\n const { kycRequired } = await this.messenger.call(\n 'KycService:checkKycRequired',\n { accessToken, country, capabilities: [{ product: params.product }] },\n );\n // The flow was reset while the check was in flight; discard the result\n // rather than resurrecting a done/cached state on an idle controller.\n const applied = this.#updateIfCurrent(generation, (state) => {\n state.kycRequiredByProduct[params.product] = kycRequired;\n state.lastCheckedAt = new Date().toISOString();\n state.phase = 'done';\n state.statusMessage = 'KYC check complete.';\n });\n if (!applied) {\n return false;\n }\n return kycRequired;\n } catch (error) {\n if (this.#generation !== generation) {\n return false;\n }\n this.#fail(`KYC check failed: ${String(error)}`);\n return false;\n }\n }\n\n /**\n * Reads the cached \"is KYC required\" result for a product.\n *\n * @param params - The parameters.\n * @param params.product - The consuming feature.\n * @returns The cached value, or `undefined` if not yet checked.\n */\n getKycStatus(params: { product: KycProduct }): boolean | undefined {\n return this.state.kycRequiredByProduct[params.product];\n }\n\n /**\n * Runs the SumSub document-verification sub-flow end to end:\n *\n * 1. requests a per-session wrapping key from the UKYC backend;\n * 2. verifies its `jwtChain` against the Fractal JWKS and confirms the\n * attested session server public key;\n * 3. derives the `data_encryption_key` from the wallet's UKYC\n * `local_user_secret` and wraps it for the session server;\n * 4. mints a client-signed, read-only `ukyc_capability_token` and creates\n * the UKYC session (handing over the wrapped key and the token);\n * 5. fetches the SumSub applicant access token; and\n * 6. presents the SDK via the injected launcher.\n *\n * If session creation reports the applicant is already approved on the relay\n * while the vendor is still finalizing (`kycStatus: approved`,\n * `finalStatus: pending`), the sub-flow stops at step 4 with a\n * `vendorProcessing` status and a message rather than launching the SDK.\n *\n * @param params - Optional parameters.\n * @param params.locale - BCP-47 locale for the SDK UI.\n * @param params.debug - Enables SDK debug logging.\n * @returns The SDK result.\n */\n async startSumSub(params?: {\n locale?: string;\n debug?: boolean;\n }): Promise<Record<string, unknown>> {\n // A new sub-flow supersedes any polling still running from a prior run.\n this.#stopPolling();\n\n if (!this.#sumsubLauncher.isAvailable()) {\n const error = 'SumSub SDK is not available in this runtime.';\n this.#applyUpdate((state) => {\n state.sumsub.status = 'failed';\n state.sumsub.result = { error };\n });\n throw new Error(error);\n }\n\n // Capture the flow generation so each async step can detect a `reset()`\n // that lands mid-flight and avoid writing stale sub-flow state (or, worse,\n // presenting the SDK) on a controller that is now idle.\n const generation = this.#generation;\n\n try {\n this.#applyUpdate((state) => {\n state.sumsub.status = 'creatingSession';\n state.sumsub.result = null;\n state.sumsub.sessionStatus = null;\n });\n\n const jwtToken = MOCK_JWT_TOKEN;\n\n // Establish a per-session X25519 keypair and exchange our public half for\n // the server's wrapping key. The private half stays on the device and is\n // used to derive the shared secret that seals the data_encryption_key.\n const sessionClientPrivateKey = x25519.utils.randomSecretKey();\n const sessionClientPublicKey = x25519.getPublicKey(\n sessionClientPrivateKey,\n );\n const wrappingKey = await this.messenger.call(\n 'KycService:getWrappingKey',\n { sessionClientPublicKey: toBase64Url(sessionClientPublicKey) },\n );\n\n // Verify the jwtChain against Fractal's JWKS, then confirm the returned\n // sessionServerPublicKey matches the value attested inside the verified\n // JWT payload before trusting it for key wrapping.\n const { keys } = await this.messenger.call('KycService:fetchJwks');\n const jwtChainPayload = verifyJwtChain(keys, wrappingKey.jwtChain);\n if (\n jwtChainPayload.sessionServerPublicKeyX !==\n wrappingKey.sessionServerPublicKey.x\n ) {\n throw new Error(\n 'sessionServerPublicKey does not match the verified jwtChain payload (sessionServerPublicKeyX).',\n );\n }\n\n // Derive the data_encryption_key from the local_user_secret and wrap it\n // for the session server. Only the wrapped (encrypted) key ever leaves\n // the device.\n const localUserSecret = await getOrCreateLocalUserSecret(\n this.#localUserSecretStore(),\n );\n const clientMaterial = deriveClientMaterial(localUserSecret);\n const wrappedEncryptionKey = {\n sessionId: wrappingKey.id,\n ...wrapEncryptionKey(\n sessionClientPrivateKey,\n wrappingKey.sessionServerPublicKey.x,\n clientMaterial.dataEncryptionKey,\n ),\n };\n\n // Mint a read-only `ukyc_capability_token` for the session. Only the\n // client holds the signing key derived from `local_user_secret`, so only\n // the client can mint it; scoping it to `read` means it authorizes later\n // storage reads without granting write or delete access.\n const ukycCapabilityToken = signStorageAccessToken({\n material: clientMaterial,\n operations: ['read'],\n expiresAt: new Date(Date.now() + UKYC_CAPABILITY_TOKEN_TTL_MS),\n });\n\n const { sessionId, kycStatus, finalStatus } = await this.messenger.call(\n 'KycService:createUkycSession',\n {\n jwtToken,\n vendorMetadata: {\n moonPayAccessToken: this.state.accessToken,\n moonPayUserId: this.state.moonpayCustomerId,\n },\n wrappedEncryptionKey,\n ukycCapabilityToken,\n },\n );\n\n // A user who already finished the journey can return to a session the\n // relay has already approved (`kycStatus`) while the vendor is still\n // finalizing its own decision (`finalStatus`). There is nothing left to\n // verify, so stop here and surface a message rather than launching the\n // SDK again.\n if (\n kycStatus === KYC_STATUSES.approved &&\n finalStatus === KYC_STATUSES.pending\n ) {\n const stillCurrent = this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'vendorProcessing';\n state.sumsub.sessionId = sessionId;\n state.statusMessage = VENDOR_PROCESSING_MESSAGE;\n });\n return stillCurrent ? { kycStatus, finalStatus } : {};\n }\n\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'fetchingToken';\n state.sumsub.sessionId = sessionId;\n });\n\n const { applicantAccessToken } = await this.messenger.call(\n 'KycService:createJourney',\n sessionId,\n );\n\n // A reset() may have landed while the session/token was being prepared.\n // Gate the `launching` write and the decision to open the SDK behind a\n // single generation check: `#updateIfCurrent` only writes when still\n // current and reports whether it did. Since there is no `await` between\n // this check and `launch` below, a successful result guarantees the SDK\n // is never presented on a flow that a concurrent reset() returned to idle.\n const stillCurrent = this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'launching';\n state.sumsub.applicantAccessToken = applicantAccessToken;\n });\n if (!stillCurrent) {\n return {};\n }\n\n // Track whether the SDK ever reported a successful completion. A resolved\n // `launch` alone does not imply success — the applicant may have\n // abandoned the flow or the SDK may have reported a non-success outcome.\n let reachedCompletion = false;\n\n const result = await this.#sumsubLauncher.launch({\n applicantAccessToken,\n onTokenExpiration: async () => {\n // A reset() may have superseded this flow while the SDK stayed open.\n // Refuse to refresh against the now-stale UKYC session rather than\n // silently keeping an orphaned SDK alive.\n if (this.#generation !== generation) {\n throw new Error(\n 'KYC flow was reset; SumSub session is no longer active.',\n );\n }\n const refreshed = await this.messenger.call(\n 'KycService:createJourney',\n sessionId,\n );\n return refreshed.applicantAccessToken;\n },\n onStatusChange: (_prev, next) => {\n if (next === SUMSUB_COMPLETED_STATUS) {\n reachedCompletion = true;\n }\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status =\n next === SUMSUB_COMPLETED_STATUS ? 'complete' : 'inProgress';\n });\n },\n locale: params?.locale ?? 'en',\n debug: params?.debug ?? false,\n });\n\n // A resolved `launch` alone is not the final outcome: only a SDK-reported\n // completion is worth polling for a verification decision. Anything else\n // (abandonment, non-success) is `failed` and must not be polled.\n const applied = this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = reachedCompletion ? 'polling' : 'failed';\n state.sumsub.result = result as Json;\n });\n\n // Once the SDK completes, the authoritative verification decision comes\n // from the UKYC backend, not the SDK result. Poll the session status\n // until it reaches a terminal decision. Guard on `applied` so a `reset()`\n // that landed during `launch` cannot start polling on an idle flow.\n if (applied && reachedCompletion) {\n if (sessionId) {\n await this.#startSessionStatusPolling(sessionId);\n } else {\n // No session id to poll against; fall back to treating the SDK\n // completion as the final outcome.\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'complete';\n });\n }\n }\n return result;\n } catch (error) {\n const result = { error: String(error) };\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'failed';\n state.sumsub.result = result;\n });\n return result;\n }\n }\n\n /**\n * Fetches the current UKYC session status for the active sub-flow and records\n * it on state. Useful for a one-off refresh outside the automatic polling\n * loop that {@link startSumSub} runs.\n *\n * @returns The fetched session status.\n * @throws If there is no active SumSub session to query.\n */\n async getSessionStatus(): Promise<KycSessionStatus> {\n const { sessionId } = this.state.sumsub;\n if (!sessionId) {\n throw new Error('Cannot fetch session status: no active SumSub session.');\n }\n\n // Capture the flow generation so a `reset()` landing while the request is\n // in flight cannot write the result onto an idle controller.\n const generation = this.#generation;\n const sessionStatus = await this.messenger.call(\n 'KycService:getSessionStatus',\n { sessionId },\n );\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.sessionStatus = sessionStatus;\n });\n return sessionStatus;\n }\n\n /**\n * Begins polling the UKYC session status until a terminal decision is\n * reached. The first poll runs immediately (and is awaited by\n * {@link startSumSub}); subsequent polls are scheduled every\n * `#sessionStatusPollIntervalMs`.\n *\n * @param sessionId - The UKYC session id to poll.\n * @returns A promise that resolves once the first poll settles.\n */\n async #startSessionStatusPolling(sessionId: string): Promise<void> {\n // Supersede any prior loop and claim a fresh token for this one. Because\n // `#stopPolling` bumps the token, any in-flight poll from a previous loop\n // sees a mismatch and neither writes state nor reschedules.\n this.#stopPolling();\n const token = this.#pollToken;\n\n const tick = async (): Promise<void> => {\n const shouldStop = await this.#pollSessionStatusOnce(sessionId, token);\n if (shouldStop) {\n return;\n }\n this.#pollTimer = setTimeout(() => {\n this.#pollTimer = null;\n // `tick` swallows its own errors (see `#pollSessionStatusOnce`) and\n // therefore never rejects, so this fire-and-forget scheduled poll\n // cannot surface as an unhandled rejection.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n tick();\n }, this.#sessionStatusPollIntervalMs);\n };\n\n await tick();\n }\n\n /**\n * Performs a single session-status poll: fetches the status, records it, and\n * resolves the sub-flow when the status is terminal.\n *\n * Transient errors are swallowed so the loop keeps polling; the last good\n * `sessionStatus` is deliberately preserved rather than being overwritten\n * with the error.\n *\n * @param sessionId - The UKYC session id to poll.\n * @param token - The polling token captured when the loop started.\n * @returns `true` when the loop should stop (terminal status or superseded\n * by a reset / new sub-flow), `false` when it should keep polling.\n */\n async #pollSessionStatusOnce(\n sessionId: string,\n token: number,\n ): Promise<boolean> {\n try {\n const sessionStatus = await this.messenger.call(\n 'KycService:getSessionStatus',\n { sessionId },\n );\n // Superseded while the request was in flight — drop the result.\n if (this.#pollToken !== token) {\n return true;\n }\n const isTerminal = TERMINAL_SESSION_STATUSES.has(\n sessionStatus.finalStatus,\n );\n this.#applyUpdate((state) => {\n state.sumsub.sessionStatus = sessionStatus;\n if (isTerminal) {\n state.sumsub.status = SUCCESSFUL_SESSION_STATUSES.has(\n sessionStatus.finalStatus,\n )\n ? 'complete'\n : 'failed';\n }\n });\n if (isTerminal) {\n this.#stopPolling();\n }\n return isTerminal;\n } catch {\n // Keep polling on transient errors, preserving the last good status.\n // Stop only when a reset / new sub-flow superseded this loop.\n return this.#pollToken !== token;\n }\n }\n\n /**\n * Stops the session-status polling loop: bumps the polling token (so any\n * in-flight `tick` bows out) and clears any scheduled poll.\n */\n #stopPolling(): void {\n this.#pollToken += 1;\n if (this.#pollTimer !== null) {\n clearTimeout(this.#pollTimer);\n this.#pollTimer = null;\n }\n }\n\n /**\n * Resets the flow to idle, clearing session tokens and sub-flow state while\n * preserving persisted terms acceptance and the per-product cache.\n */\n reset(): void {\n this.#authClientToken = null;\n // Stop any session-status polling so a late poll cannot write onto the\n // now-idle controller.\n this.#stopPolling();\n // Invalidate any in-flight async work started before this reset so its\n // results are discarded rather than written onto the now-idle controller.\n this.#generation += 1;\n this.#applyUpdate((state) => {\n state.phase = 'idle';\n state.statusMessage = '';\n state.error = null;\n state.disclaimers = [];\n state.disclaimersError = null;\n state.sessionToken = null;\n state.accessToken = null;\n state.moonpayCustomerId = null;\n state.activeProduct = null;\n state.sumsub = {\n status: 'idle',\n result: null,\n sessionId: null,\n applicantAccessToken: null,\n sessionStatus: null,\n };\n });\n }\n\n /**\n * Applies a state update only when the flow has not been reset since\n * `generation` was captured. Prevents an in-flight async step from writing\n * stale results onto a controller that a concurrent {@link reset} has\n * returned to idle.\n *\n * @param generation - The flow generation captured before the async work.\n * @param updater - The state mutation to apply when still current.\n * @returns `true` if the update was applied, `false` if it was superseded.\n */\n #updateIfCurrent(\n generation: number,\n updater: (state: KycControllerState) => void,\n ): boolean {\n if (this.#generation !== generation) {\n return false;\n }\n this.#applyUpdate(updater);\n return true;\n }\n\n /**\n * The single state-update path for this controller. All mutations go through\n * here (rather than calling `this.update` directly) so the mechanism stays\n * consistent and one subtlety is handled in a single place:\n *\n * `sumsub.result` is typed as the recursive `Json`, and expanding\n * `Draft<Json>` (which happens whenever an updater touches `sumsub.result`)\n * can trip TypeScript's \"type instantiation is excessively deep\" guard. By\n * typing the callback parameter as the plain {@link KycControllerState}\n * instead of Immer's `Draft`, we avoid expanding the draft type while keeping\n * the same mutate-in-place semantics (the underlying value is still the Immer\n * draft at runtime).\n *\n * @param updater - The state mutation to apply.\n */\n #applyUpdate(updater: (state: KycControllerState) => void): void {\n this.update((state) => {\n // @ts-expect-error Avoid \"type instantiation is excessively deep\".\n updater(state);\n });\n }\n\n /**\n * Transitions to the error phase with a message.\n *\n * @param message - The error message.\n */\n #fail(message: string): void {\n this.#applyUpdate((state) => {\n state.error = message;\n state.phase = 'error';\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"KycController.mjs","sourceRoot":"","sources":["../src/KycController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAO3D,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAE/C,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,qBAAoB;AAElE,OAAO,EAAE,WAAW,EAAE,uBAAsB;AAe5C,OAAO,EAAE,oBAAoB,EAAE,wCAAuC;AACtE,OAAO,EAAE,cAAc,EAAE,4BAA2B;AACpD,OAAO,EAAE,0BAA0B,EAAE,mCAAkC;AAEvE,OAAO,EAAE,sBAAsB,EAAE,sCAAqC;AACtE,OAAO,EAAE,iBAAiB,EAAE,qCAAoC;AAEhE,kBAAkB;AAElB,MAAM,CAAC,MAAM,cAAc,GAAG,eAAe,CAAC;AAE9C,MAAM,eAAe,GAAG,wCAAwC,CAAC;AACjE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ata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n UserStorageControllerPerformGetStorageAction,\n UserStorageControllerPerformSetStorageAction,\n} from '@metamask/profile-sync-controller/user-storage';\nimport type { Json } from '@metamask/utils';\nimport { x25519 } from '@noble/curves/ed25519';\n\nimport { decryptCredentials, generateKeyPair } from './crypto.js';\nimport type { EncryptedCredentialsEnvelope, X25519KeyPair } from './crypto.js';\nimport { toBase64Url } from './encoding.js';\nimport type { KycControllerMethodActions } from './KycController-method-action-types.js';\nimport type { KycServiceMethodActions } from './KycService-method-action-types.js';\nimport type { CreateUkycSessionParams } from './KycService.js';\nimport type {\n KycCustomerIdentity,\n KycDisclaimer,\n KycPhase,\n KycProduct,\n KycSessionStatus,\n KycSumSubLauncher,\n KycSumSubStatus,\n KycUserStatus,\n KycVendor,\n} from './types.js';\nimport { deriveClientMaterial } from './ukyc/deriveClientMaterial.js';\nimport { verifyJwtChain } from './ukyc/jwtChain.js';\nimport { getOrCreateLocalUserSecret } from './ukyc/localUserSecret.js';\nimport type { UkycLocalUserSecretStore } from './ukyc/localUserSecret.js';\nimport { signStorageAccessToken } from './ukyc/storageAccessToken.js';\nimport { wrapEncryptionKey } from './ukyc/wrapEncryptionKey.js';\n\n// === GENERAL ===\n\nexport const controllerName = 'KycController';\n\nconst FRAMES_BASE_URL = 'https://blocks.moonpay.com/platform/v1';\nconst CHANNEL_CHECK = 'ch_1';\nconst CHANNEL_AUTH = 'ch_2';\nconst CHANNEL_RESET = 'ch_reset';\n\n// Placeholder credentials for the SumSub sub-flow. These are demo values that\n// must be replaced with real UKYC-issued material before production use.\nconst MOCK_JWT_TOKEN = 'mock-jwt-token';\n\n// Lifetime of the read-only `ukyc_capability_token` minted when creating a\n// UKYC session. The storage-and-auth spec requires the token's `expires_at` to\n// cover the KYC session's expected lifetime — including the provider journey —\n// rather than a fixed short window, so this is a session-scoped window.\nconst UKYC_CAPABILITY_TOKEN_TTL_MS = 4 * 60 * 60 * 1000;\n\n// The SumSub SDK status that signals the applicant finished the flow\n// successfully. Any other resolution (abandonment, failure, or a non-success\n// outcome) must not be recorded as `complete`.\nconst SUMSUB_COMPLETED_STATUS = 'Completed';\n\n// Phases that represent an active vendor-session flow (tokens issued and/or\n// Check/Auth frames in progress). A repeat `initialize` while in one of these\n// must not restart the session and disrupt the in-flight flow.\nconst IN_PROGRESS_PHASES: KycPhase[] = [\n 'session',\n 'check',\n 'auth',\n 'form',\n 'submit',\n];\n\n// How often to poll the UKYC session status after the SumSub SDK completes,\n// until a terminal status is reached. Overridable via the constructor.\nconst DEFAULT_SESSION_STATUS_POLL_INTERVAL_MS = 15_000;\n\n// UKYC status values. `kycStatus` (the relay-side decision) and `finalStatus`\n// (the vendor-side outcome) draw from the same vocabulary, so they are defined\n// once here and composed into the sets/checks below rather than repeated as\n// literals.\nconst KYC_STATUSES = {\n approved: 'approved',\n completed: 'completed',\n rejected: 'rejected',\n failed: 'failed',\n blocked: 'blocked',\n pending: 'pending',\n} as const;\n\n// `finalStatus` values that end the polling loop. Anything else (e.g.\n// `KYC_STATUSES.pending`) keeps polling.\nconst TERMINAL_SESSION_STATUSES: ReadonlySet<string> = new Set([\n KYC_STATUSES.approved,\n KYC_STATUSES.completed,\n KYC_STATUSES.rejected,\n KYC_STATUSES.failed,\n KYC_STATUSES.blocked,\n]);\n\n// Terminal `finalStatus` values that represent a successful verification. Any\n// other terminal status resolves the sub-flow to `failed`.\nconst SUCCESSFUL_SESSION_STATUSES: ReadonlySet<string> = new Set([\n KYC_STATUSES.approved,\n KYC_STATUSES.completed,\n]);\n\n// Session creation can report that the applicant is already approved on the\n// relay (`kycStatus === KYC_STATUSES.approved`) while the vendor is still\n// finalizing its decision (`finalStatus === KYC_STATUSES.pending`, a\n// non-terminal status). In that case there is nothing left for the applicant\n// to do, so the sub-flow stops before launching the SDK and surfaces this\n// message.\nconst VENDOR_PROCESSING_MESSAGE =\n 'Your KYC has been submitted and is being processed by the vendor.';\n\n// UKYC / relay error indicating the applicant already finished KYC. Mapped to\n// the simplified `completed` user status for the Money toast surface.\nconst SESSION_NOT_IN_VALID_STATE = 'session_not_in_valid_state';\n\n// How often to refresh the user-keyed `GET /kyc/status` while the simplified\n// status is still `pending`. Overridable via the constructor.\nconst DEFAULT_USER_STATUS_POLL_INTERVAL_MS = 15_000;\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link KycController}.\n */\nexport type KycControllerState = {\n /** Current phase of the identity flow. */\n phase: KycPhase;\n /** Human-readable status message for the current phase. */\n statusMessage: string;\n /** The current error message, or `null`. */\n error: string | null;\n\n /** Email associated with the session (sourced from the account). */\n email: string | null;\n\n /** ISO-8601 timestamp of the customer's terms acceptance (persisted). */\n termsAcceptedAt: string | null;\n /** IDs of the disclaimers the customer accepted (persisted). */\n acceptedDisclaimerIds: string[];\n /**\n * The vendor whose disclaimers `acceptedDisclaimerIds` belong to (persisted).\n * Each vendor serves its own disclaimer set, so acceptance recorded for one\n * vendor must not be reused for another. `null` when nothing is accepted.\n */\n termsAcceptedVendor: KycVendor | null;\n /**\n * Whether the customer accepted the SumSub T&C (T&C2) during the last\n * terms acceptance (persisted). Consents-path vendors require this flag\n * when resuming a session. `null` for acceptance recorded before this\n * field existed (treated as requiring reacceptance).\n */\n sumsubTncAccepted: boolean | null;\n /**\n * Whether the customer accepted the idOS T&C (T&C2) during the last\n * terms acceptance (persisted). Consents-path vendors require this flag\n * when resuming a session. `null` for acceptance recorded before this\n * field existed (treated as requiring reacceptance).\n */\n idosTncAccepted: boolean | null;\n\n /** Disclaimers fetched for the current country. */\n disclaimers: KycDisclaimer[];\n /** Error encountered while loading disclaimers, or `null`. */\n disclaimersError: string | null;\n\n /** Resolved ISO 3166-1 alpha-3 country code. */\n geoCountry: string | null;\n\n /** Vendor session token (not persisted, not logged). */\n sessionToken: string | null;\n /** Vendor access token (not persisted, not logged). */\n accessToken: string | null;\n /** Vendor customer id, used for the SumSub hand-off. */\n moonpayCustomerId: string | null;\n\n /**\n * The identity vendor driving the current flow. Captured at `initialize`.\n * Defaults to `moonpay` when omitted so existing ramps/card callers keep\n * the Check/Auth frame path. Non-MoonPay vendors skip those frames.\n */\n activeVendor: KycVendor;\n\n /**\n * The product the current flow is running for. Captured at `initialize`\n * (or `acceptTermsAndStartSession`) and used to automatically run the\n * KYC-required check once authentication completes. `null` outside a\n * product-scoped flow (in which case the flow stops at `form` and the\n * consumer drives the check manually).\n */\n activeProduct: KycProduct | null;\n\n /** Cached \"is KYC required\" result per product (persisted). */\n kycRequiredByProduct: Partial<Record<KycProduct, boolean>>;\n /** ISO-8601 timestamp of the last KYC-required check (persisted). */\n lastCheckedAt: string | null;\n\n /**\n * User-keyed simplified KYC status from `GET /kyc/status` (persisted so the\n * Money toast can render across cold starts). `null` until the first\n * successful `refreshKycStatus`.\n */\n userStatus: KycUserStatus | null;\n /** Optional SumSub session id for the retryable error path. */\n userStatusSumsubSessionId: string | null;\n /** Optional machine-readable error code for terminal / EDD UX. */\n userStatusErrorCode: string | null;\n\n /** SumSub document-verification sub-flow state. */\n sumsub: {\n status: KycSumSubStatus;\n result: Json | null;\n sessionId: string | null;\n applicantAccessToken: string | null;\n /**\n * The latest UKYC session status, populated while polling after the SDK\n * completes. `null` until the first successful poll.\n */\n sessionStatus: KycSessionStatus | null;\n };\n};\n\nconst kycControllerMetadata = {\n phase: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n statusMessage: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n error: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n email: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: false,\n },\n termsAcceptedAt: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: false,\n },\n acceptedDisclaimerIds: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: false,\n },\n termsAcceptedVendor: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: false,\n },\n sumsubTncAccepted: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: false,\n },\n idosTncAccepted: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: false,\n },\n disclaimers: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: true,\n },\n disclaimersError: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n geoCountry: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n sessionToken: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: false,\n },\n accessToken: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: false,\n },\n moonpayCustomerId: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: false,\n },\n activeVendor: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n activeProduct: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n kycRequiredByProduct: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: true,\n },\n lastCheckedAt: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: false,\n },\n userStatus: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: true,\n },\n userStatusSumsubSessionId: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: true,\n usedInUi: true,\n },\n userStatusErrorCode: {\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n persist: true,\n usedInUi: true,\n },\n sumsub: {\n includeInDebugSnapshot: false,\n includeInStateLogs: false,\n persist: false,\n usedInUi: true,\n },\n} satisfies StateMetadata<KycControllerState>;\n\n/**\n * Constructs the default {@link KycController} state.\n *\n * @returns The default state.\n */\nexport function getDefaultKycControllerState(): KycControllerState {\n return {\n phase: 'idle',\n statusMessage: '',\n error: null,\n email: null,\n termsAcceptedAt: null,\n acceptedDisclaimerIds: [],\n termsAcceptedVendor: null,\n sumsubTncAccepted: null,\n idosTncAccepted: null,\n disclaimers: [],\n disclaimersError: null,\n geoCountry: null,\n sessionToken: null,\n accessToken: null,\n moonpayCustomerId: null,\n activeVendor: 'moonpay',\n activeProduct: null,\n kycRequiredByProduct: {},\n lastCheckedAt: null,\n userStatus: null,\n userStatusSumsubSessionId: null,\n userStatusErrorCode: null,\n sumsub: {\n status: 'idle',\n result: null,\n sessionId: null,\n applicantAccessToken: null,\n sessionStatus: null,\n },\n };\n}\n\n/**\n * Whether an error indicates the applicant already finished KYC — the UKYC /\n * relay `session_not_in_valid_state` signal — which the controller maps to the\n * simplified `completed` user status.\n *\n * @param error - The caught error.\n * @returns `true` when the error carries the `session_not_in_valid_state`\n * marker.\n */\nfunction isSessionAlreadyCompletedError(error: unknown): boolean {\n return String(error).includes(SESSION_NOT_IN_VALID_STATE);\n}\n\n/**\n * Vendors other than MoonPay skip Check/Auth frames and use the empty-shell\n * customer + consents path instead.\n *\n * @param vendor - The identity vendor for the current flow.\n * @returns `true` when the vendor uses the consents session path.\n */\nfunction usesConsentsFlow(vendor: KycVendor): boolean {\n return vendor !== 'moonpay';\n}\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'initialize',\n 'loadDisclaimers',\n 'acceptTermsAndStartSession',\n 'createVendorCustomer',\n 'clearSavedTerms',\n 'handleFrameMessage',\n 'buildCheckFrameUrl',\n 'buildAuthFrameUrl',\n 'buildResetFrameUrl',\n 'checkKycRequired',\n 'getKycStatus',\n 'getCustomerIdentity',\n 'refreshKycStatus',\n 'startSumSub',\n 'getSessionStatus',\n 'reset',\n] as const;\n\nexport type KycControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n KycControllerState\n>;\n\nexport type KycControllerActions =\n | KycControllerGetStateAction\n | KycControllerMethodActions;\n\ntype AllowedActions =\n | KycServiceMethodActions\n | UserStorageControllerPerformGetStorageAction\n | UserStorageControllerPerformSetStorageAction;\n\nexport type KycControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n KycControllerState\n>;\n\n/**\n * Published when the user-keyed simplified KYC status changes (Money toast).\n */\nexport type KycControllerStatusChangedEvent = {\n type: `${typeof controllerName}:statusChanged`;\n payload: [\n {\n status: KycUserStatus;\n sumsubSessionId: string | null;\n errorCode: string | null;\n },\n ];\n};\n\nexport type KycControllerEvents =\n | KycControllerStateChangeEvent\n | KycControllerStatusChangedEvent;\n\ntype AllowedEvents = never;\n\nexport type KycControllerMessenger = Messenger<\n typeof controllerName,\n KycControllerActions | AllowedActions,\n KycControllerEvents | AllowedEvents\n>;\n\n/**\n * Options for constructing a {@link KycController}.\n */\nexport type KycControllerOptions = {\n messenger: KycControllerMessenger;\n state?: Partial<KycControllerState>;\n /**\n * Platform adapter that presents the SumSub SDK. Injected by each client so\n * the controller stays platform-agnostic.\n */\n sumsubLauncher: KycSumSubLauncher;\n /**\n * How often, in milliseconds, to poll the UKYC session status after the\n * SumSub SDK completes. Defaults to\n * {@link DEFAULT_SESSION_STATUS_POLL_INTERVAL_MS}.\n */\n sessionStatusPollIntervalMs?: number;\n /**\n * How often, in milliseconds, to refresh `GET /kyc/status` while the\n * simplified user status is `pending`. Defaults to\n * {@link DEFAULT_USER_STATUS_POLL_INTERVAL_MS}.\n */\n userStatusPollIntervalMs?: number;\n};\n\n/**\n * The shape of a message posted by a Check/Auth frame.\n */\ntype FrameMessage = {\n meta?: { channelId?: string };\n kind?: string;\n payload?: {\n status?:\n | 'active'\n | 'connectionRequired'\n | 'termsAcceptanceRequired'\n | 'pending'\n | 'unavailable'\n | 'failed';\n credentials?: EncryptedCredentialsEnvelope | string;\n customer?: { id?: string };\n };\n};\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * `KycController` orchestrates the vendor-backed KYC / identity-verification\n * flow (MoonPay identity + SumSub documents) behind a vendor-neutral, per\n * product surface used by ramps and card. It owns all state, HTTP\n * orchestration (via `KycService`), crypto, and the frame message protocol;\n * platform-specific presentation (WebView/iframe, SumSub SDK) is injected.\n */\nexport class KycController extends BaseController<\n typeof controllerName,\n KycControllerState,\n KycControllerMessenger\n> {\n readonly #sumsubLauncher: KycSumSubLauncher;\n\n /** Ephemeral X25519 keypair for the frame key exchange (never persisted). */\n readonly #keypair: X25519KeyPair;\n\n /** Auth-frame client token, kept out of state. */\n #authClientToken: string | null = null;\n\n /**\n * Monotonic flow generation. Incremented by {@link reset} so in-flight async\n * work (e.g. the KYC-required check) can detect that it was superseded and\n * avoid writing stale results onto a reset controller.\n */\n #generation = 0;\n\n /** Interval, in milliseconds, between session-status polls. */\n readonly #sessionStatusPollIntervalMs: number;\n\n /** Handle for the scheduled next session-status poll, or `null`. */\n #pollTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * Monotonic polling token. Bumped by {@link #stopPolling} (called on reset, a\n * new sub-flow, and once a terminal status is reached) so an in-flight poll\n * `tick` can detect it was superseded and neither write state nor schedule a\n * follow-up. This closes the gap where clearing the timer alone would still\n * let an already-awaiting request finish and reschedule.\n */\n #pollToken = 0;\n\n /** Interval, in milliseconds, between user-keyed status polls. */\n readonly #userStatusPollIntervalMs: number;\n\n /** Handle for the scheduled next user-status poll, or `null`. */\n #userStatusPollTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * Whether a user-status poll loop is currently active. Tracked separately\n * from {@link #userStatusPollTimer} because a scheduled tick clears the timer\n * handle before awaiting `fetchKycStatus`; relying on the handle alone would\n * let a concurrent {@link refreshKycStatus} start a second loop on the same\n * token during that in-flight window.\n */\n #userStatusPolling = false;\n\n /** Monotonic token for the user-status poll loop (see `#pollToken`). */\n #userStatusPollToken = 0;\n\n /**\n * Constructs a new {@link KycController}.\n *\n * @param options - The constructor options.\n * @param options.messenger - The messenger suited for this controller.\n * @param options.state - Partial initial state; merged over defaults.\n * @param options.sumsubLauncher - The platform SumSub launcher adapter.\n * @param options.sessionStatusPollIntervalMs - How often to poll the UKYC\n * session status after the SumSub SDK completes.\n * @param options.userStatusPollIntervalMs - How often to refresh the\n * user-keyed KYC status while it is still `pending`.\n */\n constructor({\n messenger,\n state,\n sumsubLauncher,\n sessionStatusPollIntervalMs = DEFAULT_SESSION_STATUS_POLL_INTERVAL_MS,\n userStatusPollIntervalMs = DEFAULT_USER_STATUS_POLL_INTERVAL_MS,\n }: KycControllerOptions) {\n super({\n messenger,\n metadata: kycControllerMetadata,\n name: controllerName,\n state: { ...getDefaultKycControllerState(), ...state },\n });\n\n this.#sumsubLauncher = sumsubLauncher;\n this.#sessionStatusPollIntervalMs = sessionStatusPollIntervalMs;\n this.#userStatusPollIntervalMs = userStatusPollIntervalMs;\n this.#keypair = generateKeyPair();\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Builds an adapter over `UserStorageController` that the platform-agnostic\n * `getOrCreateLocalUserSecret` helper uses to persist/load the UKYC\n * `local_user_secret`.\n *\n * @returns The Encrypted User Storage adapter.\n */\n #localUserSecretStore(): UkycLocalUserSecretStore {\n return {\n get: async (\n path: string,\n entropySourceId?: string,\n ): Promise<string | null> =>\n this.messenger.call(\n 'UserStorageController:performGetStorage',\n path as `${string}.${string}`,\n entropySourceId,\n ),\n set: async (\n path: string,\n value: string,\n entropySourceId?: string,\n ): Promise<void> =>\n this.messenger.call(\n 'UserStorageController:performSetStorage',\n path as `${string}.${string}`,\n value,\n entropySourceId,\n ),\n };\n }\n\n /**\n * Resolves persisted terms + geolocation, and auto-creates a session when\n * terms are already accepted and an email is available.\n *\n * @param params - Optional parameters.\n * @param params.email - The account email to associate with the session.\n * @param params.product - The consuming feature the flow runs for. When\n * provided, the controller automatically runs the KYC-required check once\n * authentication completes (and chains into document verification when KYC\n * is required). When omitted, the flow stops at `form` and the consumer must\n * call `checkKycRequired` manually.\n * @param params.vendor - Identity vendor for this flow. Non-MoonPay vendors\n * skip Check/Auth frames and use the consents path. Defaults to `moonpay`.\n */\n async initialize(params?: {\n email?: string;\n product?: KycProduct;\n vendor?: KycVendor;\n }): Promise<void> {\n // A repeat `initialize` while a session flow is already in progress must\n // not tear it down: creating a new vendor session clears the tokens and\n // forces `phase` back through `session`/`check`, breaking an in-flight\n // Check/Auth frame flow. Leave the active flow untouched and let the\n // consumer drive it (or call `reset` first to start over).\n if (IN_PROGRESS_PHASES.includes(this.state.phase)) {\n return;\n }\n\n const vendor = params?.vendor ?? 'moonpay';\n\n // `initialize` starts a fresh flow, so `activeProduct` is always reset to\n // this call's product (or `null`). Otherwise a prior run's product could\n // linger and cause `#continueAfterAuthentication` to auto-run the check /\n // sub-flow when the caller intended the manual (product-less) flow.\n this.#applyUpdate((state) => {\n if (params?.email) {\n state.email = params.email;\n }\n // Terms acceptance is vendor-scoped: reusing another vendor's saved\n // acceptance would skip loading this vendor's disclaimers and submit its\n // ids to the wrong vendor.\n if (!this.#hasTermsForVendor(vendor)) {\n this.#clearAcceptedTerms(state);\n }\n state.activeVendor = vendor;\n // `moonpayCustomerId` is only ever issued by the MoonPay Check / Auth\n // frames. Leaving it set while the flow switches to another vendor would\n // make `getCustomerIdentity` report a MoonPay id under the wrong vendor.\n if (vendor !== 'moonpay') {\n state.moonpayCustomerId = null;\n }\n state.activeProduct = params?.product ?? null;\n });\n\n // Capture the flow generation so a `reset()` landing while the async\n // geolocation / session steps below are in flight cannot write results\n // onto an idle controller.\n const generation = this.#generation;\n\n // Resolve country for display; non-blocking.\n try {\n const country = await this.messenger.call('KycService:getGeoCountry');\n this.#updateIfCurrent(generation, (state) => {\n state.geoCountry = country;\n });\n } catch {\n // Ignore; disclaimers loading will surface a country error if needed.\n }\n\n if (usesConsentsFlow(vendor) && this.state.email) {\n try {\n await this.messenger.call('KycService:createVendorCustomer', {\n vendor,\n email: this.state.email,\n });\n if (this.#generation !== generation) {\n return;\n }\n } catch (error) {\n if (this.#generation !== generation) {\n return;\n }\n this.#fail(`Vendor customer creation failed: ${String(error)}`);\n return;\n }\n }\n\n const hasTerms =\n Boolean(this.state.termsAcceptedAt) &&\n this.state.acceptedDisclaimerIds.length > 0;\n\n if (hasTerms && this.state.email) {\n if (usesConsentsFlow(vendor)) {\n // Consents-path vendors require T&C2 flags; if they weren't persisted\n // (i.e. null from pre-migration state), require reacceptance.\n const sumsubTncSigned = this.state.sumsubTncAccepted;\n const idosTncSigned = this.state.idosTncAccepted;\n if (sumsubTncSigned === null || idosTncSigned === null) {\n this.#applyUpdate((state) => {\n this.#clearAcceptedTerms(state);\n state.phase = 'terms';\n });\n await this.loadDisclaimers();\n return;\n }\n await this.#startConsentsSession({\n sumsubTncSigned,\n idosTncSigned,\n });\n } else {\n await this.#createSession();\n }\n return;\n }\n\n this.#applyUpdate((state) => {\n state.phase = 'terms';\n });\n await this.loadDisclaimers();\n }\n\n /**\n * Creates (or resumes) an empty-shell customer for the given identity\n * vendor. Exposed so a consumer can ensure the customer exists before\n * showing T&C screens independently of {@link initialize}.\n *\n * @param params - The parameters.\n * @param params.vendor - Identity vendor for the customer.\n * @param params.email - Email for the vendor customer.\n */\n async createVendorCustomer(params: {\n vendor: KycVendor;\n email: string;\n }): Promise<void> {\n this.#applyUpdate((state) => {\n state.email = params.email;\n // See `initialize`: acceptance recorded for another vendor cannot carry\n // over, and a MoonPay-issued customer id must not survive a switch to\n // another vendor or `getCustomerIdentity` reports the wrong vendor.\n if (!this.#hasTermsForVendor(params.vendor)) {\n this.#clearAcceptedTerms(state);\n }\n state.activeVendor = params.vendor;\n if (params.vendor !== 'moonpay') {\n state.moonpayCustomerId = null;\n }\n });\n const generation = this.#generation;\n try {\n await this.messenger.call('KycService:createVendorCustomer', {\n vendor: params.vendor,\n email: params.email,\n });\n } catch (error) {\n if (this.#generation !== generation) {\n return;\n }\n this.#fail(`Vendor customer creation failed: ${String(error)}`);\n }\n }\n\n /**\n * Loads the disclaimers for the resolved (or provided) country.\n *\n * @param params - Optional parameters.\n * @param params.country - ISO 3166-1 alpha-3 country code override.\n */\n async loadDisclaimers(params?: { country?: string }): Promise<void> {\n // Capture the flow generation so a `reset()` landing while the geo /\n // disclaimers requests are in flight cannot write results onto an idle\n // controller.\n const generation = this.#generation;\n try {\n const country =\n params?.country ??\n this.state.geoCountry ??\n (await this.messenger.call('KycService:getGeoCountry'));\n if (country !== this.state.geoCountry) {\n this.#updateIfCurrent(generation, (state) => {\n state.geoCountry = country;\n });\n }\n const disclaimers = await this.messenger.call(\n 'KycService:fetchDisclaimers',\n {\n vendor: this.state.activeVendor,\n country,\n },\n );\n this.#updateIfCurrent(generation, (state) => {\n state.disclaimers = disclaimers;\n state.disclaimersError = null;\n });\n } catch (error) {\n this.#updateIfCurrent(generation, (state) => {\n state.disclaimersError = `Failed to load disclaimers: ${String(error)}`;\n });\n }\n }\n\n /**\n * Captures terms acceptance for the currently loaded disclaimers and creates\n * a session.\n *\n * @param params - The parameters.\n * @param params.email - The account email to associate with the session.\n * @param params.product - The consuming feature the flow runs for. See\n * {@link initialize} for how the product drives the automatic post\n * authentication continuation.\n * @param params.sumsubTncSigned - Whether Sumsub T&C were accepted (T&C2).\n * Required for every vendor so callers explicitly declare acceptance.\n * @param params.idosTncSigned - Whether idOS T&C were accepted (T&C2).\n * Required for every vendor so callers explicitly declare acceptance.\n */\n async acceptTermsAndStartSession(params: {\n email?: string;\n product?: KycProduct;\n sumsubTncSigned: boolean;\n idosTncSigned: boolean;\n }): Promise<void> {\n const sumsubTncSigned = params?.sumsubTncSigned;\n const idosTncSigned = params?.idosTncSigned;\n if (\n typeof sumsubTncSigned !== 'boolean' ||\n typeof idosTncSigned !== 'boolean'\n ) {\n this.#fail('Missing T&C2 acceptance flags.');\n return;\n }\n\n const termsAcceptedAt = new Date().toISOString();\n const disclaimerIds = this.state.disclaimers.map(\n (disclaimer) => disclaimer.id,\n );\n this.#applyUpdate((state) => {\n if (params.email) {\n state.email = params.email;\n }\n if (params.product) {\n state.activeProduct = params.product;\n }\n state.termsAcceptedAt = termsAcceptedAt;\n state.acceptedDisclaimerIds = disclaimerIds;\n state.termsAcceptedVendor = state.activeVendor;\n state.sumsubTncAccepted = sumsubTncSigned;\n state.idosTncAccepted = idosTncSigned;\n });\n if (usesConsentsFlow(this.state.activeVendor)) {\n await this.#startConsentsSession({ sumsubTncSigned, idosTncSigned });\n return;\n }\n await this.#createSession();\n }\n\n /**\n * Consents-path vendors: post vendor signings + Sumsub/idOS ack, then\n * launch SumSub — skipping MoonPay Check/Auth frames.\n *\n * @param consents - T&C2 boolean flags.\n * @param consents.sumsubTncSigned - Whether Sumsub T&C were accepted.\n * @param consents.idosTncSigned - Whether idOS T&C were accepted.\n */\n async #startConsentsSession(consents: {\n sumsubTncSigned: boolean;\n idosTncSigned: boolean;\n }): Promise<void> {\n const { email, acceptedDisclaimerIds } = this.state;\n if (!email) {\n this.#fail('Missing email for consents session.');\n return;\n }\n if (acceptedDisclaimerIds.length === 0) {\n this.#fail('Missing disclaimer acceptance.');\n return;\n }\n\n const generation = this.#generation;\n this.#applyUpdate((state) => {\n state.error = null;\n state.phase = 'session';\n state.statusMessage = 'Submitting consents...';\n // Consents-path vendors have no MoonPay session/access tokens.\n state.sessionToken = null;\n state.accessToken = null;\n });\n\n try {\n await this.messenger.call('KycService:submitConsents', {\n disclaimerIds: acceptedDisclaimerIds,\n sumsubTncSigned: consents.sumsubTncSigned,\n idosTncSigned: consents.idosTncSigned,\n });\n if (this.#generation !== generation) {\n return;\n }\n this.#applyUpdate((state) => {\n state.phase = 'submit';\n state.statusMessage = 'Starting document verification...';\n });\n const sumsubResult = await this.startSumSub();\n if (this.#generation !== generation) {\n return;\n }\n const sumsubError = sumsubResult?.error;\n if (typeof sumsubError === 'string') {\n throw new Error(sumsubError);\n }\n // After SumSub, refresh user-keyed status for the Money toast and start\n // polling while still pending. Soft-fail: toast refresh must not rewind\n // the consent / SumSub outcome.\n try {\n await this.refreshKycStatus();\n } catch (statusError) {\n console.error('KYC status refresh failed:', statusError);\n }\n this.#updateIfCurrent(generation, (state) => {\n if (state.phase !== 'error' && state.phase !== 'done') {\n state.phase = 'done';\n state.statusMessage = 'KYC submitted.';\n }\n });\n } catch (error) {\n console.error('Consents session failed:', error);\n if (this.#generation !== generation) {\n return;\n }\n this.#applyUpdate((state) => {\n this.#clearAcceptedTerms(state);\n state.activeProduct = null;\n state.error = `Consents session failed: ${String(error)}`;\n state.statusMessage =\n 'Consent / verification failed — accept the terms to try again.';\n state.phase = 'terms';\n });\n await this.loadDisclaimers();\n }\n }\n\n /**\n * Creates a vendor session from the currently stored terms + email.\n */\n async #createSession(): Promise<void> {\n const { email, termsAcceptedAt, acceptedDisclaimerIds } = this.state;\n if (!email) {\n this.#fail('Missing email for session creation.');\n return;\n }\n if (!termsAcceptedAt || acceptedDisclaimerIds.length === 0) {\n this.#fail('Missing terms acceptance for session creation.');\n return;\n }\n\n // A new session invalidates any authentication carried over from a prior\n // session. Clear the stale session token, access token, and auth-frame\n // client token so `buildCheckFrameUrl` cannot return a URL bound to an old\n // (or, on failure, invalid) session token, `buildAuthFrameUrl` cannot\n // return a URL tied to an old client token, and `checkKycRequired` cannot\n // run with an access token from an earlier authentication. The Check/Auth\n // frames re-populate these for the new session. Because `sessionToken` is\n // cleared here and only re-set on success, a failed creation leaves it\n // `null` rather than resurrecting the previous session.\n // Capture the flow generation so a `reset()` landing while the create\n // request is in flight cannot resurrect a session (success) or overwrite\n // the now-idle controller (failure). The synchronous update below runs\n // before any `await`, so it needs no guard.\n const generation = this.#generation;\n this.#authClientToken = null;\n this.#applyUpdate((state) => {\n state.error = null;\n state.phase = 'session';\n state.statusMessage = 'Creating session...';\n state.sessionToken = null;\n state.accessToken = null;\n });\n\n try {\n const { sessionToken } = await this.messenger.call(\n 'KycService:createSession',\n { email, termsAcceptedAt, disclaimerIds: acceptedDisclaimerIds },\n );\n this.#updateIfCurrent(generation, (state) => {\n state.sessionToken = sessionToken;\n state.phase = 'check';\n state.statusMessage = 'Authenticating via Check frame...';\n });\n } catch (error) {\n console.error('Session creation failed:', error);\n // A reset() superseded this flow while the request was in flight; leave\n // the idle controller alone rather than forcing it back to `terms`.\n if (this.#generation !== generation) {\n return;\n }\n // Invalidate the stored acceptance so the customer can retry. Also clear\n // `activeProduct` so a later `acceptTermsAndStartSession` that omits a\n // product cannot auto-run the KYC check / SumSub chain for this failed\n // flow's product — matching how `initialize` starts from a clean product.\n this.#applyUpdate((state) => {\n this.#clearAcceptedTerms(state);\n state.activeProduct = null;\n state.error = `Session creation failed: ${String(error)}`;\n state.statusMessage =\n 'Session creation failed — accept the terms to try again.';\n state.phase = 'terms';\n });\n await this.loadDisclaimers();\n }\n }\n\n /**\n * Clears the persisted terms acceptance.\n */\n clearSavedTerms(): void {\n this.#applyUpdate((state) => {\n this.#clearAcceptedTerms(state);\n });\n }\n\n /**\n * Clears the stored terms acceptance on the given draft state. Shared by the\n * paths that must invalidate acceptance — explicit clear, vendor terms\n * update, and session-creation failure — so they stay in sync. This is a\n * targeted invalidation and, unlike {@link reset}, deliberately leaves the\n * rest of the flow (geolocation, disclaimers, phase) untouched.\n *\n * @param state - The state to mutate.\n */\n #clearAcceptedTerms(state: KycControllerState): void {\n state.termsAcceptedAt = null;\n state.acceptedDisclaimerIds = [];\n state.termsAcceptedVendor = null;\n state.sumsubTncAccepted = null;\n state.idosTncAccepted = null;\n }\n\n /**\n * Determines whether the stored terms acceptance belongs to the given\n * vendor. Acceptance persisted before `termsAcceptedVendor` existed\n * (indicated by `null`) is invalidated to force reacceptance, ensuring users\n * re-review vendor terms after the multi-vendor upgrade.\n *\n * @param vendor - The vendor about to drive the flow.\n * @returns `true` when the stored acceptance can be reused for `vendor`.\n */\n #hasTermsForVendor(vendor: KycVendor): boolean {\n if (this.state.termsAcceptedVendor === null) {\n return false;\n }\n return this.state.termsAcceptedVendor === vendor;\n }\n\n /**\n * Handles a message posted by a Check/Auth frame and advances the flow.\n *\n * The transport-agnostic caller (WebView on mobile, iframe on web) forwards\n * the raw message and injects the returned `reply` back into the frame.\n *\n * @param params - The parameters.\n * @param params.message - The raw message posted by the frame.\n * @returns An object whose optional `reply` should be posted back.\n */\n async handleFrameMessage(params: {\n message: unknown;\n }): Promise<{ reply?: unknown }> {\n const payload = params.message as FrameMessage | undefined;\n\n if (!payload) {\n return {};\n }\n\n if (payload.kind === 'handshake') {\n const channelId = payload.meta?.channelId;\n return { reply: { version: 2, meta: { channelId }, kind: 'ack' } };\n }\n\n if (payload.kind !== 'complete') {\n return {};\n }\n\n const channelId = payload.meta?.channelId;\n\n // Only honor a Check/Auth `complete` for the frame the flow is currently\n // waiting on. This drops stale or duplicate messages — e.g. a late post\n // after `reset()` (phase `idle`) or after the flow already advanced past\n // this frame — so they cannot resurrect tokens or rewind `phase` on a\n // controller that has moved on. Frame messages are external input and,\n // unlike the async steps, are not covered by the `#generation` guard.\n let expectedPhase: KycPhase | null = null;\n if (channelId === CHANNEL_CHECK) {\n expectedPhase = 'check';\n } else if (channelId === CHANNEL_AUTH) {\n expectedPhase = 'auth';\n }\n if (!expectedPhase || this.state.phase !== expectedPhase) {\n return {};\n }\n\n const status = payload.payload?.status;\n const credsEnvelope = payload.payload?.credentials;\n\n const customerId = payload.payload?.customer?.id ?? null;\n if (customerId) {\n this.#applyUpdate((state) => {\n state.moonpayCustomerId = customerId;\n });\n }\n\n if (!status) {\n return {};\n }\n\n let accessToken: string | undefined;\n let clientToken: string | undefined;\n if (credsEnvelope) {\n try {\n const { credentials } = decryptCredentials(\n credsEnvelope,\n this.#keypair.privateKey,\n );\n accessToken = credentials.accessToken;\n clientToken = credentials.clientToken;\n } catch (error) {\n this.#fail(`Failed to decrypt frame credentials: ${String(error)}`);\n return {};\n }\n }\n\n if (channelId === CHANNEL_CHECK) {\n await this.#handleCheckOutcome(status, accessToken, clientToken);\n return {};\n }\n\n // channelId === CHANNEL_AUTH, guaranteed by the expectedPhase guard above.\n await this.#handleAuthOutcome(status, accessToken);\n return {};\n }\n\n /**\n * Applies a Check-frame outcome.\n *\n * @param status - The frame status.\n * @param accessToken - The decrypted access token, if any.\n * @param clientToken - The decrypted client token, if any.\n */\n async #handleCheckOutcome(\n status: NonNullable<FrameMessage['payload']>['status'],\n accessToken?: string,\n clientToken?: string,\n ): Promise<void> {\n if (status === 'active' && accessToken) {\n this.#applyUpdate((state) => {\n state.accessToken = accessToken;\n state.phase = 'form';\n state.statusMessage = 'Already authenticated. Review to submit.';\n });\n await this.#continueAfterAuthentication();\n return;\n }\n if (status === 'connectionRequired' && clientToken) {\n this.#authClientToken = clientToken;\n this.#applyUpdate((state) => {\n state.phase = 'auth';\n state.statusMessage = 'Verify your email via OTP in the Auth frame.';\n });\n return;\n }\n if (status === 'termsAcceptanceRequired') {\n this.#requireTermsReacceptance();\n return;\n }\n this.#fail(`Check frame returned status: ${status}`);\n }\n\n /**\n * Applies an Auth-frame outcome.\n *\n * @param status - The frame status.\n * @param accessToken - The decrypted access token, if any.\n */\n async #handleAuthOutcome(\n status: NonNullable<FrameMessage['payload']>['status'],\n accessToken?: string,\n ): Promise<void> {\n if (status === 'active' && accessToken) {\n this.#applyUpdate((state) => {\n state.accessToken = accessToken;\n state.phase = 'form';\n state.statusMessage = 'Authenticated. Review to submit.';\n });\n await this.#continueAfterAuthentication();\n return;\n }\n if (status === 'termsAcceptanceRequired') {\n this.#requireTermsReacceptance();\n return;\n }\n this.#fail(`Auth frame returned status: ${status}`);\n }\n\n /**\n * Continues the flow once authentication has completed (phase `form`).\n *\n * When the flow is scoped to a product (see {@link initialize}), the\n * KYC-required check runs automatically, and — when KYC is required — the\n * document-verification sub-flow is launched. When no product is set, this is\n * a no-op and the flow stays at `form` for the consumer to drive manually.\n *\n * Errors are already recorded on state by `checkKycRequired` (`error`\n * phase) and `startSumSub` (`sumsub.status = 'failed'`); this method swallows\n * them so it can be awaited safely from the frame-message handler.\n */\n async #continueAfterAuthentication(): Promise<void> {\n const product = this.state.activeProduct;\n if (!product) {\n return;\n }\n\n // Re-entry protection lives at the frame boundary: `handleFrameMessage`\n // only honors a Check/Auth `complete` while `phase` matches, and both\n // outcome handlers move `phase` to `form` before awaiting this method. A\n // duplicate or late `complete` therefore lands after the phase moved on and\n // is dropped before it can start a second continuation. Any writes here are\n // additionally guarded by `#generation` (see `checkKycRequired` /\n // `startSumSub`) so a `reset()` mid-continuation cannot corrupt state.\n const kycRequired = await this.checkKycRequired({ product });\n if (!kycRequired) {\n return;\n }\n\n try {\n await this.startSumSub();\n } catch {\n // `startSumSub` already records `sumsub.status = 'failed'`; swallow the\n // rethrown error (e.g. SDK unavailable) so the awaited continuation\n // resolves cleanly rather than surfacing as an unhandled rejection.\n }\n }\n\n /**\n * Invalidates stored terms and returns to the terms phase.\n */\n #requireTermsReacceptance(): void {\n this.#applyUpdate((state) => {\n this.#clearAcceptedTerms(state);\n state.phase = 'terms';\n state.statusMessage =\n 'The vendor updated its Terms of Use — please re-accept.';\n });\n }\n\n /**\n * Builds the Check-frame URL, or `null` when no session exists yet.\n *\n * @returns The Check-frame URL or `null`.\n */\n buildCheckFrameUrl(): string | null {\n if (!this.state.sessionToken) {\n return null;\n }\n const url = new URL(`${FRAMES_BASE_URL}/check-connection`);\n url.searchParams.set('sessionToken', this.state.sessionToken);\n url.searchParams.set('publicKey', this.#keypair.publicKeyHex);\n url.searchParams.set('channelId', CHANNEL_CHECK);\n url.searchParams.set('skipKyc', 'true');\n return url.toString();\n }\n\n /**\n * Builds the Auth-frame URL, or `null` when no client token is available.\n *\n * @returns The Auth-frame URL or `null`.\n */\n buildAuthFrameUrl(): string | null {\n if (!this.#authClientToken) {\n return null;\n }\n const url = new URL(`${FRAMES_BASE_URL}/auth`);\n url.searchParams.set('clientToken', this.#authClientToken);\n url.searchParams.set('publicKey', this.#keypair.publicKeyHex);\n url.searchParams.set('channelId', CHANNEL_AUTH);\n return url.toString();\n }\n\n /**\n * Builds the Reset-frame URL.\n *\n * @returns The Reset-frame URL.\n */\n buildResetFrameUrl(): string {\n const url = new URL(`${FRAMES_BASE_URL}/reset`);\n url.searchParams.set('channelId', CHANNEL_RESET);\n return url.toString();\n }\n\n /**\n * Checks whether KYC is required for a product and caches the result.\n *\n * @param params - The parameters.\n * @param params.product - The consuming feature.\n * @param params.country - Optional alpha-3 country override.\n * @returns Whether KYC is required.\n */\n async checkKycRequired(params: {\n product: KycProduct;\n country?: string;\n }): Promise<boolean> {\n const { accessToken } = this.state;\n if (!accessToken) {\n this.#fail('Missing accessToken — repeat the authentication step.');\n return false;\n }\n const country = params.country ?? this.state.geoCountry;\n if (!country) {\n this.#fail('Missing country for KYC-required check.');\n return false;\n }\n\n // Capture the flow generation so we can detect a `reset()` that happens\n // while the HTTP call is in flight and avoid writing stale results.\n const generation = this.#generation;\n\n this.#applyUpdate((state) => {\n state.phase = 'submit';\n state.statusMessage = 'Checking KYC status...';\n });\n\n try {\n const { kycRequired } = await this.messenger.call(\n 'KycService:checkKycRequired',\n { accessToken, country, capabilities: [{ product: params.product }] },\n );\n // The flow was reset while the check was in flight; discard the result\n // rather than resurrecting a done/cached state on an idle controller.\n const applied = this.#updateIfCurrent(generation, (state) => {\n state.kycRequiredByProduct[params.product] = kycRequired;\n state.lastCheckedAt = new Date().toISOString();\n state.phase = 'done';\n state.statusMessage = 'KYC check complete.';\n });\n if (!applied) {\n return false;\n }\n return kycRequired;\n } catch (error) {\n if (this.#generation !== generation) {\n return false;\n }\n this.#fail(`KYC check failed: ${String(error)}`);\n return false;\n }\n }\n\n /**\n * Reads the cached \"is KYC required\" result for a product.\n *\n * @param params - The parameters.\n * @param params.product - The consuming feature.\n * @returns The cached value, or `undefined` if not yet checked.\n */\n getKycStatus(params: { product: KycProduct }): boolean | undefined {\n return this.state.kycRequiredByProduct[params.product];\n }\n\n /**\n * Returns the vendor-scoped identity for the currently authenticated\n * customer, or `null` when the flow has not yet captured a vendor customer\n * id (before authentication or after {@link reset}).\n *\n * Exposed so consumers (e.g. ramps autoramp creation) can attach the vendor\n * customer id to downstream calls without reading the full KYC state, which\n * also holds session/access tokens. The id is session-scoped and never\n * persisted.\n *\n * @returns The current {@link KycCustomerIdentity}, or `null`.\n */\n getCustomerIdentity(): KycCustomerIdentity | null {\n const { moonpayCustomerId, activeVendor } = this.state;\n if (!moonpayCustomerId) {\n return null;\n }\n return { vendor: activeVendor, id: moonpayCustomerId };\n }\n\n /**\n * Builds the vendor-specific fields spread into a\n * `KycService:createUkycSession` call, derived from the active vendor and the\n * currently captured auth state.\n *\n * MoonPay sessions must carry the access token and customer id in\n * `vendorMetadata`; other vendors carry no vendor metadata.\n *\n * @returns The vendor-specific subset of the `createUkycSession` params.\n */\n #buildUkycSessionVendorFields(): Pick<\n CreateUkycSessionParams,\n 'vendor' | 'vendorMetadata'\n > {\n if (this.state.activeVendor === 'moonpay') {\n return {\n vendor: 'moonpay',\n vendorMetadata: {\n moonPayAccessToken: this.state.accessToken,\n moonPayUserId: this.state.moonpayCustomerId,\n },\n };\n }\n\n return { vendor: this.state.activeVendor };\n }\n\n /**\n * Runs the SumSub document-verification sub-flow end to end:\n *\n * 1. requests a per-session wrapping key from the UKYC backend;\n * 2. verifies its `jwtChain` against the Fractal JWKS and confirms the\n * attested session server public key;\n * 3. derives the `data_encryption_key` from the wallet's UKYC\n * `local_user_secret` and wraps it for the session server;\n * 4. mints a client-signed, read-only `ukyc_capability_token` and creates\n * the UKYC session (handing over the wrapped key and the token);\n * 5. fetches the SumSub applicant access token; and\n * 6. presents the SDK via the injected launcher.\n *\n * If session creation reports the applicant is already approved on the relay\n * while the vendor is still finalizing (`kycStatus: approved`,\n * `finalStatus: pending`), the sub-flow stops at step 4 with a\n * `vendorProcessing` status and a message rather than launching the SDK.\n *\n * @param params - Optional parameters.\n * @param params.locale - BCP-47 locale for the SDK UI.\n * @param params.debug - Enables SDK debug logging.\n * @returns The SDK result.\n */\n async startSumSub(params?: {\n locale?: string;\n debug?: boolean;\n }): Promise<Record<string, unknown>> {\n // A new sub-flow supersedes any polling still running from a prior run.\n this.#stopPolling();\n\n if (!this.#sumsubLauncher.isAvailable()) {\n const error = 'SumSub SDK is not available in this runtime.';\n this.#applyUpdate((state) => {\n state.sumsub.status = 'failed';\n state.sumsub.result = { error };\n });\n throw new Error(error);\n }\n\n // Capture the flow generation so each async step can detect a `reset()`\n // that lands mid-flight and avoid writing stale sub-flow state (or, worse,\n // presenting the SDK) on a controller that is now idle.\n const generation = this.#generation;\n\n try {\n this.#applyUpdate((state) => {\n state.sumsub.status = 'creatingSession';\n state.sumsub.result = null;\n state.sumsub.sessionStatus = null;\n });\n\n const jwtToken = MOCK_JWT_TOKEN;\n\n // Establish a per-session X25519 keypair and exchange our public half for\n // the server's wrapping key. The private half stays on the device and is\n // used to derive the shared secret that seals the data_encryption_key.\n const sessionClientPrivateKey = x25519.utils.randomSecretKey();\n const sessionClientPublicKey = x25519.getPublicKey(\n sessionClientPrivateKey,\n );\n const wrappingKey = await this.messenger.call(\n 'KycService:getWrappingKey',\n { sessionClientPublicKey: toBase64Url(sessionClientPublicKey) },\n );\n\n // Verify the jwtChain against Fractal's JWKS, then confirm the returned\n // sessionServerPublicKey matches the value attested inside the verified\n // JWT payload before trusting it for key wrapping.\n const { keys } = await this.messenger.call('KycService:fetchJwks');\n const jwtChainPayload = verifyJwtChain(keys, wrappingKey.jwtChain);\n if (\n jwtChainPayload.sessionServerPublicKeyX !==\n wrappingKey.sessionServerPublicKey.x\n ) {\n throw new Error(\n 'sessionServerPublicKey does not match the verified jwtChain payload (sessionServerPublicKeyX).',\n );\n }\n\n // Derive the data_encryption_key from the local_user_secret and wrap it\n // for the session server. Only the wrapped (encrypted) key ever leaves\n // the device.\n const localUserSecret = await getOrCreateLocalUserSecret(\n this.#localUserSecretStore(),\n );\n const clientMaterial = deriveClientMaterial(localUserSecret);\n const wrappedEncryptionKey = {\n sessionId: wrappingKey.id,\n ...wrapEncryptionKey(\n sessionClientPrivateKey,\n wrappingKey.sessionServerPublicKey.x,\n clientMaterial.dataEncryptionKey,\n ),\n };\n\n // Mint a read-only `ukyc_capability_token` for the session. Only the\n // client holds the signing key derived from `local_user_secret`, so only\n // the client can mint it; scoping it to `read` means it authorizes later\n // storage reads without granting write or delete access.\n const ukycCapabilityToken = signStorageAccessToken({\n material: clientMaterial,\n operations: ['read'],\n expiresAt: new Date(Date.now() + UKYC_CAPABILITY_TOKEN_TTL_MS),\n });\n\n const { sessionId, kycStatus, finalStatus } = await this.messenger.call(\n 'KycService:createUkycSession',\n {\n jwtToken,\n ...this.#buildUkycSessionVendorFields(),\n wrappedEncryptionKey,\n ukycCapabilityToken,\n },\n );\n\n // A user who already finished the journey can return to a session the\n // relay has already approved (`kycStatus`) while the vendor is still\n // finalizing its own decision (`finalStatus`). There is nothing left to\n // verify, so stop here and surface a message rather than launching the\n // SDK again.\n if (\n kycStatus === KYC_STATUSES.approved &&\n finalStatus === KYC_STATUSES.pending\n ) {\n const stillCurrent = this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'vendorProcessing';\n state.sumsub.sessionId = sessionId;\n state.statusMessage = VENDOR_PROCESSING_MESSAGE;\n });\n return stillCurrent ? { kycStatus, finalStatus } : {};\n }\n\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'fetchingToken';\n state.sumsub.sessionId = sessionId;\n });\n\n const { applicantAccessToken } = await this.messenger.call(\n 'KycService:createJourney',\n sessionId,\n );\n\n // A reset() may have landed while the session/token was being prepared.\n // Gate the `launching` write and the decision to open the SDK behind a\n // single generation check: `#updateIfCurrent` only writes when still\n // current and reports whether it did. Since there is no `await` between\n // this check and `launch` below, a successful result guarantees the SDK\n // is never presented on a flow that a concurrent reset() returned to idle.\n const stillCurrent = this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'launching';\n state.sumsub.applicantAccessToken = applicantAccessToken;\n });\n if (!stillCurrent) {\n return {};\n }\n\n // Track whether the SDK ever reported a successful completion. A resolved\n // `launch` alone does not imply success — the applicant may have\n // abandoned the flow or the SDK may have reported a non-success outcome.\n let reachedCompletion = false;\n\n const result = await this.#sumsubLauncher.launch({\n applicantAccessToken,\n onTokenExpiration: async () => {\n // A reset() may have superseded this flow while the SDK stayed open.\n // Refuse to refresh against the now-stale UKYC session rather than\n // silently keeping an orphaned SDK alive.\n if (this.#generation !== generation) {\n throw new Error(\n 'KYC flow was reset; SumSub session is no longer active.',\n );\n }\n const refreshed = await this.messenger.call(\n 'KycService:createJourney',\n sessionId,\n );\n return refreshed.applicantAccessToken;\n },\n onStatusChange: (_prev, next) => {\n if (next === SUMSUB_COMPLETED_STATUS) {\n reachedCompletion = true;\n }\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status =\n next === SUMSUB_COMPLETED_STATUS ? 'complete' : 'inProgress';\n });\n },\n locale: params?.locale ?? 'en',\n debug: params?.debug ?? false,\n });\n\n // A resolved `launch` alone is not the final outcome: only a SDK-reported\n // completion is worth polling for a verification decision. Anything else\n // (abandonment, non-success) is `failed` and must not be polled.\n const applied = this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = reachedCompletion ? 'polling' : 'failed';\n state.sumsub.result = result as Json;\n });\n\n // Once the SDK completes, the authoritative verification decision comes\n // from the UKYC backend, not the SDK result. Poll the session status\n // until it reaches a terminal decision. Guard on `applied` so a `reset()`\n // that landed during `launch` cannot start polling on an idle flow.\n if (applied && reachedCompletion) {\n if (sessionId) {\n await this.#startSessionStatusPolling(sessionId);\n } else {\n // No session id to poll against; fall back to treating the SDK\n // completion as the final outcome.\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'complete';\n });\n }\n }\n return result;\n } catch (error) {\n // Applicant already finished KYC — treat as completed for Money toast.\n if (isSessionAlreadyCompletedError(error)) {\n // A reset() may have landed while `launch` was in flight; forcing\n // `completed` (and publishing `statusChanged`) on an idle controller\n // would resurrect a flow the consumer already tore down.\n if (this.#generation !== generation) {\n return { alreadyCompleted: true };\n }\n this.#applyUserStatus({\n status: 'completed',\n sumsubSessionId: null,\n errorCode: null,\n });\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'complete';\n state.sumsub.result = { alreadyCompleted: true };\n state.statusMessage = 'KYC already completed.';\n state.phase = 'done';\n state.error = null;\n });\n return { alreadyCompleted: true };\n }\n const result = { error: String(error) };\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = 'failed';\n state.sumsub.result = result;\n });\n return result;\n }\n }\n\n /**\n * Refreshes the user-keyed simplified KYC status from `GET /kyc/status`,\n * stores it on state, publishes {@link KycControllerStatusChangedEvent}, and\n * schedules short-interval polling while the status is `pending`.\n *\n * @returns The latest status payload.\n */\n async refreshKycStatus(): Promise<{\n status: KycUserStatus;\n sumsubSessionId: string | null;\n errorCode: string | null;\n }> {\n const generation = this.#generation;\n const payload = await this.#fetchAndApplyUserStatus();\n // A `reset()` landing while the request was in flight already stopped\n // polling and left the flow idle, and the payload above is the pre-reset\n // cached status. Starting a loop from it would poll — and publish\n // `statusChanged` — on a torn-down flow.\n if (this.#generation !== generation) {\n return payload;\n }\n if (payload.status === 'pending') {\n this.#ensureUserStatusPolling();\n } else {\n this.#stopUserStatusPolling();\n }\n return payload;\n }\n\n /**\n * Fetches `GET /kyc/status` and applies it to state without managing the\n * poll loop (used by both {@link refreshKycStatus} and the poll tick).\n *\n * @returns The latest status payload.\n */\n async #fetchAndApplyUserStatus(): Promise<{\n status: KycUserStatus;\n sumsubSessionId: string | null;\n errorCode: string | null;\n }> {\n const generation = this.#generation;\n const response = await this.messenger.call('KycService:fetchKycStatus');\n if (this.#generation !== generation) {\n return {\n status: this.state.userStatus ?? 'not-started',\n sumsubSessionId: this.state.userStatusSumsubSessionId,\n errorCode: this.state.userStatusErrorCode,\n };\n }\n const payload = {\n status: response.status,\n sumsubSessionId: response.sumsubSessionId ?? null,\n errorCode: response.errorCode ?? null,\n };\n this.#applyUserStatus(payload);\n return payload;\n }\n\n /**\n * Writes user-keyed status onto state and publishes `statusChanged` when the\n * value actually changes.\n *\n * @param payload - The status payload to apply.\n * @param payload.status - User-keyed KYC status from `GET /kyc/status`.\n * @param payload.sumsubSessionId - Optional SumSub session id from status.\n * @param payload.errorCode - Optional error code from status.\n */\n #applyUserStatus(payload: {\n status: KycUserStatus;\n sumsubSessionId: string | null;\n errorCode: string | null;\n }): void {\n const previous = this.state.userStatus;\n this.#applyUpdate((state) => {\n state.userStatus = payload.status;\n state.userStatusSumsubSessionId = payload.sumsubSessionId;\n state.userStatusErrorCode = payload.errorCode;\n });\n if (previous !== payload.status) {\n this.messenger.publish(`${controllerName}:statusChanged`, payload);\n }\n }\n\n /**\n * Starts the user-status poll loop when not already running and status is\n * still `pending`.\n */\n #ensureUserStatusPolling(): void {\n if (this.#userStatusPolling) {\n return;\n }\n this.#userStatusPolling = true;\n const token = this.#userStatusPollToken;\n const tick = async (): Promise<void> => {\n try {\n const payload = await this.#fetchAndApplyUserStatus();\n // Race with `reset()` / `#stopUserStatusPolling` while the request was\n // in flight — do not reschedule onto an idle controller.\n /* istanbul ignore next */\n if (this.#userStatusPollToken !== token) {\n return;\n }\n if (payload.status !== 'pending') {\n this.#stopUserStatusPolling();\n return;\n }\n } catch {\n // Keep polling on transient errors, unless the loop was superseded.\n /* istanbul ignore next */\n if (this.#userStatusPollToken !== token) {\n return;\n }\n }\n this.#userStatusPollTimer = setTimeout(() => {\n this.#userStatusPollTimer = null;\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n tick();\n }, this.#userStatusPollIntervalMs);\n // Allow the process to exit while a pending-status poll is scheduled.\n // React Native / browser timers are numbers with no `unref`, hence the\n // optional call.\n this.#userStatusPollTimer.unref?.();\n };\n this.#userStatusPollTimer = setTimeout(() => {\n this.#userStatusPollTimer = null;\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n tick();\n }, this.#userStatusPollIntervalMs);\n this.#userStatusPollTimer.unref?.();\n }\n\n /**\n * Stops the user-keyed status poll loop.\n */\n #stopUserStatusPolling(): void {\n this.#userStatusPollToken += 1;\n this.#userStatusPolling = false;\n if (this.#userStatusPollTimer !== null) {\n clearTimeout(this.#userStatusPollTimer);\n this.#userStatusPollTimer = null;\n }\n }\n\n /**\n * Fetches the current UKYC session status for the active sub-flow and records\n * it on state. Useful for a one-off refresh outside the automatic polling\n * loop that {@link startSumSub} runs.\n *\n * @returns The fetched session status.\n * @throws If there is no active SumSub session to query.\n */\n async getSessionStatus(): Promise<KycSessionStatus> {\n const { sessionId } = this.state.sumsub;\n if (!sessionId) {\n throw new Error('Cannot fetch session status: no active SumSub session.');\n }\n\n // Capture the flow generation so a `reset()` landing while the request is\n // in flight cannot write the result onto an idle controller.\n const generation = this.#generation;\n const sessionStatus = await this.messenger.call(\n 'KycService:getSessionStatus',\n { sessionId },\n );\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.sessionStatus = sessionStatus;\n });\n return sessionStatus;\n }\n\n /**\n * Begins polling the UKYC session status until a terminal decision is\n * reached. The first poll runs immediately (and is awaited by\n * {@link startSumSub}); subsequent polls are scheduled every\n * `#sessionStatusPollIntervalMs`.\n *\n * @param sessionId - The UKYC session id to poll.\n * @returns A promise that resolves once the first poll settles.\n */\n async #startSessionStatusPolling(sessionId: string): Promise<void> {\n // Supersede any prior loop and claim a fresh token for this one. Because\n // `#stopPolling` bumps the token, any in-flight poll from a previous loop\n // sees a mismatch and neither writes state nor reschedules.\n this.#stopPolling();\n const token = this.#pollToken;\n\n const tick = async (): Promise<void> => {\n const shouldStop = await this.#pollSessionStatusOnce(sessionId, token);\n if (shouldStop) {\n return;\n }\n this.#pollTimer = setTimeout(() => {\n this.#pollTimer = null;\n // `tick` swallows its own errors (see `#pollSessionStatusOnce`) and\n // therefore never rejects, so this fire-and-forget scheduled poll\n // cannot surface as an unhandled rejection.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n tick();\n }, this.#sessionStatusPollIntervalMs);\n };\n\n await tick();\n }\n\n /**\n * Performs a single session-status poll: fetches the status, records it, and\n * resolves the sub-flow when the status is terminal.\n *\n * Transient errors are swallowed so the loop keeps polling; the last good\n * `sessionStatus` is deliberately preserved rather than being overwritten\n * with the error.\n *\n * @param sessionId - The UKYC session id to poll.\n * @param token - The polling token captured when the loop started.\n * @returns `true` when the loop should stop (terminal status or superseded\n * by a reset / new sub-flow), `false` when it should keep polling.\n */\n async #pollSessionStatusOnce(\n sessionId: string,\n token: number,\n ): Promise<boolean> {\n try {\n const sessionStatus = await this.messenger.call(\n 'KycService:getSessionStatus',\n { sessionId },\n );\n // Superseded while the request was in flight — drop the result.\n if (this.#pollToken !== token) {\n return true;\n }\n const isTerminal = TERMINAL_SESSION_STATUSES.has(\n sessionStatus.finalStatus,\n );\n this.#applyUpdate((state) => {\n state.sumsub.sessionStatus = sessionStatus;\n if (isTerminal) {\n state.sumsub.status = SUCCESSFUL_SESSION_STATUSES.has(\n sessionStatus.finalStatus,\n )\n ? 'complete'\n : 'failed';\n }\n });\n if (isTerminal) {\n this.#stopPolling();\n }\n return isTerminal;\n } catch {\n // Keep polling on transient errors, preserving the last good status.\n // Stop only when a reset / new sub-flow superseded this loop.\n return this.#pollToken !== token;\n }\n }\n\n /**\n * Stops the session-status polling loop: bumps the polling token (so any\n * in-flight `tick` bows out) and clears any scheduled poll.\n */\n #stopPolling(): void {\n this.#pollToken += 1;\n if (this.#pollTimer !== null) {\n clearTimeout(this.#pollTimer);\n this.#pollTimer = null;\n }\n }\n\n /**\n * Resets the flow to idle, clearing session tokens and sub-flow state while\n * preserving persisted terms acceptance and the per-product cache.\n */\n reset(): void {\n this.#authClientToken = null;\n // Stop any session-status polling so a late poll cannot write onto the\n // now-idle controller.\n this.#stopPolling();\n this.#stopUserStatusPolling();\n // Invalidate any in-flight async work started before this reset so its\n // results are discarded rather than written onto the now-idle controller.\n this.#generation += 1;\n this.#applyUpdate((state) => {\n state.phase = 'idle';\n state.statusMessage = '';\n state.error = null;\n state.disclaimers = [];\n state.disclaimersError = null;\n state.sessionToken = null;\n state.accessToken = null;\n state.moonpayCustomerId = null;\n state.activeVendor = 'moonpay';\n state.activeProduct = null;\n state.sumsub = {\n status: 'idle',\n result: null,\n sessionId: null,\n applicantAccessToken: null,\n sessionStatus: null,\n };\n });\n }\n\n /**\n * Applies a state update only when the flow has not been reset since\n * `generation` was captured. Prevents an in-flight async step from writing\n * stale results onto a controller that a concurrent {@link reset} has\n * returned to idle.\n *\n * @param generation - The flow generation captured before the async work.\n * @param updater - The state mutation to apply when still current.\n * @returns `true` if the update was applied, `false` if it was superseded.\n */\n #updateIfCurrent(\n generation: number,\n updater: (state: KycControllerState) => void,\n ): boolean {\n if (this.#generation !== generation) {\n return false;\n }\n this.#applyUpdate(updater);\n return true;\n }\n\n /**\n * The single state-update path for this controller. All mutations go through\n * here (rather than calling `this.update` directly) so the mechanism stays\n * consistent and one subtlety is handled in a single place:\n *\n * `sumsub.result` is typed as the recursive `Json`, and expanding\n * `Draft<Json>` (which happens whenever an updater touches `sumsub.result`)\n * can trip TypeScript's \"type instantiation is excessively deep\" guard. By\n * typing the callback parameter as the plain {@link KycControllerState}\n * instead of Immer's `Draft`, we avoid expanding the draft type while keeping\n * the same mutate-in-place semantics (the underlying value is still the Immer\n * draft at runtime).\n *\n * @param updater - The state mutation to apply.\n */\n #applyUpdate(updater: (state: KycControllerState) => void): void {\n this.update((state) => {\n // @ts-expect-error Avoid \"type instantiation is excessively deep\".\n updater(state);\n });\n }\n\n /**\n * Transitions to the error phase with a message.\n *\n * @param message - The error message.\n */\n #fail(message: string): void {\n this.#applyUpdate((state) => {\n state.error = message;\n state.phase = 'error';\n });\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"KycService-method-action-types.cjs","sourceRoot":"","sources":["../src/KycService-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { KycService } from './KycService.js';\n\n/**\n * Resolves the customer's country from the geolocation source and converts it\n * to an ISO 3166-1 alpha-3 code.\n *\n * @returns The alpha-3 country code.\n * @throws If the country cannot be determined or mapped.\n */\nexport type KycServiceGetGeoCountryAction = {\n type: `KycService:getGeoCountry`;\n handler: KycService['getGeoCountry'];\n};\n\n/**\n * Fetches the disclaimers the customer must accept before a session is\n * created.\n *\n * @param params - The parameters.\n * @param params.country - ISO 3166-1 alpha-3 country code.\n * @returns The disclaimers.\n */\nexport type KycServiceFetchDisclaimersAction = {\n type: `KycService:fetchDisclaimers`;\n handler: KycService['fetchDisclaimers'];\n};\n\n/**\n * Creates a vendor session via the UKYC backend.\n *\n * @param params - The session parameters.\n * @returns The created session token.\n */\nexport type KycServiceCreateSessionAction = {\n type: `KycService:createSession`;\n handler: KycService['createSession'];\n};\n\n/**\n * Checks whether KYC is required for the given
|
|
1
|
+
{"version":3,"file":"KycService-method-action-types.cjs","sourceRoot":"","sources":["../src/KycService-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { KycService } from './KycService.js';\n\n/**\n * Resolves the customer's country from the geolocation source and converts it\n * to an ISO 3166-1 alpha-3 code.\n *\n * @returns The alpha-3 country code.\n * @throws If the country cannot be determined or mapped.\n */\nexport type KycServiceGetGeoCountryAction = {\n type: `KycService:getGeoCountry`;\n handler: KycService['getGeoCountry'];\n};\n\n/**\n * Fetches the disclaimers the customer must accept before a session is\n * created.\n *\n * @param params - The parameters.\n * @param params.vendor - Identity vendor. Defaults to `moonpay`.\n * @param params.country - ISO 3166-1 alpha-3 country code.\n * @returns The disclaimers.\n */\nexport type KycServiceFetchDisclaimersAction = {\n type: `KycService:fetchDisclaimers`;\n handler: KycService['fetchDisclaimers'];\n};\n\n/**\n * Creates a vendor session via the UKYC backend.\n *\n * @param params - The session parameters.\n * @returns The created session token.\n */\nexport type KycServiceCreateSessionAction = {\n type: `KycService:createSession`;\n handler: KycService['createSession'];\n};\n\n/**\n * Checks whether KYC is required for the given vendor, country, and\n * capabilities.\n *\n * @param params - The check parameters.\n * @returns Whether KYC is required.\n */\nexport type KycServiceCheckKycRequiredAction = {\n type: `KycService:checkKycRequired`;\n handler: KycService['checkKycRequired'];\n};\n\n/**\n * Creates (or resumes) an empty-shell customer for the authenticated\n * canonical user on the given identity vendor. Must run before showing\n * vendor T&C so the customer exists and resume logic can key off vendor\n * status.\n *\n * @param params - The parameters.\n * @param params.vendor - Identity vendor (e.g. `iron` for Money/VBA).\n * @param params.email - Email associated with the customer.\n * @returns The vendor customer record (subset validated for controller use).\n */\nexport type KycServiceCreateVendorCustomerAction = {\n type: `KycService:createVendorCustomer`;\n handler: KycService['createVendorCustomer'];\n};\n\n/**\n * Posts T&C1 (vendor signings) and T&C2 (Sumsub + idOS) consents for the\n * authenticated user. The API responds with 204 No Content on success.\n *\n * @param params - The consent parameters.\n */\nexport type KycServiceSubmitConsentsAction = {\n type: `KycService:submitConsents`;\n handler: KycService['submitConsents'];\n};\n\n/**\n * Fetches the user-keyed simplified KYC status used by Money toast / banner\n * surfaces (`GET /kyc/status`).\n *\n * @returns The simplified status payload.\n */\nexport type KycServiceFetchKycStatusAction = {\n type: `KycService:fetchKycStatus`;\n handler: KycService['fetchKycStatus'];\n};\n\n/**\n * Requests a per-session wrapping key from the UKYC backend.\n *\n * The client sends its ephemeral X25519 public key; the backend responds with\n * its session public key (`sessionServerPublicKey`) and a `jwtChain` that\n * attests it. The caller must verify `jwtChain` against the Fractal JWKS\n * (see {@link KycService.fetchJwks}) before trusting the key to wrap the\n * `data_encryption_key`.\n *\n * @param params - The parameters.\n * @param params.sessionClientPublicKey - Our ephemeral X25519 public key\n * (base64url).\n * @returns The wrapping key id, `jwtChain`, and session server public key.\n */\nexport type KycServiceGetWrappingKeyAction = {\n type: `KycService:getWrappingKey`;\n handler: KycService['getWrappingKey'];\n};\n\n/**\n * Fetches the Fractal encryption service JWKS used to verify the `jwtChain`\n * returned by {@link KycService.getWrappingKey}.\n *\n * This is an unauthenticated request to a well-known path on the Fractal\n * host, distinct from the UKYC base URL.\n *\n * @returns The JWKS keys.\n */\nexport type KycServiceFetchJwksAction = {\n type: `KycService:fetchJwks`;\n handler: KycService['fetchJwks'];\n};\n\n/**\n * Creates a UKYC session for the SumSub document-verification sub-flow,\n * handing over the wrapped `data_encryption_key` and the client-signed,\n * read-only `ukyc_capability_token` that authorizes later storage access for\n * the session.\n *\n * @param params - The session parameters.\n * @returns The UKYC session identifiers.\n */\nexport type KycServiceCreateUkycSessionAction = {\n type: `KycService:createUkycSession`;\n handler: KycService['createUkycSession'];\n};\n\n/**\n * Creates (or refreshes) the SumSub verification journey for a UKYC session,\n * returning the applicant access token used to launch the SDK.\n *\n * @param sessionId - The UKYC session id from `createUkycSession`.\n * @returns The applicant access token and status.\n */\nexport type KycServiceCreateJourneyAction = {\n type: `KycService:createJourney`;\n handler: KycService['createJourney'];\n};\n\n/**\n * Fetches the current status of a UKYC session. Polled after the SumSub SDK\n * completes to determine the final verification decision.\n *\n * @param params - The parameters.\n * @param params.sessionId - The UKYC session id.\n * @returns The session status.\n */\nexport type KycServiceGetSessionStatusAction = {\n type: `KycService:getSessionStatus`;\n handler: KycService['getSessionStatus'];\n};\n\n/**\n * Union of all KycService action types.\n */\nexport type KycServiceMethodActions =\n | KycServiceGetGeoCountryAction\n | KycServiceFetchDisclaimersAction\n | KycServiceCreateSessionAction\n | KycServiceCheckKycRequiredAction\n | KycServiceCreateVendorCustomerAction\n | KycServiceSubmitConsentsAction\n | KycServiceFetchKycStatusAction\n | KycServiceGetWrappingKeyAction\n | KycServiceFetchJwksAction\n | KycServiceCreateUkycSessionAction\n | KycServiceCreateJourneyAction\n | KycServiceGetSessionStatusAction;\n"]}
|
|
@@ -19,6 +19,7 @@ export type KycServiceGetGeoCountryAction = {
|
|
|
19
19
|
* created.
|
|
20
20
|
*
|
|
21
21
|
* @param params - The parameters.
|
|
22
|
+
* @param params.vendor - Identity vendor. Defaults to `moonpay`.
|
|
22
23
|
* @param params.country - ISO 3166-1 alpha-3 country code.
|
|
23
24
|
* @returns The disclaimers.
|
|
24
25
|
*/
|
|
@@ -37,7 +38,7 @@ export type KycServiceCreateSessionAction = {
|
|
|
37
38
|
handler: KycService['createSession'];
|
|
38
39
|
};
|
|
39
40
|
/**
|
|
40
|
-
* Checks whether KYC is required for the given
|
|
41
|
+
* Checks whether KYC is required for the given vendor, country, and
|
|
41
42
|
* capabilities.
|
|
42
43
|
*
|
|
43
44
|
* @param params - The check parameters.
|
|
@@ -47,6 +48,41 @@ export type KycServiceCheckKycRequiredAction = {
|
|
|
47
48
|
type: `KycService:checkKycRequired`;
|
|
48
49
|
handler: KycService['checkKycRequired'];
|
|
49
50
|
};
|
|
51
|
+
/**
|
|
52
|
+
* Creates (or resumes) an empty-shell customer for the authenticated
|
|
53
|
+
* canonical user on the given identity vendor. Must run before showing
|
|
54
|
+
* vendor T&C so the customer exists and resume logic can key off vendor
|
|
55
|
+
* status.
|
|
56
|
+
*
|
|
57
|
+
* @param params - The parameters.
|
|
58
|
+
* @param params.vendor - Identity vendor (e.g. `iron` for Money/VBA).
|
|
59
|
+
* @param params.email - Email associated with the customer.
|
|
60
|
+
* @returns The vendor customer record (subset validated for controller use).
|
|
61
|
+
*/
|
|
62
|
+
export type KycServiceCreateVendorCustomerAction = {
|
|
63
|
+
type: `KycService:createVendorCustomer`;
|
|
64
|
+
handler: KycService['createVendorCustomer'];
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Posts T&C1 (vendor signings) and T&C2 (Sumsub + idOS) consents for the
|
|
68
|
+
* authenticated user. The API responds with 204 No Content on success.
|
|
69
|
+
*
|
|
70
|
+
* @param params - The consent parameters.
|
|
71
|
+
*/
|
|
72
|
+
export type KycServiceSubmitConsentsAction = {
|
|
73
|
+
type: `KycService:submitConsents`;
|
|
74
|
+
handler: KycService['submitConsents'];
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Fetches the user-keyed simplified KYC status used by Money toast / banner
|
|
78
|
+
* surfaces (`GET /kyc/status`).
|
|
79
|
+
*
|
|
80
|
+
* @returns The simplified status payload.
|
|
81
|
+
*/
|
|
82
|
+
export type KycServiceFetchKycStatusAction = {
|
|
83
|
+
type: `KycService:fetchKycStatus`;
|
|
84
|
+
handler: KycService['fetchKycStatus'];
|
|
85
|
+
};
|
|
50
86
|
/**
|
|
51
87
|
* Requests a per-session wrapping key from the UKYC backend.
|
|
52
88
|
*
|
|
@@ -117,5 +153,5 @@ export type KycServiceGetSessionStatusAction = {
|
|
|
117
153
|
/**
|
|
118
154
|
* Union of all KycService action types.
|
|
119
155
|
*/
|
|
120
|
-
export type KycServiceMethodActions = KycServiceGetGeoCountryAction | KycServiceFetchDisclaimersAction | KycServiceCreateSessionAction | KycServiceCheckKycRequiredAction | KycServiceGetWrappingKeyAction | KycServiceFetchJwksAction | KycServiceCreateUkycSessionAction | KycServiceCreateJourneyAction | KycServiceGetSessionStatusAction;
|
|
156
|
+
export type KycServiceMethodActions = KycServiceGetGeoCountryAction | KycServiceFetchDisclaimersAction | KycServiceCreateSessionAction | KycServiceCheckKycRequiredAction | KycServiceCreateVendorCustomerAction | KycServiceSubmitConsentsAction | KycServiceFetchKycStatusAction | KycServiceGetWrappingKeyAction | KycServiceFetchJwksAction | KycServiceCreateUkycSessionAction | KycServiceCreateJourneyAction | KycServiceGetSessionStatusAction;
|
|
121
157
|
//# sourceMappingURL=KycService-method-action-types.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"KycService-method-action-types.d.cts","sourceRoot":"","sources":["../src/KycService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,yBAAwB;AAElD;;;;;;GAMG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C,IAAI,EAAE,0BAA0B,CAAC;IACjC,OAAO,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;CACtC,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"KycService-method-action-types.d.cts","source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