@metamask-previews/kyc-controller 0.0.0-preview-11d78534e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +6 -0
  3. package/LICENSE.APACHE2 +201 -0
  4. package/LICENSE.MIT +21 -0
  5. package/README.md +648 -0
  6. package/dist/KycController-method-action-types.cjs +7 -0
  7. package/dist/KycController-method-action-types.cjs.map +1 -0
  8. package/dist/KycController-method-action-types.d.cts +143 -0
  9. package/dist/KycController-method-action-types.d.cts.map +1 -0
  10. package/dist/KycController-method-action-types.d.mts +143 -0
  11. package/dist/KycController-method-action-types.d.mts.map +1 -0
  12. package/dist/KycController-method-action-types.mjs +6 -0
  13. package/dist/KycController-method-action-types.mjs.map +1 -0
  14. package/dist/KycController.cjs +800 -0
  15. package/dist/KycController.cjs.map +1 -0
  16. package/dist/KycController.d.cts +219 -0
  17. package/dist/KycController.d.cts.map +1 -0
  18. package/dist/KycController.d.mts +219 -0
  19. package/dist/KycController.d.mts.map +1 -0
  20. package/dist/KycController.mjs +795 -0
  21. package/dist/KycController.mjs.map +1 -0
  22. package/dist/KycService-method-action-types.cjs +7 -0
  23. package/dist/KycService-method-action-types.cjs.map +1 -0
  24. package/dist/KycService-method-action-types.d.cts +74 -0
  25. package/dist/KycService-method-action-types.d.cts.map +1 -0
  26. package/dist/KycService-method-action-types.d.mts +74 -0
  27. package/dist/KycService-method-action-types.d.mts.map +1 -0
  28. package/dist/KycService-method-action-types.mjs +6 -0
  29. package/dist/KycService-method-action-types.mjs.map +1 -0
  30. package/dist/KycService.cjs +238 -0
  31. package/dist/KycService.cjs.map +1 -0
  32. package/dist/KycService.d.cts +169 -0
  33. package/dist/KycService.d.cts.map +1 -0
  34. package/dist/KycService.d.mts +169 -0
  35. package/dist/KycService.d.mts.map +1 -0
  36. package/dist/KycService.mjs +234 -0
  37. package/dist/KycService.mjs.map +1 -0
  38. package/dist/countryCodes.cjs +274 -0
  39. package/dist/countryCodes.cjs.map +1 -0
  40. package/dist/countryCodes.d.cts +18 -0
  41. package/dist/countryCodes.d.cts.map +1 -0
  42. package/dist/countryCodes.d.mts +18 -0
  43. package/dist/countryCodes.d.mts.map +1 -0
  44. package/dist/countryCodes.mjs +270 -0
  45. package/dist/countryCodes.mjs.map +1 -0
  46. package/dist/crypto.cjs +165 -0
  47. package/dist/crypto.cjs.map +1 -0
  48. package/dist/crypto.d.cts +83 -0
  49. package/dist/crypto.d.cts.map +1 -0
  50. package/dist/crypto.d.mts +83 -0
  51. package/dist/crypto.d.mts.map +1 -0
  52. package/dist/crypto.mjs +160 -0
  53. package/dist/crypto.mjs.map +1 -0
  54. package/dist/index.cjs +21 -0
  55. package/dist/index.cjs.map +1 -0
  56. package/dist/index.d.cts +12 -0
  57. package/dist/index.d.cts.map +1 -0
  58. package/dist/index.d.mts +12 -0
  59. package/dist/index.d.mts.map +1 -0
  60. package/dist/index.mjs +6 -0
  61. package/dist/index.mjs.map +1 -0
  62. package/dist/selectors.cjs +30 -0
  63. package/dist/selectors.cjs.map +1 -0
  64. package/dist/selectors.d.cts +24 -0
  65. package/dist/selectors.d.cts.map +1 -0
  66. package/dist/selectors.d.mts +24 -0
  67. package/dist/selectors.d.mts.map +1 -0
  68. package/dist/selectors.mjs +24 -0
  69. package/dist/selectors.mjs.map +1 -0
  70. package/dist/types.cjs +10 -0
  71. package/dist/types.cjs.map +1 -0
  72. package/dist/types.d.cts +93 -0
  73. package/dist/types.d.cts.map +1 -0
  74. package/dist/types.d.mts +93 -0
  75. package/dist/types.d.mts.map +1 -0
  76. package/dist/types.mjs +9 -0
  77. package/dist/types.mjs.map +1 -0
  78. package/package.json +89 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KycController.mjs","sourceRoot":"","sources":["../src/KycController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAI3D,OAAO,EAAE,k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AAqB,KAAK,CAAC,CAAC;QAChC,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;QACtB,KAAK,CAAC,aAAa;YACjB,yDAAyD,CAAC;IAC9D,CAAC,CAAC,CAAC;AACL,CAAC,2EA4RC,UAAkB,EAClB,OAA4C;IAE5C,IAAI,uBAAA,IAAI,iCAAY,KAAK,UAAU,EAAE,CAAC;QACpC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,uBAAA,IAAI,4DAAa,MAAjB,IAAI,EAAc,OAAO,CAAC,CAAC;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC,mEAiBY,OAA4C;IACvD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,OAAO,CAAC,KAAsC,CAAC,CAAC;IAClD,CAAC,CAAC,CAAC;AACL,CAAC,qDAOK,OAAe;IACnB,uBAAA,IAAI,4DAAa,MAAjB,IAAI,EAAc,CAAC,KAAK,EAAE,EAAE;QAC1B,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;QACtB,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;IACxB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Json } from '@metamask/utils';\n\nimport { decryptCredentials, generateKeyPair } from './crypto';\nimport type { EncryptedCredentialsEnvelope, X25519KeyPair } from './crypto';\nimport type { KycControllerMethodActions } from './KycController-method-action-types';\nimport type { KycServiceMethodActions } from './KycService-method-action-types';\nimport type {\n KycDisclaimer,\n KycPhase,\n KycProduct,\n KycSumSubLauncher,\n KycSumSubStatus,\n} from './types';\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// 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// === 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};\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 },\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 '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 = KycServiceMethodActions;\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\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 /**\n * Guards the automatic post-authentication continuation. The Check/Auth\n * frames can post more than one `complete` message (duplicate or late), each\n * of which resolves to an `active` outcome with an access token. Without this\n * flag, every such message would re-enter {@link #continueAfterAuthentication}\n * and run the KYC-required check / SumSub sub-flow again while a prior run is\n * still in flight. Set for the duration of a continuation and cleared by\n * {@link reset} so a fresh flow can continue again.\n */\n #continuationInFlight = false;\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 */\n constructor({ messenger, state, sumsubLauncher }: KycControllerOptions) {\n super({\n messenger,\n metadata: kycControllerMetadata,\n name: controllerName,\n state: { ...getDefaultKycControllerState(), ...state },\n });\n\n this.#sumsubLauncher = sumsubLauncher;\n this.#keypair = generateKeyPair();\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\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 // `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 // Resolve country for display; non-blocking.\n try {\n const country = await this.messenger.call('KycService:getGeoCountry');\n this.#applyUpdate((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 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.#applyUpdate((state) => {\n state.geoCountry = country;\n });\n }\n const disclaimers = await this.messenger.call(\n 'KycService:fetchDisclaimers',\n { country },\n );\n this.#applyUpdate((state) => {\n state.disclaimers = disclaimers;\n state.disclaimersError = null;\n });\n } catch (error) {\n this.#applyUpdate((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 access token and auth-frame client token so\n // `buildAuthFrameUrl` cannot return a URL tied to an old client token and\n // `checkKycRequired` cannot run with an access token from an earlier\n // authentication. The Check/Auth frames re-populate these for the new\n // session.\n this.#authClientToken = null;\n this.#applyUpdate((state) => {\n state.error = null;\n state.phase = 'session';\n state.statusMessage = 'Creating session...';\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.#applyUpdate((state) => {\n state.sessionToken = sessionToken;\n state.phase = 'check';\n state.statusMessage = 'Authenticating via Check frame...';\n });\n } catch (error) {\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 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 if (channelId === CHANNEL_AUTH) {\n await this.#handleAuthOutcome(status, accessToken);\n return {};\n }\n\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 // A duplicate or late `complete` message can re-enter here while a prior\n // continuation is still running; ignore it so the check / sub-flow does not\n // run twice concurrently.\n if (this.#continuationInFlight) {\n return;\n }\n this.#continuationInFlight = true;\n\n // Capture the generation so a `reset()` landing mid-continuation does not\n // let the `finally` clear a flag that belongs to a newer flow.\n const generation = this.#generation;\n\n try {\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 } finally {\n if (this.#generation === generation) {\n this.#continuationInFlight = false;\n }\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 if (this.#generation !== generation) {\n return false;\n }\n this.#applyUpdate((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 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: creates a UKYC session,\n * exchanges the wrapped key for an applicant access token, and presents the\n * SDK via the injected launcher.\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 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 });\n\n const jwtToken = MOCK_JWT_TOKEN;\n const { sessionId, wrappingPublicKey, idosSessionId } =\n await this.messenger.call('KycService:createUkycSession', {\n jwtToken,\n vendorMetadata: {\n moonPayAccessToken: this.state.accessToken,\n moonPayUserId: this.state.moonpayCustomerId,\n },\n });\n // Retain the exchange material so the SDK can refresh its token. The\n // session's `wrappingPublicKey` is forwarded opaquely as the request's\n // `wrappedUserKey` field (the /wrapped-key endpoint's body is unchanged).\n const exchange = {\n sessionId,\n wrappedUserKey: wrappingPublicKey,\n idosSessionId,\n jwtToken,\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:submitWrappedKey',\n exchange,\n );\n\n // A reset() landed while the session/token was being prepared; abort\n // before presenting the SDK rather than launching on an idle controller.\n if (this.#generation !== generation) {\n return {};\n }\n\n this.#applyUpdate((state) => {\n state.sumsub.status = 'launching';\n state.sumsub.applicantAccessToken = applicantAccessToken;\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:submitWrappedKey',\n exchange,\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 // Only record `complete` when the SDK actually reported completion;\n // otherwise treat the resolved-but-unfinished flow as `failed` so\n // consumers and UI do not mistake it for a finished verification.\n this.#updateIfCurrent(generation, (state) => {\n state.sumsub.status = reachedCompletion ? 'complete' : 'failed';\n state.sumsub.result = result as Json;\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 * 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 // Invalidate any in-flight async work started before this reset.\n this.#generation += 1;\n // Allow the next authenticated flow to auto-continue; any continuation from\n // the superseded generation will no longer clear this flag (see the\n // generation guard in `#continueAfterAuthentication`).\n this.#continuationInFlight = false;\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 };\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 * trips 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 updater(state as unknown as KycControllerState);\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"]}
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ /**
3
+ * This file is auto generated.
4
+ * Do not edit manually.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ //# sourceMappingURL=KycService-method-action-types.cjs.map
@@ -0,0 +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';\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 access token, 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 a UKYC session for the SumSub document-verification sub-flow.\n *\n * @param params - The session parameters.\n * @returns The UKYC session identifiers and wrapped key.\n */\nexport type KycServiceCreateUkycSessionAction = {\n type: `KycService:createUkycSession`;\n handler: KycService['createUkycSession'];\n};\n\n/**\n * Exchanges the wrapped user key for a SumSub applicant access token.\n *\n * @param params - The exchange parameters.\n * @returns The applicant access token and status.\n */\nexport type KycServiceSubmitWrappedKeyAction = {\n type: `KycService:submitWrappedKey`;\n handler: KycService['submitWrappedKey'];\n};\n\n/**\n * Union of all KycService action types.\n */\nexport type KycServiceMethodActions =\n | KycServiceGetGeoCountryAction\n | KycServiceFetchDisclaimersAction\n | KycServiceCreateSessionAction\n | KycServiceCheckKycRequiredAction\n | KycServiceCreateUkycSessionAction\n | KycServiceSubmitWrappedKeyAction;\n"]}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * This file is auto generated.
3
+ * Do not edit manually.
4
+ */
5
+ import type { KycService } from "./KycService.cjs";
6
+ /**
7
+ * Resolves the customer's country from the geolocation source and converts it
8
+ * to an ISO 3166-1 alpha-3 code.
9
+ *
10
+ * @returns The alpha-3 country code.
11
+ * @throws If the country cannot be determined or mapped.
12
+ */
13
+ export type KycServiceGetGeoCountryAction = {
14
+ type: `KycService:getGeoCountry`;
15
+ handler: KycService['getGeoCountry'];
16
+ };
17
+ /**
18
+ * Fetches the disclaimers the customer must accept before a session is
19
+ * created.
20
+ *
21
+ * @param params - The parameters.
22
+ * @param params.country - ISO 3166-1 alpha-3 country code.
23
+ * @returns The disclaimers.
24
+ */
25
+ export type KycServiceFetchDisclaimersAction = {
26
+ type: `KycService:fetchDisclaimers`;
27
+ handler: KycService['fetchDisclaimers'];
28
+ };
29
+ /**
30
+ * Creates a vendor session via the UKYC backend.
31
+ *
32
+ * @param params - The session parameters.
33
+ * @returns The created session token.
34
+ */
35
+ export type KycServiceCreateSessionAction = {
36
+ type: `KycService:createSession`;
37
+ handler: KycService['createSession'];
38
+ };
39
+ /**
40
+ * Checks whether KYC is required for the given access token, country, and
41
+ * capabilities.
42
+ *
43
+ * @param params - The check parameters.
44
+ * @returns Whether KYC is required.
45
+ */
46
+ export type KycServiceCheckKycRequiredAction = {
47
+ type: `KycService:checkKycRequired`;
48
+ handler: KycService['checkKycRequired'];
49
+ };
50
+ /**
51
+ * Creates a UKYC session for the SumSub document-verification sub-flow.
52
+ *
53
+ * @param params - The session parameters.
54
+ * @returns The UKYC session identifiers and wrapped key.
55
+ */
56
+ export type KycServiceCreateUkycSessionAction = {
57
+ type: `KycService:createUkycSession`;
58
+ handler: KycService['createUkycSession'];
59
+ };
60
+ /**
61
+ * Exchanges the wrapped user key for a SumSub applicant access token.
62
+ *
63
+ * @param params - The exchange parameters.
64
+ * @returns The applicant access token and status.
65
+ */
66
+ export type KycServiceSubmitWrappedKeyAction = {
67
+ type: `KycService:submitWrappedKey`;
68
+ handler: KycService['submitWrappedKey'];
69
+ };
70
+ /**
71
+ * Union of all KycService action types.
72
+ */
73
+ export type KycServiceMethodActions = KycServiceGetGeoCountryAction | KycServiceFetchDisclaimersAction | KycServiceCreateSessionAction | KycServiceCheckKycRequiredAction | KycServiceCreateUkycSessionAction | KycServiceSubmitWrappedKeyAction;
74
+ //# sourceMappingURL=KycService-method-action-types.d.cts.map
@@ -0,0 +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,yBAAqB;AAE/C;;;;;;GAMG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C,IAAI,EAAE,0BAA0B,CAAC;IACjC,OAAO,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;CACtC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C,IAAI,EAAE,6BAA6B,CAAC;IACpC,OAAO,EAAE,UAAU,CAAC,kBAAkB,CAAC,CAAC;CACzC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C,IAAI,EAAE,0BAA0B,CAAC;IACjC,OAAO,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;CACtC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C,IAAI,EAAE,6BAA6B,CAAC;IACpC,OAAO,EAAE,UAAU,CAAC,kBAAkB,CAAC,CAAC;CACzC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,UAAU,CAAC,mBAAmB,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C,IAAI,EAAE,6BAA6B,CAAC;IACpC,OAAO,EAAE,UAAU,CAAC,kBAAkB,CAAC,CAAC;CACzC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAC/B,6BAA6B,GAC7B,gCAAgC,GAChC,6BAA6B,GAC7B,gCAAgC,GAChC,iCAAiC,GACjC,gCAAgC,CAAC"}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * This file is auto generated.
3
+ * Do not edit manually.
4
+ */
5
+ import type { KycService } from "./KycService.mjs";
6
+ /**
7
+ * Resolves the customer's country from the geolocation source and converts it
8
+ * to an ISO 3166-1 alpha-3 code.
9
+ *
10
+ * @returns The alpha-3 country code.
11
+ * @throws If the country cannot be determined or mapped.
12
+ */
13
+ export type KycServiceGetGeoCountryAction = {
14
+ type: `KycService:getGeoCountry`;
15
+ handler: KycService['getGeoCountry'];
16
+ };
17
+ /**
18
+ * Fetches the disclaimers the customer must accept before a session is
19
+ * created.
20
+ *
21
+ * @param params - The parameters.
22
+ * @param params.country - ISO 3166-1 alpha-3 country code.
23
+ * @returns The disclaimers.
24
+ */
25
+ export type KycServiceFetchDisclaimersAction = {
26
+ type: `KycService:fetchDisclaimers`;
27
+ handler: KycService['fetchDisclaimers'];
28
+ };
29
+ /**
30
+ * Creates a vendor session via the UKYC backend.
31
+ *
32
+ * @param params - The session parameters.
33
+ * @returns The created session token.
34
+ */
35
+ export type KycServiceCreateSessionAction = {
36
+ type: `KycService:createSession`;
37
+ handler: KycService['createSession'];
38
+ };
39
+ /**
40
+ * Checks whether KYC is required for the given access token, country, and
41
+ * capabilities.
42
+ *
43
+ * @param params - The check parameters.
44
+ * @returns Whether KYC is required.
45
+ */
46
+ export type KycServiceCheckKycRequiredAction = {
47
+ type: `KycService:checkKycRequired`;
48
+ handler: KycService['checkKycRequired'];
49
+ };
50
+ /**
51
+ * Creates a UKYC session for the SumSub document-verification sub-flow.
52
+ *
53
+ * @param params - The session parameters.
54
+ * @returns The UKYC session identifiers and wrapped key.
55
+ */
56
+ export type KycServiceCreateUkycSessionAction = {
57
+ type: `KycService:createUkycSession`;
58
+ handler: KycService['createUkycSession'];
59
+ };
60
+ /**
61
+ * Exchanges the wrapped user key for a SumSub applicant access token.
62
+ *
63
+ * @param params - The exchange parameters.
64
+ * @returns The applicant access token and status.
65
+ */
66
+ export type KycServiceSubmitWrappedKeyAction = {
67
+ type: `KycService:submitWrappedKey`;
68
+ handler: KycService['submitWrappedKey'];
69
+ };
70
+ /**
71
+ * Union of all KycService action types.
72
+ */
73
+ export type KycServiceMethodActions = KycServiceGetGeoCountryAction | KycServiceFetchDisclaimersAction | KycServiceCreateSessionAction | KycServiceCheckKycRequiredAction | KycServiceCreateUkycSessionAction | KycServiceSubmitWrappedKeyAction;
74
+ //# sourceMappingURL=KycService-method-action-types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KycService-method-action-types.d.mts","sourceRoot":"","sources":["../src/KycService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,yBAAqB;AAE/C;;;;;;GAMG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C,IAAI,EAAE,0BAA0B,CAAC;IACjC,OAAO,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;CACtC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C,IAAI,EAAE,6BAA6B,CAAC;IACpC,OAAO,EAAE,UAAU,CAAC,kBAAkB,CAAC,CAAC;CACzC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C,IAAI,EAAE,0BAA0B,CAAC;IACjC,OAAO,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;CACtC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C,IAAI,EAAE,6BAA6B,CAAC;IACpC,OAAO,EAAE,UAAU,CAAC,kBAAkB,CAAC,CAAC;CACzC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,UAAU,CAAC,mBAAmB,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C,IAAI,EAAE,6BAA6B,CAAC;IACpC,OAAO,EAAE,UAAU,CAAC,kBAAkB,CAAC,CAAC;CACzC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAC/B,6BAA6B,GAC7B,gCAAgC,GAChC,6BAA6B,GAC7B,gCAAgC,GAChC,iCAAiC,GACjC,gCAAgC,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * This file is auto generated.
3
+ * Do not edit manually.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=KycService-method-action-types.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KycService-method-action-types.mjs","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';\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 access token, 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 a UKYC session for the SumSub document-verification sub-flow.\n *\n * @param params - The session parameters.\n * @returns The UKYC session identifiers and wrapped key.\n */\nexport type KycServiceCreateUkycSessionAction = {\n type: `KycService:createUkycSession`;\n handler: KycService['createUkycSession'];\n};\n\n/**\n * Exchanges the wrapped user key for a SumSub applicant access token.\n *\n * @param params - The exchange parameters.\n * @returns The applicant access token and status.\n */\nexport type KycServiceSubmitWrappedKeyAction = {\n type: `KycService:submitWrappedKey`;\n handler: KycService['submitWrappedKey'];\n};\n\n/**\n * Union of all KycService action types.\n */\nexport type KycServiceMethodActions =\n | KycServiceGetGeoCountryAction\n | KycServiceFetchDisclaimersAction\n | KycServiceCreateSessionAction\n | KycServiceCheckKycRequiredAction\n | KycServiceCreateUkycSessionAction\n | KycServiceSubmitWrappedKeyAction;\n"]}
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _KycService_instances, _KycService_messenger, _KycService_fetch, _KycService_baseUrl, _KycService_policy, _KycService_validateResponse, _KycService_request;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.KycService = exports.serviceName = void 0;
16
+ const controller_utils_1 = require("@metamask/controller-utils");
17
+ const superstruct_1 = require("@metamask/superstruct");
18
+ const countryCodes_1 = require("./countryCodes.cjs");
19
+ // === GENERAL ===
20
+ /**
21
+ * The name of the {@link KycService}, used to namespace the service's actions.
22
+ */
23
+ exports.serviceName = 'KycService';
24
+ const KYC_API_URLS = {
25
+ production: 'https://kyc-api.cx.metamask.io',
26
+ development: 'https://kyc-api.dev-api.cx.metamask.io',
27
+ };
28
+ // === MESSENGER ===
29
+ const MESSENGER_EXPOSED_METHODS = [
30
+ 'getGeoCountry',
31
+ 'fetchDisclaimers',
32
+ 'createSession',
33
+ 'checkKycRequired',
34
+ 'createUkycSession',
35
+ 'submitWrappedKey',
36
+ ];
37
+ // === API RESPONSE SCHEMAS ===
38
+ const DisclaimerStruct = (0, superstruct_1.type)({
39
+ id: (0, superstruct_1.string)(),
40
+ display_name: (0, superstruct_1.string)(),
41
+ url: (0, superstruct_1.string)(),
42
+ });
43
+ const DisclaimersResponseStruct = (0, superstruct_1.array)(DisclaimerStruct);
44
+ const CreateSessionResponseStruct = (0, superstruct_1.type)({ sessionToken: (0, superstruct_1.string)() });
45
+ // The live KYC API returns the flag under `required`; the service normalizes
46
+ // this to `kycRequired` for consumers (see `checkKycRequired`).
47
+ const KycRequiredResponseStruct = (0, superstruct_1.type)({ required: (0, superstruct_1.boolean)() });
48
+ const UkycSessionResponseStruct = (0, superstruct_1.type)({
49
+ sessionId: (0, superstruct_1.string)(),
50
+ wrappingPublicKey: (0, superstruct_1.string)(),
51
+ idosSessionId: (0, superstruct_1.string)(),
52
+ });
53
+ const WrappedKeyResponseStruct = (0, superstruct_1.type)({
54
+ status: (0, superstruct_1.string)(),
55
+ applicantAccessToken: (0, superstruct_1.string)(),
56
+ });
57
+ // === SERVICE DEFINITION ===
58
+ /**
59
+ * `KycService` communicates with the Universal KYC (UKYC) backend to drive the
60
+ * identity + document-verification flow. It is stateless and platform-agnostic:
61
+ * HTTP is performed through an injected `fetch`, and the auth bearer token and
62
+ * geolocation come from other controllers via the messenger.
63
+ */
64
+ class KycService {
65
+ /**
66
+ * Constructs a new KycService.
67
+ *
68
+ * @param options - The constructor options.
69
+ * @param options.messenger - The messenger suited for this service.
70
+ * @param options.fetch - A function used to make HTTP requests.
71
+ * @param options.env - The environment; determines the base URL.
72
+ * @param options.baseUrl - Overrides the base URL derived from `env`.
73
+ * @param options.policyOptions - Options for the request service policy.
74
+ */
75
+ constructor({ messenger, fetch: fetchFunction, env, baseUrl, policyOptions, }) {
76
+ _KycService_instances.add(this);
77
+ _KycService_messenger.set(this, void 0);
78
+ _KycService_fetch.set(this, void 0);
79
+ _KycService_baseUrl.set(this, void 0);
80
+ _KycService_policy.set(this, void 0);
81
+ this.name = exports.serviceName;
82
+ __classPrivateFieldSet(this, _KycService_messenger, messenger, "f");
83
+ __classPrivateFieldSet(this, _KycService_fetch, fetchFunction, "f");
84
+ __classPrivateFieldSet(this, _KycService_baseUrl, baseUrl ?? KYC_API_URLS[env], "f");
85
+ __classPrivateFieldSet(this, _KycService_policy, (0, controller_utils_1.createServicePolicy)(policyOptions ?? {}), "f");
86
+ __classPrivateFieldGet(this, _KycService_messenger, "f").registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
87
+ }
88
+ /**
89
+ * Resolves the customer's country from the geolocation source and converts it
90
+ * to an ISO 3166-1 alpha-3 code.
91
+ *
92
+ * @returns The alpha-3 country code.
93
+ * @throws If the country cannot be determined or mapped.
94
+ */
95
+ async getGeoCountry() {
96
+ const location = await __classPrivateFieldGet(this, _KycService_messenger, "f").call('GeolocationController:getGeolocation');
97
+ // Guard nullish/empty geolocation with the documented domain error rather
98
+ // than letting `assert(location, string())` surface a superstruct
99
+ // assertion error (which would change how the failure reads in
100
+ // `disclaimersError`).
101
+ const alpha2 = typeof location === 'string' ? location.split('-')[0].toUpperCase() : '';
102
+ if (!alpha2 || alpha2 === 'UNKNOWN') {
103
+ throw new Error(`Unable to determine country from geolocation (got "${String(location)}").`);
104
+ }
105
+ const alpha3 = (0, countryCodes_1.alpha2ToAlpha3)(alpha2);
106
+ if (!alpha3) {
107
+ throw new Error(`Unable to map country code "${alpha2}" to an ISO 3166-1 alpha-3 code.`);
108
+ }
109
+ return alpha3;
110
+ }
111
+ /**
112
+ * Fetches the disclaimers the customer must accept before a session is
113
+ * created.
114
+ *
115
+ * @param params - The parameters.
116
+ * @param params.country - ISO 3166-1 alpha-3 country code.
117
+ * @returns The disclaimers.
118
+ */
119
+ async fetchDisclaimers({ country, }) {
120
+ const url = new URL('/vendors/moonpay/disclaimers', __classPrivateFieldGet(this, _KycService_baseUrl, "f"));
121
+ url.searchParams.set('country', country);
122
+ const data = await __classPrivateFieldGet(this, _KycService_instances, "m", _KycService_request).call(this, url, { method: 'GET' });
123
+ return __classPrivateFieldGet(this, _KycService_instances, "m", _KycService_validateResponse).call(this, data, DisclaimersResponseStruct, 'disclaimers');
124
+ }
125
+ /**
126
+ * Creates a vendor session via the UKYC backend.
127
+ *
128
+ * @param params - The session parameters.
129
+ * @returns The created session token.
130
+ */
131
+ async createSession(params) {
132
+ const url = new URL('/vendors/moonpay/sessions', __classPrivateFieldGet(this, _KycService_baseUrl, "f"));
133
+ const data = await __classPrivateFieldGet(this, _KycService_instances, "m", _KycService_request).call(this, url, {
134
+ method: 'POST',
135
+ body: JSON.stringify(params),
136
+ });
137
+ return __classPrivateFieldGet(this, _KycService_instances, "m", _KycService_validateResponse).call(this, data, CreateSessionResponseStruct, 'sessions');
138
+ }
139
+ /**
140
+ * Checks whether KYC is required for the given access token, country, and
141
+ * capabilities.
142
+ *
143
+ * @param params - The check parameters.
144
+ * @returns Whether KYC is required.
145
+ */
146
+ async checkKycRequired(params) {
147
+ const url = new URL('/vendors/moonpay/kyc-required', __classPrivateFieldGet(this, _KycService_baseUrl, "f"));
148
+ const data = await __classPrivateFieldGet(this, _KycService_instances, "m", _KycService_request).call(this, url, {
149
+ method: 'POST',
150
+ body: JSON.stringify({
151
+ accessToken: params.accessToken,
152
+ country: params.country,
153
+ capabilities: params.capabilities ?? [{ product: 'ramps' }],
154
+ }),
155
+ });
156
+ const { required } = __classPrivateFieldGet(this, _KycService_instances, "m", _KycService_validateResponse).call(this, data, KycRequiredResponseStruct, 'kyc-required');
157
+ return { kycRequired: required };
158
+ }
159
+ /**
160
+ * Creates a UKYC session for the SumSub document-verification sub-flow.
161
+ *
162
+ * @param params - The session parameters.
163
+ * @returns The UKYC session identifiers and wrapped key.
164
+ */
165
+ async createUkycSession(params) {
166
+ const url = new URL('/sessions', __classPrivateFieldGet(this, _KycService_baseUrl, "f"));
167
+ const data = await __classPrivateFieldGet(this, _KycService_instances, "m", _KycService_request).call(this, url, {
168
+ method: 'POST',
169
+ body: JSON.stringify({
170
+ vendorId: 'moonpay',
171
+ vendorUserId: 'mockedId',
172
+ jwtToken: params.jwtToken,
173
+ vendorMetadata: params.vendorMetadata,
174
+ }),
175
+ });
176
+ return __classPrivateFieldGet(this, _KycService_instances, "m", _KycService_validateResponse).call(this, data, UkycSessionResponseStruct, 'UKYC sessions');
177
+ }
178
+ /**
179
+ * Exchanges the wrapped user key for a SumSub applicant access token.
180
+ *
181
+ * @param params - The exchange parameters.
182
+ * @returns The applicant access token and status.
183
+ */
184
+ async submitWrappedKey(params) {
185
+ const url = new URL(`/sessions/${encodeURIComponent(params.sessionId)}/wrapped-key`, __classPrivateFieldGet(this, _KycService_baseUrl, "f"));
186
+ const data = await __classPrivateFieldGet(this, _KycService_instances, "m", _KycService_request).call(this, url, {
187
+ method: 'POST',
188
+ body: JSON.stringify({
189
+ wrappedUserKey: params.wrappedUserKey,
190
+ jwtToken: params.jwtToken,
191
+ idosSessionId: params.idosSessionId,
192
+ }),
193
+ });
194
+ return __classPrivateFieldGet(this, _KycService_instances, "m", _KycService_validateResponse).call(this, data, WrappedKeyResponseStruct, 'wrapped-key');
195
+ }
196
+ }
197
+ exports.KycService = KycService;
198
+ _KycService_messenger = new WeakMap(), _KycService_fetch = new WeakMap(), _KycService_baseUrl = new WeakMap(), _KycService_policy = new WeakMap(), _KycService_instances = new WeakSet(), _KycService_validateResponse = function _KycService_validateResponse(data, struct, apiName) {
199
+ try {
200
+ (0, superstruct_1.assert)(data, struct);
201
+ return data;
202
+ }
203
+ catch (error) {
204
+ const detail = error instanceof superstruct_1.StructError
205
+ ? `${error.message} (received: ${JSON.stringify(data)})`
206
+ : String(error);
207
+ throw new Error(`Malformed response received from ${apiName} API: ${detail}`);
208
+ }
209
+ }, _KycService_request =
210
+ /**
211
+ * Performs an authenticated JSON request wrapped in the service policy.
212
+ *
213
+ * @param url - The request URL.
214
+ * @param init - The request init (method, body).
215
+ * @returns The parsed JSON response.
216
+ */
217
+ async function _KycService_request(url, init) {
218
+ const bearerToken = await __classPrivateFieldGet(this, _KycService_messenger, "f").call('AuthenticationController:getBearerToken');
219
+ (0, superstruct_1.assert)(bearerToken, (0, superstruct_1.string)());
220
+ if (!bearerToken) {
221
+ throw new Error('Unable to obtain an authentication bearer token — is the wallet signed in?');
222
+ }
223
+ const response = await __classPrivateFieldGet(this, _KycService_policy, "f").execute(async () => {
224
+ const localResponse = await __classPrivateFieldGet(this, _KycService_fetch, "f").call(this, url.toString(), {
225
+ ...init,
226
+ headers: {
227
+ 'Content-Type': 'application/json',
228
+ Authorization: `Bearer ${bearerToken}`,
229
+ },
230
+ });
231
+ if (!localResponse.ok) {
232
+ throw new controller_utils_1.HttpError(localResponse.status, `Fetching '${url.toString()}' failed with status '${localResponse.status}'`);
233
+ }
234
+ return localResponse;
235
+ });
236
+ return response.json();
237
+ };
238
+ //# sourceMappingURL=KycService.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KycService.cjs","sourceRoot":"","sources":["../src/KycService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;A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AO,EAAE;gBACP,cAAc,EAAE,kBAAkB;gBAClC,aAAa,EAAE,UAAU,WAAW,EAAE;aACvC;SACF,CAAC,CAAC;QACH,IAAI,CAAC,aAAa,CAAC,EAAE,EAAE,CAAC;YACtB,MAAM,IAAI,4BAAS,CACjB,aAAa,CAAC,MAAM,EACpB,aAAa,GAAG,CAAC,QAAQ,EAAE,yBAAyB,aAAa,CAAC,MAAM,GAAG,CAC5E,CAAC;QACJ,CAAC;QACD,OAAO,aAAa,CAAC;IACvB,CAAC,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport { createServicePolicy, HttpError } from '@metamask/controller-utils';\nimport type { GeolocationControllerGetGeolocationAction } from '@metamask/geolocation-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationControllerGetBearerTokenAction } from '@metamask/profile-sync-controller/auth';\nimport type { Infer, Struct } from '@metamask/superstruct';\nimport {\n array,\n assert,\n boolean,\n string,\n StructError,\n type,\n} from '@metamask/superstruct';\n\nimport { alpha2ToAlpha3 } from './countryCodes';\nimport type { KycServiceMethodActions } from './KycService-method-action-types';\nimport type { KycDisclaimer } from './types';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link KycService}, used to namespace the service's actions.\n */\nexport const serviceName = 'KycService';\n\n/**\n * The supported environments for the Universal KYC API.\n */\nexport type KycServiceEnvironment = 'production' | 'development';\n\nconst KYC_API_URLS: Record<KycServiceEnvironment, string> = {\n production: 'https://kyc-api.cx.metamask.io',\n development: 'https://kyc-api.dev-api.cx.metamask.io',\n};\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getGeoCountry',\n 'fetchDisclaimers',\n 'createSession',\n 'checkKycRequired',\n 'createUkycSession',\n 'submitWrappedKey',\n] as const;\n\n/**\n * Actions that {@link KycService} exposes to other consumers.\n */\nexport type KycServiceActions = KycServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link KycService} calls.\n */\ntype AllowedActions =\n | AuthenticationControllerGetBearerTokenAction\n | GeolocationControllerGetGeolocationAction;\n\n/**\n * Events that {@link KycService} exposes to other consumers.\n */\nexport type KycServiceEvents = never;\n\n/**\n * Events from other messengers that {@link KycService} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link KycService}.\n */\nexport type KycServiceMessenger = Messenger<\n typeof serviceName,\n KycServiceActions | AllowedActions,\n KycServiceEvents | AllowedEvents\n>;\n\n/**\n * Options for constructing a {@link KycService}.\n */\nexport type KycServiceOptions = {\n messenger: KycServiceMessenger;\n fetch: typeof fetch;\n env: KycServiceEnvironment;\n /**\n * Overrides the base URL derived from `env`. When provided, this value is\n * used verbatim as the base URL for all requests, which is useful for\n * targeting a local or staging KYC API.\n */\n baseUrl?: string;\n policyOptions?: CreateServicePolicyOptions;\n};\n\n// === API RESPONSE SCHEMAS ===\n\nconst DisclaimerStruct = type({\n id: string(),\n display_name: string(),\n url: string(),\n});\nconst DisclaimersResponseStruct = array(DisclaimerStruct);\n\nconst CreateSessionResponseStruct = type({ sessionToken: string() });\n\n// The live KYC API returns the flag under `required`; the service normalizes\n// this to `kycRequired` for consumers (see `checkKycRequired`).\nconst KycRequiredResponseStruct = type({ required: boolean() });\n\nconst UkycSessionResponseStruct = type({\n sessionId: string(),\n wrappingPublicKey: string(),\n idosSessionId: string(),\n});\nexport type UkycSessionResponse = Infer<typeof UkycSessionResponseStruct>;\n\nconst WrappedKeyResponseStruct = type({\n status: string(),\n applicantAccessToken: string(),\n});\nexport type WrappedKeyResponse = Infer<typeof WrappedKeyResponseStruct>;\n\n// === PARAM TYPES ===\n\nexport type CreateSessionParams = {\n email: string;\n termsAcceptedAt: string;\n disclaimerIds: string[];\n};\n\nexport type CheckKycRequiredParams = {\n accessToken: string;\n country: string;\n capabilities?: { product: string }[];\n};\n\nexport type CreateUkycSessionParams = {\n jwtToken: string;\n vendorMetadata: Record<string, unknown>;\n};\n\nexport type SubmitWrappedKeyParams = {\n sessionId: string;\n wrappedUserKey: string;\n idosSessionId: string;\n jwtToken: string;\n};\n\n// === SERVICE DEFINITION ===\n\n/**\n * `KycService` communicates with the Universal KYC (UKYC) backend to drive the\n * identity + document-verification flow. It is stateless and platform-agnostic:\n * HTTP is performed through an injected `fetch`, and the auth bearer token and\n * geolocation come from other controllers via the messenger.\n */\nexport class KycService {\n readonly name: typeof serviceName;\n\n readonly #messenger: KycServiceMessenger;\n\n readonly #fetch: typeof fetch;\n\n readonly #baseUrl: string;\n\n readonly #policy: ServicePolicy;\n\n /**\n * Constructs a new KycService.\n *\n * @param options - The constructor options.\n * @param options.messenger - The messenger suited for this service.\n * @param options.fetch - A function used to make HTTP requests.\n * @param options.env - The environment; determines the base URL.\n * @param options.baseUrl - Overrides the base URL derived from `env`.\n * @param options.policyOptions - Options for the request service policy.\n */\n constructor({\n messenger,\n fetch: fetchFunction,\n env,\n baseUrl,\n policyOptions,\n }: KycServiceOptions) {\n this.name = serviceName;\n this.#messenger = messenger;\n this.#fetch = fetchFunction;\n this.#baseUrl = baseUrl ?? KYC_API_URLS[env];\n this.#policy = createServicePolicy(policyOptions ?? {});\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\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 */\n async getGeoCountry(): Promise<string> {\n const location = await this.#messenger.call(\n 'GeolocationController:getGeolocation',\n );\n // Guard nullish/empty geolocation with the documented domain error rather\n // than letting `assert(location, string())` surface a superstruct\n // assertion error (which would change how the failure reads in\n // `disclaimersError`).\n const alpha2 =\n typeof location === 'string' ? location.split('-')[0].toUpperCase() : '';\n if (!alpha2 || alpha2 === 'UNKNOWN') {\n throw new Error(\n `Unable to determine country from geolocation (got \"${String(\n location,\n )}\").`,\n );\n }\n const alpha3 = alpha2ToAlpha3(alpha2);\n if (!alpha3) {\n throw new Error(\n `Unable to map country code \"${alpha2}\" to an ISO 3166-1 alpha-3 code.`,\n );\n }\n return alpha3;\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 */\n async fetchDisclaimers({\n country,\n }: {\n country: string;\n }): Promise<KycDisclaimer[]> {\n const url = new URL('/vendors/moonpay/disclaimers', this.#baseUrl);\n url.searchParams.set('country', country);\n const data = await this.#request(url, { method: 'GET' });\n return this.#validateResponse(\n data,\n DisclaimersResponseStruct,\n 'disclaimers',\n ) as KycDisclaimer[];\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 */\n async createSession(\n params: CreateSessionParams,\n ): Promise<Infer<typeof CreateSessionResponseStruct>> {\n const url = new URL('/vendors/moonpay/sessions', this.#baseUrl);\n const data = await this.#request(url, {\n method: 'POST',\n body: JSON.stringify(params),\n });\n return this.#validateResponse(\n data,\n CreateSessionResponseStruct,\n 'sessions',\n );\n }\n\n /**\n * Checks whether KYC is required for the given access token, country, and\n * capabilities.\n *\n * @param params - The check parameters.\n * @returns Whether KYC is required.\n */\n async checkKycRequired(\n params: CheckKycRequiredParams,\n ): Promise<{ kycRequired: boolean }> {\n const url = new URL('/vendors/moonpay/kyc-required', this.#baseUrl);\n const data = await this.#request(url, {\n method: 'POST',\n body: JSON.stringify({\n accessToken: params.accessToken,\n country: params.country,\n capabilities: params.capabilities ?? [{ product: 'ramps' }],\n }),\n });\n const { required } = this.#validateResponse(\n data,\n KycRequiredResponseStruct,\n 'kyc-required',\n );\n return { kycRequired: required };\n }\n\n /**\n * Creates a UKYC session for the SumSub document-verification sub-flow.\n *\n * @param params - The session parameters.\n * @returns The UKYC session identifiers and wrapped key.\n */\n async createUkycSession(\n params: CreateUkycSessionParams,\n ): Promise<UkycSessionResponse> {\n const url = new URL('/sessions', this.#baseUrl);\n const data = await this.#request(url, {\n method: 'POST',\n body: JSON.stringify({\n vendorId: 'moonpay',\n vendorUserId: 'mockedId',\n jwtToken: params.jwtToken,\n vendorMetadata: params.vendorMetadata,\n }),\n });\n return this.#validateResponse(\n data,\n UkycSessionResponseStruct,\n 'UKYC sessions',\n );\n }\n\n /**\n * Exchanges the wrapped user key for a SumSub applicant access token.\n *\n * @param params - The exchange parameters.\n * @returns The applicant access token and status.\n */\n async submitWrappedKey(\n params: SubmitWrappedKeyParams,\n ): Promise<WrappedKeyResponse> {\n const url = new URL(\n `/sessions/${encodeURIComponent(params.sessionId)}/wrapped-key`,\n this.#baseUrl,\n );\n const data = await this.#request(url, {\n method: 'POST',\n body: JSON.stringify({\n wrappedUserKey: params.wrappedUserKey,\n jwtToken: params.jwtToken,\n idosSessionId: params.idosSessionId,\n }),\n });\n return this.#validateResponse(\n data,\n WrappedKeyResponseStruct,\n 'wrapped-key',\n );\n }\n\n /**\n * Validates a parsed API response against a superstruct schema, throwing a\n * descriptive error when the response does not match.\n *\n * Unlike a bare `Struct.is` check, this surfaces exactly which field was\n * missing or had the wrong type, which is essential for diagnosing shape\n * mismatches between the client and the live API.\n *\n * @param data - The parsed response body.\n * @param struct - The superstruct schema the body is expected to satisfy.\n * @param apiName - A human-readable name of the API, used in the error message.\n * @returns The validated, typed response.\n * @throws If `data` does not match `struct`.\n */\n #validateResponse<Type, Schema>(\n data: unknown,\n struct: Struct<Type, Schema>,\n apiName: string,\n ): Type {\n try {\n assert(data, struct);\n return data;\n } catch (error) {\n const detail =\n error instanceof StructError\n ? `${error.message} (received: ${JSON.stringify(data)})`\n : String(error);\n throw new Error(\n `Malformed response received from ${apiName} API: ${detail}`,\n );\n }\n }\n\n /**\n * Performs an authenticated JSON request wrapped in the service policy.\n *\n * @param url - The request URL.\n * @param init - The request init (method, body).\n * @returns The parsed JSON response.\n */\n async #request(url: URL, init: RequestInit): Promise<unknown> {\n const bearerToken = await this.#messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n assert(bearerToken, string());\n if (!bearerToken) {\n throw new Error(\n 'Unable to obtain an authentication bearer token — is the wallet signed in?',\n );\n }\n\n const response = await this.#policy.execute(async () => {\n const localResponse = await this.#fetch(url.toString(), {\n ...init,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n if (!localResponse.ok) {\n throw new HttpError(\n localResponse.status,\n `Fetching '${url.toString()}' failed with status '${localResponse.status}'`,\n );\n }\n return localResponse;\n });\n\n return response.json();\n }\n}\n"]}