@metamask-previews/kyc-controller 0.0.0-preview-8bfa290fb → 0.2.0-preview-0a30e47

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 (203) hide show
  1. package/CHANGELOG.md +30 -49
  2. package/dist/{KycController-method-action-types.d.mts → KycController-method-action-types.d.ts} +35 -7
  3. package/dist/KycController-method-action-types.d.ts.map +1 -0
  4. package/dist/{KycController-method-action-types.mjs → KycController-method-action-types.js} +1 -1
  5. package/dist/KycController-method-action-types.js.map +1 -0
  6. package/dist/{KycController.d.mts → KycController.d.ts} +87 -45
  7. package/dist/KycController.d.ts.map +1 -0
  8. package/dist/KycController.js +1991 -0
  9. package/dist/KycController.js.map +1 -0
  10. package/dist/{KycService-method-action-types.d.mts → KycService-method-action-types.d.ts} +16 -16
  11. package/dist/KycService-method-action-types.d.ts.map +1 -0
  12. package/dist/{KycService-method-action-types.mjs → KycService-method-action-types.js} +1 -1
  13. package/dist/KycService-method-action-types.js.map +1 -0
  14. package/dist/{KycService.d.mts → KycService.d.ts} +23 -23
  15. package/dist/KycService.d.ts.map +1 -0
  16. package/dist/{KycService.mjs → KycService.js} +194 -185
  17. package/dist/KycService.js.map +1 -0
  18. package/dist/{countryCodes.d.cts → countryCodes.d.ts} +1 -1
  19. package/dist/countryCodes.d.ts.map +1 -0
  20. package/dist/{countryCodes.mjs → countryCodes.js} +1 -1
  21. package/dist/countryCodes.js.map +1 -0
  22. package/dist/{crypto.d.mts → crypto.d.ts} +1 -1
  23. package/dist/crypto.d.ts.map +1 -0
  24. package/dist/{crypto.mjs → crypto.js} +7 -7
  25. package/dist/crypto.js.map +1 -0
  26. package/dist/{encoding.d.mts → encoding.d.ts} +1 -1
  27. package/dist/encoding.d.ts.map +1 -0
  28. package/dist/{encoding.mjs → encoding.js} +2 -2
  29. package/dist/encoding.js.map +1 -0
  30. package/dist/index.d.ts +19 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +12 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/{logger.d.cts → logger.d.ts} +2 -3
  35. package/dist/logger.d.ts.map +1 -0
  36. package/dist/{logger.mjs → logger.js} +2 -2
  37. package/dist/logger.js.map +1 -0
  38. package/dist/{selectors.d.mts → selectors.d.ts} +4 -4
  39. package/dist/selectors.d.ts.map +1 -0
  40. package/dist/{selectors.mjs → selectors.js} +2 -2
  41. package/dist/selectors.js.map +1 -0
  42. package/dist/{types.d.cts → types.d.ts} +72 -13
  43. package/dist/types.d.ts.map +1 -0
  44. package/dist/{types.mjs → types.js} +1 -1
  45. package/dist/types.js.map +1 -0
  46. package/dist/ukyc/{constants.d.mts → constants.d.ts} +9 -9
  47. package/dist/ukyc/constants.d.ts.map +1 -0
  48. package/dist/ukyc/{constants.mjs → constants.js} +1 -1
  49. package/dist/ukyc/constants.js.map +1 -0
  50. package/dist/ukyc/{deriveClientMaterial.d.cts → deriveClientMaterial.d.ts} +1 -1
  51. package/dist/ukyc/deriveClientMaterial.d.ts.map +1 -0
  52. package/dist/ukyc/{deriveClientMaterial.mjs → deriveClientMaterial.js} +7 -7
  53. package/dist/ukyc/deriveClientMaterial.js.map +1 -0
  54. package/dist/ukyc/{jwtChain.d.mts → jwtChain.d.ts} +1 -1
  55. package/dist/ukyc/jwtChain.d.ts.map +1 -0
  56. package/dist/ukyc/{jwtChain.mjs → jwtChain.js} +4 -4
  57. package/dist/ukyc/jwtChain.js.map +1 -0
  58. package/dist/ukyc/{localUserSecret.d.mts → localUserSecret.d.ts} +1 -1
  59. package/dist/ukyc/localUserSecret.d.ts.map +1 -0
  60. package/dist/ukyc/{localUserSecret.mjs → localUserSecret.js} +4 -4
  61. package/dist/ukyc/localUserSecret.js.map +1 -0
  62. package/dist/ukyc/{storageAccessToken.d.mts → storageAccessToken.d.ts} +2 -2
  63. package/dist/ukyc/storageAccessToken.d.ts.map +1 -0
  64. package/dist/ukyc/{storageAccessToken.mjs → storageAccessToken.js} +5 -5
  65. package/dist/ukyc/storageAccessToken.js.map +1 -0
  66. package/dist/ukyc/{testToken.d.mts → testToken.d.ts} +2 -2
  67. package/dist/ukyc/testToken.d.ts.map +1 -0
  68. package/dist/ukyc/{testToken.mjs → testToken.js} +5 -5
  69. package/dist/ukyc/testToken.js.map +1 -0
  70. package/dist/ukyc/{wrapEncryptionKey.d.mts → wrapEncryptionKey.d.ts} +1 -1
  71. package/dist/ukyc/wrapEncryptionKey.d.ts.map +1 -0
  72. package/dist/ukyc/{wrapEncryptionKey.mjs → wrapEncryptionKey.js} +3 -4
  73. package/dist/ukyc/wrapEncryptionKey.js.map +1 -0
  74. package/dist/ukyc/{wrappedRelayPayload.d.mts → wrappedRelayPayload.d.ts} +3 -3
  75. package/dist/ukyc/wrappedRelayPayload.d.ts.map +1 -0
  76. package/dist/ukyc/{wrappedRelayPayload.mjs → wrappedRelayPayload.js} +2 -2
  77. package/dist/ukyc/wrappedRelayPayload.js.map +1 -0
  78. package/dist/vendorDisclaimerAcceptance.d.ts +39 -0
  79. package/dist/vendorDisclaimerAcceptance.d.ts.map +1 -0
  80. package/dist/vendorDisclaimerAcceptance.js +67 -0
  81. package/dist/vendorDisclaimerAcceptance.js.map +1 -0
  82. package/dist/vendors/MoonPayFrameHandler.d.ts +74 -0
  83. package/dist/vendors/MoonPayFrameHandler.d.ts.map +1 -0
  84. package/dist/vendors/MoonPayFrameHandler.js +218 -0
  85. package/dist/vendors/MoonPayFrameHandler.js.map +1 -0
  86. package/package.json +19 -23
  87. package/dist/KycController-method-action-types.cjs +0 -7
  88. package/dist/KycController-method-action-types.cjs.map +0 -1
  89. package/dist/KycController-method-action-types.d.cts +0 -239
  90. package/dist/KycController-method-action-types.d.cts.map +0 -1
  91. package/dist/KycController-method-action-types.d.mts.map +0 -1
  92. package/dist/KycController-method-action-types.mjs.map +0 -1
  93. package/dist/KycController.cjs +0 -1882
  94. package/dist/KycController.cjs.map +0 -1
  95. package/dist/KycController.d.cts +0 -395
  96. package/dist/KycController.d.cts.map +0 -1
  97. package/dist/KycController.d.mts.map +0 -1
  98. package/dist/KycController.mjs +0 -1877
  99. package/dist/KycController.mjs.map +0 -1
  100. package/dist/KycService-method-action-types.cjs +0 -7
  101. package/dist/KycService-method-action-types.cjs.map +0 -1
  102. package/dist/KycService-method-action-types.d.cts +0 -220
  103. package/dist/KycService-method-action-types.d.cts.map +0 -1
  104. package/dist/KycService-method-action-types.d.mts.map +0 -1
  105. package/dist/KycService-method-action-types.mjs.map +0 -1
  106. package/dist/KycService.cjs +0 -637
  107. package/dist/KycService.cjs.map +0 -1
  108. package/dist/KycService.d.cts +0 -552
  109. package/dist/KycService.d.cts.map +0 -1
  110. package/dist/KycService.d.mts.map +0 -1
  111. package/dist/KycService.mjs.map +0 -1
  112. package/dist/countryCodes.cjs +0 -274
  113. package/dist/countryCodes.cjs.map +0 -1
  114. package/dist/countryCodes.d.cts.map +0 -1
  115. package/dist/countryCodes.d.mts +0 -18
  116. package/dist/countryCodes.d.mts.map +0 -1
  117. package/dist/countryCodes.mjs.map +0 -1
  118. package/dist/crypto.cjs +0 -154
  119. package/dist/crypto.cjs.map +0 -1
  120. package/dist/crypto.d.cts +0 -84
  121. package/dist/crypto.d.cts.map +0 -1
  122. package/dist/crypto.d.mts.map +0 -1
  123. package/dist/crypto.mjs.map +0 -1
  124. package/dist/encoding.cjs +0 -40
  125. package/dist/encoding.cjs.map +0 -1
  126. package/dist/encoding.d.cts +0 -24
  127. package/dist/encoding.d.cts.map +0 -1
  128. package/dist/encoding.d.mts.map +0 -1
  129. package/dist/encoding.mjs.map +0 -1
  130. package/dist/index.cjs +0 -37
  131. package/dist/index.cjs.map +0 -1
  132. package/dist/index.d.cts +0 -19
  133. package/dist/index.d.cts.map +0 -1
  134. package/dist/index.d.mts +0 -19
  135. package/dist/index.d.mts.map +0 -1
  136. package/dist/index.mjs +0 -12
  137. package/dist/index.mjs.map +0 -1
  138. package/dist/logger.cjs +0 -9
  139. package/dist/logger.cjs.map +0 -1
  140. package/dist/logger.d.cts.map +0 -1
  141. package/dist/logger.d.mts +0 -6
  142. package/dist/logger.d.mts.map +0 -1
  143. package/dist/logger.mjs.map +0 -1
  144. package/dist/selectors.cjs +0 -30
  145. package/dist/selectors.cjs.map +0 -1
  146. package/dist/selectors.d.cts +0 -24
  147. package/dist/selectors.d.cts.map +0 -1
  148. package/dist/selectors.d.mts.map +0 -1
  149. package/dist/selectors.mjs.map +0 -1
  150. package/dist/types.cjs +0 -10
  151. package/dist/types.cjs.map +0 -1
  152. package/dist/types.d.cts.map +0 -1
  153. package/dist/types.d.mts +0 -217
  154. package/dist/types.d.mts.map +0 -1
  155. package/dist/types.mjs.map +0 -1
  156. package/dist/ukyc/constants.cjs +0 -75
  157. package/dist/ukyc/constants.cjs.map +0 -1
  158. package/dist/ukyc/constants.d.cts +0 -69
  159. package/dist/ukyc/constants.d.cts.map +0 -1
  160. package/dist/ukyc/constants.d.mts.map +0 -1
  161. package/dist/ukyc/constants.mjs.map +0 -1
  162. package/dist/ukyc/deriveClientMaterial.cjs +0 -65
  163. package/dist/ukyc/deriveClientMaterial.cjs.map +0 -1
  164. package/dist/ukyc/deriveClientMaterial.d.cts.map +0 -1
  165. package/dist/ukyc/deriveClientMaterial.d.mts +0 -54
  166. package/dist/ukyc/deriveClientMaterial.d.mts.map +0 -1
  167. package/dist/ukyc/deriveClientMaterial.mjs.map +0 -1
  168. package/dist/ukyc/jwtChain.cjs +0 -54
  169. package/dist/ukyc/jwtChain.cjs.map +0 -1
  170. package/dist/ukyc/jwtChain.d.cts +0 -40
  171. package/dist/ukyc/jwtChain.d.cts.map +0 -1
  172. package/dist/ukyc/jwtChain.d.mts.map +0 -1
  173. package/dist/ukyc/jwtChain.mjs.map +0 -1
  174. package/dist/ukyc/localUserSecret.cjs +0 -98
  175. package/dist/ukyc/localUserSecret.cjs.map +0 -1
  176. package/dist/ukyc/localUserSecret.d.cts +0 -65
  177. package/dist/ukyc/localUserSecret.d.cts.map +0 -1
  178. package/dist/ukyc/localUserSecret.d.mts.map +0 -1
  179. package/dist/ukyc/localUserSecret.mjs.map +0 -1
  180. package/dist/ukyc/storageAccessToken.cjs +0 -139
  181. package/dist/ukyc/storageAccessToken.cjs.map +0 -1
  182. package/dist/ukyc/storageAccessToken.d.cts +0 -99
  183. package/dist/ukyc/storageAccessToken.d.cts.map +0 -1
  184. package/dist/ukyc/storageAccessToken.d.mts.map +0 -1
  185. package/dist/ukyc/storageAccessToken.mjs.map +0 -1
  186. package/dist/ukyc/testToken.cjs +0 -61
  187. package/dist/ukyc/testToken.cjs.map +0 -1
  188. package/dist/ukyc/testToken.d.cts +0 -50
  189. package/dist/ukyc/testToken.d.cts.map +0 -1
  190. package/dist/ukyc/testToken.d.mts.map +0 -1
  191. package/dist/ukyc/testToken.mjs.map +0 -1
  192. package/dist/ukyc/wrapEncryptionKey.cjs +0 -31
  193. package/dist/ukyc/wrapEncryptionKey.cjs.map +0 -1
  194. package/dist/ukyc/wrapEncryptionKey.d.cts +0 -36
  195. package/dist/ukyc/wrapEncryptionKey.d.cts.map +0 -1
  196. package/dist/ukyc/wrapEncryptionKey.d.mts.map +0 -1
  197. package/dist/ukyc/wrapEncryptionKey.mjs.map +0 -1
  198. package/dist/ukyc/wrappedRelayPayload.cjs +0 -32
  199. package/dist/ukyc/wrappedRelayPayload.cjs.map +0 -1
  200. package/dist/ukyc/wrappedRelayPayload.d.cts +0 -35
  201. package/dist/ukyc/wrappedRelayPayload.d.cts.map +0 -1
  202. package/dist/ukyc/wrappedRelayPayload.d.mts.map +0 -1
  203. package/dist/ukyc/wrappedRelayPayload.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KycService.js","sourceRoot":"","sources":["../src/KycService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAO9D,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAKvD,OAAO,EACL,KAAK,EACL,MAAM,EACN,OAAO,EACP,KAAK,E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AQ,CAAC,IAAI,EAAE,CAAC;gBACjD,IAAI,SAAS,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE,CAAC;oBAC/C,MAAM,MAAM,GAAG,SAAoC,CAAC;oBACpD,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;wBACvC,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC;oBAC1B,CAAC;yBAAM,IAAI,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,EAAE,CAAC;wBAC5C,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC;oBACxB,CAAC;gBACH,CAAC;YACH,CAAC;YAAC,MAAM,CAAC;gBACP,4DAA4D;YAC9D,CAAC;YACD,MAAM,IAAI,SAAS,CACjB,QAAQ,CAAC,MAAM,EACf,aAAa,GAAG,CAAC,QAAQ,EAAE,yBAAyB,QAAQ,CAAC,MAAM,IACjE,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,EAC3B,EAAE,CACH,CAAC;QACJ,CAAC;QAED,wDAAwD;QACxD,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YAC5B,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAS,CAAC;IACzC,CAAC;CACF","sourcesContent":["import { BaseDataService } from '@metamask/base-data-service';\nimport type {\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n} from '@metamask/base-data-service';\nimport type { CreateServicePolicyOptions } from '@metamask/controller-utils';\nimport { 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 enums,\n optional,\n string,\n StructError,\n type,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\nimport type { QueryClientConfig } from '@tanstack/query-core';\n\nimport { alpha2ToAlpha3 } from './countryCodes.js';\nimport type { KycServiceMethodActions } from './KycService-method-action-types.js';\nimport type {\n KycConsentRecord,\n KycDisclaimer,\n KycDisclaimersCatalog,\n KycSessionDisclaimers,\n KycSessionStatus,\n KycUserStatusResponse,\n KycVendor,\n KycVendorSigning,\n} from './types.js';\nimport { UKYC_JWKS_PATH } from './ukyc/constants.js';\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// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getGeoCountry',\n 'fetchVendorDisclaimers',\n 'createSession',\n 'checkKycRequired',\n 'createVendorCustomer',\n 'submitVendorDisclaimers',\n 'fetchSessionDisclaimersByCountry',\n 'fetchSessionDisclaimersBySessionId',\n 'submitSessionDisclaimers',\n 'fetchKycStatus',\n 'fetchIdosEnclaveJwks',\n 'fetchIdosRelayJwks',\n 'createUkycSession',\n 'setAuthorizations',\n 'createJourney',\n 'getSessionStatus',\n] as const;\n\n/**\n * Invalidates cached queries serviced by {@link KycService}.\n */\nexport type KycServiceInvalidateQueriesAction =\n DataServiceInvalidateQueriesAction<typeof serviceName>;\n\n/**\n * Actions that {@link KycService} exposes to other consumers.\n */\nexport type KycServiceActions =\n | KycServiceMethodActions\n | KycServiceInvalidateQueriesAction;\n\n/**\n * Actions from other messengers that {@link KycService} calls.\n */\ntype AllowedActions =\n | AuthenticationControllerGetBearerTokenAction\n | GeolocationControllerGetGeolocationAction;\n\n/**\n * Published when {@link KycService}'s cache is updated.\n */\nexport type KycServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<\n typeof serviceName\n>;\n\n/**\n * Published when a single key within {@link KycService}'s cache is updated.\n */\nexport type KycServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\n/**\n * Events that {@link KycService} exposes to other consumers.\n */\nexport type KycServiceEvents =\n | KycServiceCacheUpdatedEvent\n | KycServiceGranularCacheUpdatedEvent;\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 /**\n * A function used to make HTTP requests. Defaults to the runtime's native\n * `fetch`, so consumers do not need to inject one on platforms where `fetch`\n * is available globally (browser, React Native, Node 18+).\n */\n fetch?: typeof fetch;\n /**\n * Mandatory value that sets the base url to KYC api\n */\n baseUrl: string;\n /**\n * Base URL of the idOS enclave, from which the JWKS used to\n * verify the `encryptionDataKey` schema's `jwtChain` is fetched.\n */\n idosEnclaveBaseUrl?: string;\n /**\n * Base URL of the idOS relay, from which the JWKS used to verify the\n * `ukycCapabilityToken` schema's `jwtChain` is fetched.\n */\n idosRelayBaseUrl?: string;\n /**\n * Shared configuration applied to all queries exposed by the service (e.g. a\n * default `staleTime`/`gcTime`). Each data service gets its own\n * `QueryClient`.\n */\n queryClientConfig?: QueryClientConfig;\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 VendorSigningStruct = type({\n id: string(),\n customer_id: string(),\n content_id: optional(string()),\n});\nconst VendorSigningsResponseStruct = array(VendorSigningStruct);\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\n// The session server's public key, in JWK-like form, returned inside an\n// encryption schema from `POST /sessions`. `x` is the base64url public key\n// used to wrap a secret for that schema.\nconst ServerPublicKeyStruct = type({\n kty: string(),\n crv: string(),\n x: string(),\n kid: optional(string()),\n alg: optional(string()),\n use: optional(string()),\n});\n\nconst EncryptionSchemaStruct = type({\n serverPublicKey: ServerPublicKeyStruct,\n jwtChain: string(),\n});\nexport type EncryptionSchema = Infer<typeof EncryptionSchemaStruct>;\n\n// A single Ed25519 (OKP) JWK. `type` (not `object`) keeps optional/extra JWK\n// fields (`use`, `alg`) from failing validation.\nconst JwkStruct = type({\n kty: string(),\n crv: string(),\n x: string(),\n kid: string(),\n});\nconst JwksResponseStruct = type({ keys: array(JwkStruct) });\nexport type JwksResponse = Infer<typeof JwksResponseStruct>;\n\nconst UkycSessionResponseStruct = type({\n sessionId: string(),\n // Per-secret wrapping material so the client can seal the\n // `data_encryption_key` and the `ukyc_capability_token` independently.\n encryptionDataKey: EncryptionSchemaStruct,\n ukycCapabilityToken: EncryptionSchemaStruct,\n});\nexport type UkycSessionResponse = Infer<typeof UkycSessionResponseStruct>;\n\nconst ApplicantAccessTokenResponseStruct = type({\n status: string(),\n applicantAccessToken: string(),\n});\nexport type ApplicantAccessTokenResponse = Infer<\n typeof ApplicantAccessTokenResponseStruct\n>;\n\nconst SessionStatusResponseStruct = type({\n finalStatus: string(),\n statusMessage: optional(string()),\n externalUserId: string(),\n kycStatus: string(),\n vendor: string(),\n vendorStatus: string(),\n});\n\n// Vendor customer subset — `type` (not `object`) keeps extra vendor fields from\n// failing validation while still requiring the fields the controller needs.\nconst VendorCustomerResponseStruct = type({\n id: string(),\n email: string(),\n status: string(),\n});\nexport type VendorCustomerResponse = Infer<typeof VendorCustomerResponseStruct>;\n\nconst KYC_USER_STATUSES = [\n 'not-started',\n 'pending',\n 'need-more-information',\n 'terminal-failure',\n 'completed',\n] as const;\n\nconst KycUserStatusResponseStruct = type({\n status: enums([...KYC_USER_STATUSES]),\n sumsubSessionId: optional(string()),\n errorCode: optional(string()),\n});\n\nconst CatalogDocumentFields = {\n key: string(),\n version: string(),\n title: string(),\n url: string(),\n} as const;\n\nconst CatalogDocumentStruct = type(CatalogDocumentFields);\n\n// Session documents also report whether that version was already consented to.\nconst ConsentDocumentStruct = type({\n ...CatalogDocumentFields,\n consented: boolean(),\n});\n\n/**\n * Global catalog from `GET /disclaimers` (no per-document `consented` flag and\n * no credential-reuse flag).\n */\nconst GlobalDisclaimersResponseStruct = type({\n idOS: array(CatalogDocumentStruct),\n kycProvider: array(CatalogDocumentStruct),\n});\n\n/** Session catalog from `GET`/`POST /sessions/{id}/disclaimers`. */\nconst SessionDisclaimersResponseStruct = type({\n idOS: array(ConsentDocumentStruct),\n kycProvider: array(ConsentDocumentStruct),\n credentialReusabilityConsentGiven: boolean(),\n});\n\n// === PARAM TYPES ===\n\nexport type CreateSessionParams = {\n email: string;\n termsAcceptedAt: string;\n disclaimerIds: string[];\n};\n\nexport type CheckKycRequiredParams = {\n /**\n * Identity vendor to check. Defaults to `moonpay` for the existing\n * Check/Auth path.\n */\n vendor?: KycVendor;\n /**\n * MoonPay access token. Required when `vendor` is `moonpay` (or omitted).\n */\n accessToken?: string;\n /**\n * ISO 3166-1 alpha-3 country code. Required when `vendor` is `moonpay`.\n */\n country?: string;\n capabilities?: { product: string }[];\n};\n\nexport type CreateVendorCustomerParams = {\n vendor: KycVendor;\n email: string;\n};\n\nexport type SubmitVendorDisclaimersParams = {\n /** Identity vendor whose T&Cs were accepted (currently `iron`). */\n vendor: KycVendor;\n /** Disclaimer ids from {@link KycService.fetchVendorDisclaimers}. */\n disclaimerIds: string[];\n};\n\nexport type FetchSessionDisclaimersByCountryParams = {\n /** ISO 3166-1 alpha-3 country code for `GET /disclaimers?country=`. */\n country: string;\n};\n\nexport type FetchSessionDisclaimersBySessionIdParams = {\n /** UKYC session id from {@link KycService.createUkycSession}. */\n sessionId: string;\n};\n\nexport type SubmitSessionDisclaimersParams = {\n /** UKYC session id from {@link KycService.createUkycSession}. */\n sessionId: string;\n /** Consents to the idOS legal documents (`key`/`version` from the catalog). */\n idOS: KycConsentRecord[];\n /**\n * Consents to the KYC provider (SumSub) legal documents (`key`/`version`\n * from the catalog).\n */\n kycProvider: KycConsentRecord[];\n /** Consent to reuse the user's existing idOS credentials. */\n credentialReusabilityConsentGiven: boolean;\n};\n\nexport type CreateUkycSessionParams = {\n jwtToken: string;\n /**\n * The client's per-session X25519 public key (unpadded base64url). Generated\n * with the matching private key used later to wrap authorizations, so the\n * session server can open those boxes.\n */\n sessionClientPublicKey: string;\n /**\n * Country of residence in ISO 3166-1 alpha-3 format (e.g. `USA`, `GBR`).\n */\n residenceCountry: string;\n /**\n * Identity vendor for the UKYC session. Defaults to `moonpay` for the\n * existing Check/Auth flow. Pass a non-MoonPay vendor (e.g. `iron`) for\n * the consents path (no MoonPay metadata required).\n */\n vendor?: KycVendor;\n /**\n * Vendor-specific metadata. Required for MoonPay (`moonPayAccessToken` /\n * `moonPayUserId`); optional / omitted for other vendors.\n */\n vendorMetadata?: Record<string, unknown>;\n};\n\n/**\n * Encrypted capability authorization payload (base64url nonce + ciphertext)\n * accepted by `POST /sessions/:sessionId/authorizations`. Produced by\n * `wrapEncryptionKey` for both the `data_encryption_key` and the\n * `ukyc_capability_token`.\n */\nexport type CapabilityAuthorization = {\n nonce: string;\n data: string;\n};\n\nexport type SetAuthorizationsParams = {\n sessionId: string;\n wrappedEncryptionDataKey: CapabilityAuthorization;\n wrappedUkycCapabilityToken: CapabilityAuthorization;\n};\n\nexport type GetSessionStatusParams = {\n sessionId: 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 the runtime's native `fetch` (or an injected\n * `fetch` when provided), and the auth bearer token and geolocation come from\n * other controllers via the messenger.\n *\n * It extends {@link BaseDataService}, so read-only endpoints are routed through\n * `fetchQuery`: they are wrapped in the shared service policy (retries, circuit\n * breaker) and their results are exposed via the service's `QueryClient`.\n * `fetchDisclaimers` and `fetchJwks` are cached with a `staleTime`;\n * session-scoped disclaimer and status-polling reads opt out of caching\n * (`staleTime`/`gcTime` of `0`) so they never serve a stale result.\n *\n * Write endpoints (every `POST`) deliberately bypass `fetchQuery`. The query\n * cache is built for idempotent reads: it deduplicates concurrent requests\n * sharing a `queryKey`, retains responses for replay, and publishes them on the\n * messenger via `cacheUpdated`. None of that is safe for calls that create\n * sessions, customers, or consents — two overlapping `createVendorCustomer`\n * calls would collapse into a single `POST`, and session tokens would be\n * broadcast as cache payloads. Writes therefore call `#requestJson` directly,\n * which also means they are not retried by the service policy.\n */\nexport class KycService extends BaseDataService<\n typeof serviceName,\n KycServiceMessenger\n> {\n readonly #fetch: typeof fetch;\n\n readonly #baseUrl: string;\n\n readonly #idosEnclaveBaseUrl: string;\n\n readonly #idosRelayBaseUrl: string;\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. Defaults to\n * the runtime's native `fetch`.\n * @param options.baseUrl - Base URL of the KYC API\n * @param options.idosEnclaveBaseUrl - Base URL of the idOS enclave, from\n * which the JWKS used to verify the `encryptionDataKey` schema's `jwtChain`\n * is fetched.\n * @param options.idosRelayBaseUrl - Base URL of the idOS relay, from which\n * the JWKS used to verify the `ukycCapabilityToken` schema's `jwtChain` is\n * fetched.\n * @param options.queryClientConfig - Shared configuration for all queries\n * exposed by the service.\n * @param options.policyOptions - Options for the request service policy.\n */\n constructor({\n messenger,\n fetch: fetchFunction,\n baseUrl,\n idosEnclaveBaseUrl,\n idosRelayBaseUrl,\n queryClientConfig = {},\n policyOptions = {},\n }: KycServiceOptions) {\n super({\n name: serviceName,\n messenger,\n queryClientConfig,\n policyOptions,\n });\n // Fall back to the runtime's native `fetch`, bound to `globalThis` so it\n // can be invoked as a method of this instance without an illegal-invocation\n // error on platforms that check the receiver.\n if (fetchFunction) {\n this.#fetch = fetchFunction;\n } else if (typeof globalThis.fetch === 'function') {\n this.#fetch = globalThis.fetch.bind(globalThis);\n } else {\n throw new Error(\n 'KycService: fetch is not available globally and was not provided in options. Please inject a fetch implementation.',\n );\n }\n if (!baseUrl) {\n throw new Error('KycService: baseUrl is required');\n }\n this.#baseUrl = baseUrl;\n this.#idosEnclaveBaseUrl = idosEnclaveBaseUrl ?? '';\n this.#idosRelayBaseUrl = idosRelayBaseUrl ?? '';\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 // `vendorError`).\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.vendor - Identity vendor. Defaults to `moonpay`.\n * @param params.country - ISO 3166-1 alpha-3 country code.\n * @returns The disclaimers.\n */\n async fetchVendorDisclaimers({\n vendor = 'moonpay',\n country,\n }: {\n vendor?: KycVendor;\n country: string;\n }): Promise<KycDisclaimer[]> {\n const url = new URL(`/vendors/${vendor}/disclaimers`, this.#baseUrl);\n url.searchParams.set('country', country);\n const data = await this.fetchQuery({\n queryKey: [`${this.name}:fetchVendorDisclaimers`, vendor, country],\n queryFn: async () => this.#requestJson(url, { method: 'GET' }),\n staleTime: inMilliseconds(5, Duration.Minute),\n });\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.#requestJson(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 vendor, 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 vendor = params.vendor ?? 'moonpay';\n const url = new URL(`/vendors/${vendor}/kyc-required`, this.#baseUrl);\n const capabilities = params.capabilities ?? [{ product: 'ramps' }];\n const body =\n vendor === 'moonpay'\n ? {\n accessToken: params.accessToken,\n country: params.country,\n capabilities,\n }\n : {};\n\n // MoonPay requires accessToken and country; validate before making the request.\n if (vendor === 'moonpay') {\n if (!params.accessToken) {\n throw new Error(\n 'checkKycRequired: accessToken is required for vendor \"moonpay\".',\n );\n }\n if (!params.country) {\n throw new Error(\n 'checkKycRequired: country is required for vendor \"moonpay\".',\n );\n }\n }\n\n const data = await this.#requestJson(url, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n const { required } = this.#validateResponse(\n data,\n KycRequiredResponseStruct,\n 'kyc-required',\n );\n return { kycRequired: required };\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 */\n async createVendorCustomer(\n params: CreateVendorCustomerParams,\n ): Promise<VendorCustomerResponse> {\n const url = new URL(`/vendors/${params.vendor}/customers`, this.#baseUrl);\n const data = await this.#requestJson(url, {\n method: 'POST',\n body: JSON.stringify({ email: params.email }),\n });\n return this.#validateResponse(\n data,\n VendorCustomerResponseStruct,\n 'vendor customers',\n );\n }\n\n /**\n * Records vendor T&C acceptance (`POST /vendors/{vendor}/disclaimers`).\n * For Iron this creates content signings from the disclaimer ids the\n * customer accepted. Session-scoped idOS / KYC-provider consents are\n * recorded separately via {@link submitSessionDisclaimers}. Retries re-POST\n * the same ids, matching the legacy `POST /consents` signing step.\n *\n * @param params - The parameters.\n * @param params.vendor - Identity vendor (e.g. `iron`).\n * @param params.disclaimerIds - Accepted vendor T&C ids.\n * @returns The vendor signing records.\n */\n async submitVendorDisclaimers(\n params: SubmitVendorDisclaimersParams,\n ): Promise<KycVendorSigning[]> {\n const url = new URL(\n `/vendors/${encodeURIComponent(params.vendor)}/disclaimers`,\n this.#baseUrl,\n );\n const data = await this.#requestJson(url, {\n method: 'POST',\n body: JSON.stringify({ disclaimerIds: params.disclaimerIds }),\n });\n return this.#validateResponse(\n data,\n VendorSigningsResponseStruct,\n 'vendor disclaimers',\n );\n }\n\n /**\n * Fetches the global idOS + KYC-provider disclaimer catalog\n * (`GET /disclaimers?country=`). Carries no consent state — per-document\n * `consented` flags and `credentialReusabilityConsentGiven` are\n * session-scoped via {@link fetchSessionDisclaimersBySessionId}. Vendor T&Cs continue to\n * come from {@link fetchVendorDisclaimers}.\n *\n * @param params - The parameters.\n * @param params.country - ISO 3166-1 alpha-3 country code.\n * @returns The catalog documents.\n */\n async fetchSessionDisclaimersByCountry({\n country,\n }: FetchSessionDisclaimersByCountryParams): Promise<KycDisclaimersCatalog> {\n if (country.length !== 3) {\n throw new Error(\n `KycService.fetchSessionDisclaimersByCountry: country must be an ISO 3166-1 alpha-3 code (received \"${country}\").`,\n );\n }\n\n const url = new URL('/disclaimers', this.#baseUrl);\n url.searchParams.set('country', country);\n const data = await this.fetchQuery({\n queryKey: [`${this.name}:fetchSessionDisclaimersByCountry`, country],\n queryFn: async () => this.#requestJson(url, { method: 'GET' }),\n staleTime: 0,\n gcTime: 0,\n });\n return this.#validateResponse(\n data,\n GlobalDisclaimersResponseStruct,\n 'disclaimers',\n );\n }\n\n /**\n * Fetches the session-scoped idOS + KYC-provider disclaimer catalog\n * (`GET /sessions/{sessionId}/disclaimers`), including per-session\n * `consented` flags and `credentialReusabilityConsentGiven`. For the\n * pre-session global catalog use {@link fetchSessionDisclaimersByCountry}.\n * Vendor T&Cs continue to come from {@link fetchVendorDisclaimers}.\n *\n * @param params - The parameters.\n * @param params.sessionId - The UKYC session id.\n * @returns The catalog, including which documents are already consented.\n */\n async fetchSessionDisclaimersBySessionId({\n sessionId,\n }: FetchSessionDisclaimersBySessionIdParams): Promise<KycSessionDisclaimers> {\n const url = new URL(\n `/sessions/${encodeURIComponent(sessionId)}/disclaimers`,\n this.#baseUrl,\n );\n const data = await this.fetchQuery({\n queryKey: [`${this.name}:fetchSessionDisclaimersBySessionId`, sessionId],\n queryFn: async () => this.#requestJson(url, { method: 'GET' }),\n // Consent state can change after a POST, so always re-fetch.\n staleTime: 0,\n gcTime: 0,\n });\n return this.#validateResponse(\n data,\n SessionDisclaimersResponseStruct,\n 'session disclaimers',\n );\n }\n\n /**\n * Records idOS + KYC-provider consents for a UKYC session\n * (`POST /sessions/{sessionId}/disclaimers`). `key`/`version` pairs must\n * match the current catalog from {@link fetchSessionDisclaimersBySessionId}. A 409\n * means those document versions were already recorded for the session.\n *\n * @param params - The consent parameters.\n * @returns The updated catalog after recording.\n */\n async submitSessionDisclaimers(\n params: SubmitSessionDisclaimersParams,\n ): Promise<KycSessionDisclaimers> {\n const url = new URL(\n `/sessions/${encodeURIComponent(params.sessionId)}/disclaimers`,\n this.#baseUrl,\n );\n const data = await this.#requestJson(url, {\n method: 'POST',\n body: JSON.stringify({\n idOS: params.idOS,\n kycProvider: params.kycProvider,\n credentialReusabilityConsentGiven:\n params.credentialReusabilityConsentGiven,\n }),\n });\n return this.#validateResponse(\n data,\n SessionDisclaimersResponseStruct,\n 'session disclaimers',\n );\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 */\n async fetchKycStatus(): Promise<KycUserStatusResponse> {\n const url = new URL('/kyc/status', this.#baseUrl);\n const data = await this.fetchQuery({\n queryKey: [`${this.name}:fetchKycStatus`],\n queryFn: async () => this.#requestJson(url, { method: 'GET' }),\n // Status is polled for toast flips, so it must always be fresh.\n staleTime: 0,\n gcTime: 0,\n });\n return this.#validateResponse(\n data,\n KycUserStatusResponseStruct,\n 'kyc status',\n );\n }\n\n /**\n * Fetches a well-known JWKS from `baseUrl`, caching the result for an hour.\n *\n * @param baseUrl - Host base URL that serves `/.well-known/jwks.json`.\n * @param queryName - Cache query-key segment.\n * @param responseLabel - Label used in malformed-response errors.\n * @param missingConfigMessage - Error thrown when `baseUrl` is empty.\n * @returns The JWKS keys.\n */\n async #fetchWellKnownJwks(\n baseUrl: string,\n queryName: string,\n responseLabel: string,\n missingConfigMessage: string,\n ): Promise<JwksResponse> {\n if (!baseUrl) {\n throw new Error(missingConfigMessage);\n }\n const url = new URL(UKYC_JWKS_PATH, baseUrl);\n const data = await this.fetchQuery({\n queryKey: [`${this.name}:${queryName}`, baseUrl],\n queryFn: async () =>\n this.#requestJson(url, { method: 'GET' }, { authenticated: false }),\n staleTime: inMilliseconds(1, Duration.Hour),\n });\n return this.#validateResponse(data, JwksResponseStruct, responseLabel);\n }\n\n /**\n * Fetches the idOS enclave JWKS used to verify the\n * `encryptionDataKey` schema's `jwtChain` from\n * {@link KycService.createUkycSession}.\n *\n * This is an unauthenticated request to a well-known path on the idOS enclave\n * host, distinct from the UKYC base URL.\n *\n * @returns The JWKS keys.\n */\n async fetchIdosEnclaveJwks(): Promise<JwksResponse> {\n return this.#fetchWellKnownJwks(\n this.#idosEnclaveBaseUrl,\n 'fetchIdosEnclaveJwks',\n 'idOS enclave JWKS',\n 'KycService: idosEnclaveBaseUrl is not configured; cannot fetch JWKS to verify the encryptionDataKey schema.',\n );\n }\n\n /**\n * Fetches the idOS relay JWKS used to verify the `ukycCapabilityToken`\n * schema's `jwtChain` from {@link KycService.createUkycSession}.\n *\n * This is an unauthenticated request to a well-known path on the idOS relay\n * host, distinct from both the UKYC base URL and the idOS enclave.\n *\n * @returns The JWKS keys.\n */\n async fetchIdosRelayJwks(): Promise<JwksResponse> {\n return this.#fetchWellKnownJwks(\n this.#idosRelayBaseUrl,\n 'fetchIdosRelayJwks',\n 'idOS relay JWKS',\n 'KycService: idosRelayBaseUrl is not configured; cannot fetch JWKS to verify the ukycCapabilityToken schema.',\n );\n }\n\n /**\n * Creates a UKYC session for the SumSub document-verification sub-flow.\n *\n * The client registers its per-session X25519 public key so the server can\n * later open boxes sealed with the matching private key, and supplies the\n * customer's ISO 3166-1 alpha-3 country of residence. The response\n * carries per-secret encryption schemas (`encryptionDataKey` and\n * `ukycCapabilityToken`) so the client can wrap the `data_encryption_key` and\n * the read-only `ukyc_capability_token` and submit them via\n * {@link KycService.setAuthorizations}.\n *\n * @param params - The session parameters.\n * @returns The UKYC session id and encryption schemas.\n */\n async createUkycSession(\n params: CreateUkycSessionParams,\n ): Promise<UkycSessionResponse> {\n const url = new URL('/sessions', this.#baseUrl);\n const data = await this.#requestJson(url, {\n method: 'POST',\n body: JSON.stringify({\n vendorId: params.vendor ?? 'moonpay',\n vendorUserId: 'mockedId',\n jwtToken: params.jwtToken,\n sessionClientPublicKey: params.sessionClientPublicKey,\n residenceCountry: params.residenceCountry,\n vendorMetadata: params.vendorMetadata ?? {},\n }),\n });\n return this.#validateResponse(\n data,\n UkycSessionResponseStruct,\n 'UKYC sessions',\n );\n }\n\n /**\n * Submits the wrapped `data_encryption_key` and wrapped\n * `ukyc_capability_token` for a UKYC session. Both secrets are sealed with\n * `wrapEncryptionKey` against the encryption schemas returned by\n * {@link KycService.createUkycSession}.\n *\n * @param params - The wrapped authorizations.\n * @returns The session status after the authorizations are applied.\n */\n async setAuthorizations(\n params: SetAuthorizationsParams,\n ): Promise<KycSessionStatus> {\n const url = new URL(\n `/sessions/${encodeURIComponent(params.sessionId)}/authorizations`,\n this.#baseUrl,\n );\n const data = await this.#requestJson(url, {\n method: 'POST',\n body: JSON.stringify({\n wrappedEncryptionDataKey: params.wrappedEncryptionDataKey,\n wrappedUkycCapabilityToken: params.wrappedUkycCapabilityToken,\n }),\n });\n return this.#validateResponse(\n data,\n SessionStatusResponseStruct,\n 'authorizations',\n );\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 */\n async createJourney(\n sessionId: string,\n ): Promise<ApplicantAccessTokenResponse> {\n const url = new URL(\n `/sessions/${encodeURIComponent(sessionId)}/journey`,\n this.#baseUrl,\n );\n const data = await this.#requestJson(url, { method: 'POST' });\n return this.#validateResponse(\n data,\n ApplicantAccessTokenResponseStruct,\n 'journey',\n );\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 */\n async getSessionStatus(\n params: GetSessionStatusParams,\n ): Promise<KycSessionStatus> {\n const url = new URL(\n `/sessions/${encodeURIComponent(params.sessionId)}/status`,\n this.#baseUrl,\n );\n const data = await this.fetchQuery({\n queryKey: [`${this.name}:getSessionStatus`, params.sessionId],\n queryFn: async () => this.#requestJson(url, { method: 'GET' }),\n // Status is polled for a terminal decision, so it must always be fresh.\n staleTime: 0,\n gcTime: 0,\n });\n return this.#validateResponse(\n data,\n SessionStatusResponseStruct,\n 'session status',\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 : // `assert` only ever throws `StructError` for the plain structs used\n // here, so this is a defensive fallback that is not exercised.\n /* istanbul ignore next */\n String(error);\n throw new Error(\n `Malformed response received from ${apiName} API: ${detail}`,\n );\n }\n }\n\n /**\n * Performs a single JSON request.\n *\n * Read endpoints pass this as the `queryFn` to {@link fetchQuery}, which\n * wraps it in the shared service policy (retries, circuit breaker). Write\n * endpoints call it directly, so they are executed exactly once. Requests\n * are authenticated with the wallet bearer token by default; pass\n * `{ authenticated: false }` for calls to services that do not expect it\n * (e.g. the idOS enclave or idOS relay JWKS endpoints).\n *\n * @param url - The request URL.\n * @param init - The request init (method, body).\n * @param options - Request options.\n * @param options.authenticated - Whether to attach the bearer token. Defaults\n * to `true`.\n * @returns The parsed JSON response.\n */\n async #requestJson(\n url: URL,\n init: RequestInit,\n options: { authenticated?: boolean } = {},\n ): Promise<Json> {\n const { authenticated = true } = options;\n\n const headers: Record<string, string> = {};\n\n // Only advertise a JSON body when one is actually sent; bodyless requests\n // (e.g. `createJourney`) must not carry a `Content-Type`.\n if (init.body !== undefined && init.body !== null) {\n headers['Content-Type'] = 'application/json';\n }\n\n if (authenticated) {\n const bearerToken = await this.messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n if (!bearerToken) {\n throw new Error(\n 'Unable to obtain an authentication bearer token — is the wallet signed in?',\n );\n }\n assert(bearerToken, string());\n headers.Authorization = `Bearer ${bearerToken}`;\n }\n\n const response = await this.#fetch(url.toString(), {\n ...init,\n headers,\n });\n if (!response.ok) {\n let detail = '';\n try {\n const errorBody: unknown = await response.json();\n if (errorBody && typeof errorBody === 'object') {\n const record = errorBody as Record<string, unknown>;\n if (typeof record.message === 'string') {\n detail = record.message;\n } else if (typeof record.error === 'string') {\n detail = record.error;\n }\n }\n } catch {\n // Ignore body parse failures; status alone is still useful.\n }\n throw new HttpError(\n response.status,\n `Fetching '${url.toString()}' failed with status '${response.status}'${\n detail ? `: ${detail}` : ''\n }`,\n );\n }\n\n // DELETE (and similar) endpoints return 204 No Content.\n if (response.status === 204) {\n return null;\n }\n\n return (await response.json()) as Json;\n }\n}\n"]}
@@ -15,4 +15,4 @@ export declare const ALPHA2_TO_ALPHA3: Record<string, string>;
15
15
  * @returns The alpha-3 code, or `undefined` if the input is not recognized.
16
16
  */
17
17
  export declare function alpha2ToAlpha3(alpha2: string): string | undefined;
18
- //# sourceMappingURL=countryCodes.d.cts.map
18
+ //# sourceMappingURL=countryCodes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"countryCodes.d.ts","sourceRoot":"","sources":["../src/countryCodes.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CA0PnD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEjE"}
@@ -267,4 +267,4 @@ export const ALPHA2_TO_ALPHA3 = {
267
267
  export function alpha2ToAlpha3(alpha2) {
268
268
  return ALPHA2_TO_ALPHA3[alpha2.toUpperCase()];
269
269
  }
270
- //# sourceMappingURL=countryCodes.mjs.map
270
+ //# sourceMappingURL=countryCodes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"countryCodes.js","sourceRoot":"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EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;CACV,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAAC,MAAc;IAC3C,OAAO,gBAAgB,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC;AAChD,CAAC","sourcesContent":["/**\n * ISO 3166-1 alpha-2 to alpha-3 country code mapping.\n *\n * The geolocation source returns ISO 3166-2 codes whose leading segment is an\n * alpha-2 country code (e.g. \"US\", \"US-NY\"). The identity vendor APIs\n * (disclaimers, kyc-required) expect alpha-3 codes (e.g. \"USA\"). This map\n * bridges the two.\n */\nexport const ALPHA2_TO_ALPHA3: Record<string, string> = {\n AD: 'AND',\n AE: 'ARE',\n AF: 'AFG',\n AG: 'ATG',\n AI: 'AIA',\n AL: 'ALB',\n AM: 'ARM',\n AO: 'AGO',\n AQ: 'ATA',\n AR: 'ARG',\n AS: 'ASM',\n AT: 'AUT',\n AU: 'AUS',\n AW: 'ABW',\n AX: 'ALA',\n AZ: 'AZE',\n BA: 'BIH',\n BB: 'BRB',\n BD: 'BGD',\n BE: 'BEL',\n BF: 'BFA',\n BG: 'BGR',\n BH: 'BHR',\n BI: 'BDI',\n BJ: 'BEN',\n BL: 'BLM',\n BM: 'BMU',\n BN: 'BRN',\n BO: 'BOL',\n BQ: 'BES',\n BR: 'BRA',\n BS: 'BHS',\n BT: 'BTN',\n BV: 'BVT',\n BW: 'BWA',\n BY: 'BLR',\n BZ: 'BLZ',\n CA: 'CAN',\n CC: 'CCK',\n CD: 'COD',\n CF: 'CAF',\n CG: 'COG',\n CH: 'CHE',\n CI: 'CIV',\n CK: 'COK',\n CL: 'CHL',\n CM: 'CMR',\n CN: 'CHN',\n CO: 'COL',\n CR: 'CRI',\n CU: 'CUB',\n CV: 'CPV',\n CW: 'CUW',\n CX: 'CXR',\n CY: 'CYP',\n CZ: 'CZE',\n DE: 'DEU',\n DJ: 'DJI',\n DK: 'DNK',\n DM: 'DMA',\n DO: 'DOM',\n DZ: 'DZA',\n EC: 'ECU',\n EE: 'EST',\n EG: 'EGY',\n EH: 'ESH',\n ER: 'ERI',\n ES: 'ESP',\n ET: 'ETH',\n FI: 'FIN',\n FJ: 'FJI',\n FK: 'FLK',\n FM: 'FSM',\n FO: 'FRO',\n FR: 'FRA',\n GA: 'GAB',\n GB: 'GBR',\n GD: 'GRD',\n GE: 'GEO',\n GF: 'GUF',\n GG: 'GGY',\n GH: 'GHA',\n GI: 'GIB',\n GL: 'GRL',\n GM: 'GMB',\n GN: 'GIN',\n GP: 'GLP',\n GQ: 'GNQ',\n GR: 'GRC',\n GS: 'SGS',\n GT: 'GTM',\n GU: 'GUM',\n GW: 'GNB',\n GY: 'GUY',\n HK: 'HKG',\n HM: 'HMD',\n HN: 'HND',\n HR: 'HRV',\n HT: 'HTI',\n HU: 'HUN',\n ID: 'IDN',\n IE: 'IRL',\n IL: 'ISR',\n IM: 'IMN',\n IN: 'IND',\n IO: 'IOT',\n IQ: 'IRQ',\n IR: 'IRN',\n IS: 'ISL',\n IT: 'ITA',\n JE: 'JEY',\n JM: 'JAM',\n JO: 'JOR',\n JP: 'JPN',\n KE: 'KEN',\n KG: 'KGZ',\n KH: 'KHM',\n KI: 'KIR',\n KM: 'COM',\n KN: 'KNA',\n KP: 'PRK',\n KR: 'KOR',\n KW: 'KWT',\n KY: 'CYM',\n KZ: 'KAZ',\n LA: 'LAO',\n LB: 'LBN',\n LC: 'LCA',\n LI: 'LIE',\n LK: 'LKA',\n LR: 'LBR',\n LS: 'LSO',\n LT: 'LTU',\n LU: 'LUX',\n LV: 'LVA',\n LY: 'LBY',\n MA: 'MAR',\n MC: 'MCO',\n MD: 'MDA',\n ME: 'MNE',\n MF: 'MAF',\n MG: 'MDG',\n MH: 'MHL',\n MK: 'MKD',\n ML: 'MLI',\n MM: 'MMR',\n MN: 'MNG',\n MO: 'MAC',\n MP: 'MNP',\n MQ: 'MTQ',\n MR: 'MRT',\n MS: 'MSR',\n MT: 'MLT',\n MU: 'MUS',\n MV: 'MDV',\n MW: 'MWI',\n MX: 'MEX',\n MY: 'MYS',\n MZ: 'MOZ',\n NA: 'NAM',\n NC: 'NCL',\n NE: 'NER',\n NF: 'NFK',\n NG: 'NGA',\n NI: 'NIC',\n NL: 'NLD',\n NO: 'NOR',\n NP: 'NPL',\n NR: 'NRU',\n NU: 'NIU',\n NZ: 'NZL',\n OM: 'OMN',\n PA: 'PAN',\n PE: 'PER',\n PF: 'PYF',\n PG: 'PNG',\n PH: 'PHL',\n PK: 'PAK',\n PL: 'POL',\n PM: 'SPM',\n PN: 'PCN',\n PR: 'PRI',\n PS: 'PSE',\n PT: 'PRT',\n PW: 'PLW',\n PY: 'PRY',\n QA: 'QAT',\n RE: 'REU',\n RO: 'ROU',\n RS: 'SRB',\n RU: 'RUS',\n RW: 'RWA',\n SA: 'SAU',\n SB: 'SLB',\n SC: 'SYC',\n SD: 'SDN',\n SE: 'SWE',\n SG: 'SGP',\n SH: 'SHN',\n SI: 'SVN',\n SJ: 'SJM',\n SK: 'SVK',\n SL: 'SLE',\n SM: 'SMR',\n SN: 'SEN',\n SO: 'SOM',\n SR: 'SUR',\n SS: 'SSD',\n ST: 'STP',\n SV: 'SLV',\n SX: 'SXM',\n SY: 'SYR',\n SZ: 'SWZ',\n TC: 'TCA',\n TD: 'TCD',\n TF: 'ATF',\n TG: 'TGO',\n TH: 'THA',\n TJ: 'TJK',\n TK: 'TKL',\n TL: 'TLS',\n TM: 'TKM',\n TN: 'TUN',\n TO: 'TON',\n TR: 'TUR',\n TT: 'TTO',\n TV: 'TUV',\n TW: 'TWN',\n TZ: 'TZA',\n UA: 'UKR',\n UG: 'UGA',\n UM: 'UMI',\n US: 'USA',\n UY: 'URY',\n UZ: 'UZB',\n VA: 'VAT',\n VC: 'VCT',\n VE: 'VEN',\n VG: 'VGB',\n VI: 'VIR',\n VN: 'VNM',\n VU: 'VUT',\n WF: 'WLF',\n WS: 'WSM',\n YE: 'YEM',\n YT: 'MYT',\n ZA: 'ZAF',\n ZM: 'ZMB',\n ZW: 'ZWE',\n};\n\n/**\n * Converts an ISO 3166-1 alpha-2 country code (e.g. \"US\") to its alpha-3\n * equivalent (e.g. \"USA\"). Returns `undefined` for unknown codes.\n *\n * @param alpha2 - The ISO 3166-1 alpha-2 country code.\n * @returns The alpha-3 code, or `undefined` if the input is not recognized.\n */\nexport function alpha2ToAlpha3(alpha2: string): string | undefined {\n return ALPHA2_TO_ALPHA3[alpha2.toUpperCase()];\n}\n"]}
@@ -81,4 +81,4 @@ export declare function generateKeyPair(): X25519KeyPair;
81
81
  * @throws If the envelope is malformed or the IV length is not 12 bytes.
82
82
  */
83
83
  export declare function decryptCredentials(rawEnvelope: EncryptedCredentialsEnvelope | string, ourPrivateKey: Uint8Array): DecryptResult;
84
- //# sourceMappingURL=crypto.d.mts.map
84
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAUH;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,wEAAwE;IACxE,UAAU,EAAE,UAAU,CAAC;IACvB,qCAAqC;IACrC,SAAS,EAAE,UAAU,CAAC;IACtB,yEAAyE;IACzE,YAAY,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,4BAA4B,GAAG;IACzC,+EAA+E;IAC/E,kBAAkB,EAAE,MAAM,CAAC;IAC3B,0DAA0D;IAC1D,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qDAAqD;IACrD,UAAU,EAAE,MAAM,CAAC;IACnB,gEAAgE;IAChE,QAAQ,CAAC,EAAE,KAAK,GAAG,QAAQ,CAAC;CAC7B,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,WAAW,EAAE,oBAAoB,CAAC;IAClC,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,eAAe,IAAI,aAAa,CAQ/C;AAkHD;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAChC,WAAW,EAAE,4BAA4B,GAAG,MAAM,EAClD,aAAa,EAAE,UAAU,GACxB,aAAa,CAkBf"}
@@ -18,12 +18,12 @@
18
18
  * (via the shared encoding helpers) and avoids `Buffer` / `atob` so it runs
19
19
  * unchanged on mobile, extension, and web.
20
20
  */
21
- import { gcm } from "@noble/ciphers/aes";
22
- import { x25519 } from "@noble/curves/ed25519";
23
- import { hkdf } from "@noble/hashes/hkdf";
24
- import { sha256 } from "@noble/hashes/sha2";
25
- import { bytesToHex, hexToBytes } from "@noble/hashes/utils";
26
- import { base64UrlToBytes } from "./encoding.mjs";
21
+ import { gcm } from '@noble/ciphers/aes';
22
+ import { x25519 } from '@noble/curves/ed25519';
23
+ import { hkdf } from '@noble/hashes/hkdf';
24
+ import { sha256 } from '@noble/hashes/sha2';
25
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
26
+ import { base64UrlToBytes } from './encoding.js';
27
27
  /**
28
28
  * Generate a fresh X25519 keypair. The private key never leaves the device;
29
29
  * only `publicKeyHex` is sent to the vendor via the frame URL.
@@ -146,4 +146,4 @@ export function decryptCredentials(rawEnvelope, ourPrivateKey) {
146
146
  }
147
147
  return aesGcmDecrypt(theirPublicKey, iv, ciphertext, ourPrivateKey);
148
148
  }
149
- //# sourceMappingURL=crypto.mjs.map
149
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAE7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAoDjD;;;;;GAKG;AACH,MAAM,UAAU,eAAe;IAC7B,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E,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;IAC3D,MAAM,SAAS,GAAG,GAAG,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACnD,MAAM,IAAI,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACjD,OAAO;QACL,WAAW,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAyB;QACrD,MAAM,EAAE,yBAAyB;KAClC,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,kBAAkB,CAChC,WAAkD,EAClD,aAAyB;IAEzB,MAAM,QAAQ,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;IAChD,MAAM,cAAc,GAAG,YAAY,CACjC,QAAQ,CAAC,kBAAkB,EAC3B,QAAQ,CAAC,QAAQ,CAClB,CAAC;IACF,mEAAmE;IACnE,MAAM,OAAO,GAAG,CAAC,QAAQ,CAAC,EAAE,IAAI,QAAQ,CAAC,KAAK,CAAW,CAAC;IAC1D,MAAM,EAAE,GAAG,YAAY,CAAC,OAAO,EAAE,QAAQ,CAAC,QAAQ,CAAC,CAAC;IACpD,MAAM,UAAU,GAAG,YAAY,CAAC,QAAQ,CAAC,UAAU,EAAE,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAExE,IAAI,EAAE,CAAC,MAAM,KAAK,EAAE,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CACb,wBAAwB,EAAE,CAAC,MAAM,iCAAiC,CACnE,CAAC;IACJ,CAAC;IAED,OAAO,aAAa,CAAC,cAAc,EAAE,EAAE,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC;AACtE,CAAC","sourcesContent":["/**\n * Check / Auth frame key exchange and credential decryption.\n *\n * The identity vendor's Check and Auth frames return encrypted credentials.\n * The confirmed protocol is X25519 ECDH + AES-256-GCM (an \"ECDH-ES\" pattern\n * signalled by a 12-byte IV):\n *\n * 1. Client generates an X25519 keypair, sends `publicKey` (hex) into the\n * frame as a URL param.\n * 2. Frame generates its own ephemeral X25519 keypair and encrypts the\n * credentials, returning `{ ephemeralPublicKey, iv, ciphertext }`.\n * 3. Client reverses:\n * shared = X25519(ourPrivate, theirEphemeralPublic)\n * key = HKDF-SHA256(shared, salt=none, info=none, 32 bytes)\n * plain = AES-256-GCM.decrypt(key, iv, ciphertext || 16-byte tag)\n *\n * This module is platform-agnostic: it uses `@noble/*` and `@metamask/utils`\n * (via the shared encoding helpers) and avoids `Buffer` / `atob` so it runs\n * unchanged on mobile, extension, and web.\n */\n\nimport { gcm } from '@noble/ciphers/aes';\nimport { x25519 } from '@noble/curves/ed25519';\nimport { hkdf } from '@noble/hashes/hkdf';\nimport { sha256 } from '@noble/hashes/sha2';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\n\nimport { base64UrlToBytes } from './encoding.js';\n\n/**\n * An X25519 keypair used for the Check/Auth frame key exchange.\n */\nexport type X25519KeyPair = {\n /** Raw 32-byte X25519 private (scalar) key. Never leaves the device. */\n privateKey: Uint8Array;\n /** Raw 32-byte X25519 public key. */\n publicKey: Uint8Array;\n /** Hex-encoded public key, ready to drop into a Check/Auth frame URL. */\n publicKeyHex: string;\n};\n\n/**\n * The encrypted-credentials envelope returned by the Check/Auth frames. Binary\n * fields may be hex or base64; the IV field may be named `iv` or `nonce`.\n */\nexport type EncryptedCredentialsEnvelope = {\n /** Ephemeral public key produced by the frame for this exchange (32 bytes). */\n ephemeralPublicKey: string;\n /** Per-message IV. May be provided as `iv` or `nonce`. */\n iv?: string;\n nonce?: string;\n /** Ciphertext (plaintext + 16-byte GCM auth tag). */\n ciphertext: string;\n /** Optional explicit encoding hint. Defaults to auto-detect. */\n encoding?: 'hex' | 'base64';\n};\n\n/**\n * Decrypted Check/Auth frame credentials.\n *\n * - `accessToken` is the Bearer token for the identity API.\n * - `clientToken` is the short-lived token consumed by the Auth frame when the\n * Check frame returns `connectionRequired`.\n */\nexport type DecryptedCredentials = {\n accessToken?: string;\n clientToken?: string;\n [key: string]: unknown;\n};\n\n/**\n * Result of a successful decryption — the credentials plus the `method` that\n * authenticated.\n */\nexport type DecryptResult = {\n credentials: DecryptedCredentials;\n method: string;\n};\n\n/**\n * Generate a fresh X25519 keypair. The private key never leaves the device;\n * only `publicKeyHex` is sent to the vendor via the frame URL.\n *\n * @returns The generated keypair.\n */\nexport function generateKeyPair(): X25519KeyPair {\n const privateKey = x25519.utils.randomSecretKey();\n const publicKey = x25519.getPublicKey(privateKey);\n return {\n privateKey,\n publicKey,\n publicKeyHex: bytesToHex(publicKey),\n };\n}\n\n/**\n * Decode a binary envelope field that may be hex or base64.\n *\n * @param value - The encoded field.\n * @param encoding - Optional explicit encoding; auto-detected when omitted.\n * @returns The decoded bytes.\n */\nfunction decodeBinary(value: string, encoding?: 'hex' | 'base64'): Uint8Array {\n const isHex =\n encoding === 'hex' ||\n (encoding === undefined && /^[0-9a-fA-F]+$/u.test(value));\n if (isHex) {\n return hexToBytes(value);\n }\n return base64UrlToBytes(value);\n}\n\n/**\n * Coerce the `credentials` field into a structured envelope. The frame may\n * deliver it as an object, a JSON string, or base64(JSON).\n *\n * @param input - The raw credentials value.\n * @returns The normalized envelope.\n * @throws If the value is not a structured or base64(JSON) envelope, or is\n * missing required fields.\n */\nfunction normalizeEnvelope(\n input: EncryptedCredentialsEnvelope | string,\n): EncryptedCredentialsEnvelope {\n let value: unknown = input;\n\n if (typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed.startsWith('{')) {\n try {\n value = JSON.parse(trimmed);\n } catch {\n throw new Error(\n `credentials looked like JSON but failed to parse (preview: \"${trimmed.slice(\n 0,\n 64,\n )}\").`,\n );\n }\n } else {\n let decodedText: string | null = null;\n try {\n decodedText = new TextDecoder().decode(base64UrlToBytes(trimmed));\n } catch {\n decodedText = null;\n }\n const decodedTrimmed = decodedText?.trim();\n if (decodedTrimmed?.startsWith('{')) {\n try {\n value = JSON.parse(decodedTrimmed);\n } catch {\n throw new Error(\n `credentials base64-decoded to non-JSON (preview: \"${decodedTrimmed.slice(\n 0,\n 64,\n )}\").`,\n );\n }\n } else {\n throw new Error(\n `credentials is an opaque string, not a structured or base64(JSON) envelope (preview: \"${trimmed.slice(\n 0,\n 64,\n )}\").`,\n );\n }\n }\n }\n\n const env = value as Partial<EncryptedCredentialsEnvelope>;\n if (!env.ephemeralPublicKey || !(env.iv ?? env.nonce) || !env.ciphertext) {\n const keys =\n value && typeof value === 'object'\n ? Object.keys(value).join(', ')\n : typeof value;\n throw new Error(\n `credentials envelope missing required fields (ephemeralPublicKey/iv/ciphertext). Got: ${keys}`,\n );\n }\n return env as EncryptedCredentialsEnvelope;\n}\n\n/**\n * X25519 ECDH to AES-256-GCM decryption.\n *\n * @param theirPublicKey - The frame's ephemeral public key.\n * @param iv - The 12-byte GCM IV.\n * @param ciphertext - The ciphertext including the 16-byte auth tag.\n * @param ourPrivateKey - Our X25519 private key.\n * @returns The decrypted credentials and method.\n */\nfunction aesGcmDecrypt(\n theirPublicKey: Uint8Array,\n iv: Uint8Array,\n ciphertext: Uint8Array,\n ourPrivateKey: Uint8Array,\n): DecryptResult {\n const shared = x25519.getSharedSecret(ourPrivateKey, theirPublicKey);\n const key = hkdf(sha256, shared, undefined, undefined, 32);\n const plaintext = gcm(key, iv).decrypt(ciphertext);\n const text = new TextDecoder().decode(plaintext);\n return {\n credentials: JSON.parse(text) as DecryptedCredentials,\n method: 'aes-256-gcm/hkdf-sha256',\n };\n}\n\n/**\n * Decrypt a Check/Auth frame credentials envelope using our X25519 private\n * key.\n *\n * @param rawEnvelope - The raw envelope (object, JSON string, or base64(JSON)).\n * @param ourPrivateKey - Our X25519 private key.\n * @returns The parsed credentials and the method that authenticated.\n * @throws If the envelope is malformed or the IV length is not 12 bytes.\n */\nexport function decryptCredentials(\n rawEnvelope: EncryptedCredentialsEnvelope | string,\n ourPrivateKey: Uint8Array,\n): DecryptResult {\n const envelope = normalizeEnvelope(rawEnvelope);\n const theirPublicKey = decodeBinary(\n envelope.ephemeralPublicKey,\n envelope.encoding,\n );\n // `normalizeEnvelope` guarantees one of `iv` / `nonce` is present.\n const ivField = (envelope.iv ?? envelope.nonce) as string;\n const iv = decodeBinary(ivField, envelope.encoding);\n const ciphertext = decodeBinary(envelope.ciphertext, envelope.encoding);\n\n if (iv.length !== 12) {\n throw new Error(\n `Unexpected IV length ${iv.length} (expected 12 for AES-256-GCM).`,\n );\n }\n\n return aesGcmDecrypt(theirPublicKey, iv, ciphertext, ourPrivateKey);\n}\n"]}
@@ -21,4 +21,4 @@ export declare function toBase64Url(bytes: Uint8Array): string;
21
21
  * @returns The decoded bytes.
22
22
  */
23
23
  export declare function base64UrlToBytes(value: string): Uint8Array;
24
- //# sourceMappingURL=encoding.d.mts.map
24
+ //# sourceMappingURL=encoding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encoding.d.ts","sourceRoot":"","sources":["../src/encoding.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AAEH;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAKrD;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAO1D"}
@@ -1,4 +1,4 @@
1
- import { base64ToBytes, bytesToBase64 } from "@metamask/utils";
1
+ import { base64ToBytes, bytesToBase64 } from '@metamask/utils';
2
2
  /**
3
3
  * Shared base64url encoding helpers used by frame crypto and UKYC modules.
4
4
  *
@@ -32,4 +32,4 @@ export function base64UrlToBytes(value) {
32
32
  .replace(/_/gu, '/')
33
33
  .padEnd(value.length + ((4 - (value.length % 4)) % 4), '='));
34
34
  }
35
- //# sourceMappingURL=encoding.mjs.map
35
+ //# sourceMappingURL=encoding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encoding.js","sourceRoot":"","sources":["../src/encoding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE/D;;;;;GAKG;AAEH;;;;;;;GAOG;AACH,MAAM,UAAU,WAAW,CAAC,KAAiB;IAC3C,OAAO,aAAa,CAAC,KAAK,CAAC;SACxB,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;SACpB,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;SACpB,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAC3B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAa;IAC5C,OAAO,aAAa,CAClB,KAAK;SACF,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAC9D,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from '@metamask/utils';\n\n/**\n * Shared base64url encoding helpers used by frame crypto and UKYC modules.\n *\n * These are platform-agnostic: they rely on `@metamask/utils` rather than\n * `Buffer` / `atob`, so they run unchanged on mobile, extension, and web.\n */\n\n/**\n * Encodes bytes as unpadded base64url (RFC 4648 §5). This is the wire shape\n * used for `storage_id`, `signing_public_key`, and Ed25519 signatures in the\n * UKYC storage API.\n *\n * @param bytes - The bytes to encode.\n * @returns The base64url string without `=` padding.\n */\nexport function toBase64Url(bytes: Uint8Array): string {\n return bytesToBase64(bytes)\n .replace(/\\+/gu, '-')\n .replace(/\\//gu, '_')\n .replace(/[=]+$/u, '');\n}\n\n/**\n * Decodes an unpadded (or padded) base64url string back to bytes. Inverse of\n * {@link toBase64Url}.\n *\n * @param value - The base64url string.\n * @returns The decoded bytes.\n */\nexport function base64UrlToBytes(value: string): Uint8Array {\n return base64ToBytes(\n value\n .replace(/-/gu, '+')\n .replace(/_/gu, '/')\n .padEnd(value.length + ((4 - (value.length % 4)) % 4), '='),\n );\n}\n"]}
@@ -0,0 +1,19 @@
1
+ export { KycController, getDefaultKycControllerState, getDefaultKycProviderDisclaimersAccepted, getDefaultKycVendorDisclaimersAccepted, controllerName, } from './KycController.js';
2
+ export type { KycControllerActions, KycControllerEvents, KycControllerGetStateAction, KycControllerMessenger, KycControllerOptions, KycControllerState, KycControllerStateChangeEvent, KycControllerStatusChangedEvent, FetchSessionDisclaimersParams, } from './KycController.js';
3
+ export type { KycControllerAcceptTermsAndStartSessionAction, KycControllerBuildAuthFrameUrlAction, KycControllerBuildCheckFrameUrlAction, KycControllerBuildResetFrameUrlAction, KycControllerCheckKycRequiredAction, KycControllerClearSavedTermsAction, KycControllerClearStateAction, KycControllerCreateVendorCustomerAction, KycControllerFetchSessionDisclaimersAction, KycControllerGetCustomerIdentityAction, KycControllerGetKycStatusAction, KycControllerGetSessionStatusAction, KycControllerHandleFrameMessageAction, KycControllerInitializeAction, KycControllerLoadDisclaimersAction, KycControllerRefreshKycStatusAction, KycControllerResetAction, KycControllerStartSumSubAction, } from './KycController-method-action-types.js';
4
+ export { KycService, serviceName } from './KycService.js';
5
+ export type { ApplicantAccessTokenResponse, CapabilityAuthorization, CheckKycRequiredParams, CreateVendorCustomerParams, CreateSessionParams, CreateUkycSessionParams, EncryptionSchema, FetchSessionDisclaimersByCountryParams, FetchSessionDisclaimersBySessionIdParams, GetSessionStatusParams, VendorCustomerResponse, JwksResponse, KycServiceActions, KycServiceCacheUpdatedEvent, KycServiceEvents, KycServiceGranularCacheUpdatedEvent, KycServiceInvalidateQueriesAction, KycServiceMessenger, KycServiceOptions, SetAuthorizationsParams, SubmitSessionDisclaimersParams, SubmitVendorDisclaimersParams, UkycSessionResponse, } from './KycService.js';
6
+ export type { KycServiceCheckKycRequiredAction, KycServiceCreateVendorCustomerAction, KycServiceCreateJourneyAction, KycServiceCreateSessionAction, KycServiceCreateUkycSessionAction, KycServiceFetchIdosEnclaveJwksAction, KycServiceFetchIdosRelayJwksAction, KycServiceFetchKycStatusAction, KycServiceFetchSessionDisclaimersByCountryAction, KycServiceFetchSessionDisclaimersBySessionIdAction, KycServiceFetchVendorDisclaimersAction, KycServiceGetGeoCountryAction, KycServiceGetSessionStatusAction, KycServiceSetAuthorizationsAction, KycServiceSubmitSessionDisclaimersAction, KycServiceSubmitVendorDisclaimersAction, } from './KycService-method-action-types.js';
7
+ export { selectIsKycRequiredForProduct, selectKycPhase, selectKycSumSub, } from './selectors.js';
8
+ export { alpha2ToAlpha3, ALPHA2_TO_ALPHA3 } from './countryCodes.js';
9
+ export { decryptCredentials, generateKeyPair } from './crypto.js';
10
+ export type { DecryptedCredentials, DecryptResult, EncryptedCredentialsEnvelope, X25519KeyPair, } from './crypto.js';
11
+ export type { KycCatalogDocument, KycConsentDocument, KycConsentRecord, KycCustomerIdentity, KycDisclaimer, KycDisclaimersCatalog, KycPhase, KycProduct, KycProviderDisclaimersAccepted, KycSessionDisclaimers, KycSessionStatus, KycSumSubLaunchParams, KycSumSubLauncher, KycSumSubSdkStatus, KycSumSubStatus, KycUserStatus, KycUserStatusResponse, KycVendor, KycIronVendorDisclaimersAccepted, KycMoonpayVendorDisclaimersAccepted, KycVendorDisclaimersAccepted, KycVendorSigning, } from './types.js';
12
+ export { UKYC_CAPABILITY_AUTH_SCHEME, UKYC_KWIL_AUDIENCE, UKYC_STORAGE_ACCESS_TOKEN_AUDIENCE, UKYC_STORAGE_ACCESS_TOKEN_AUDIENCES, UKYC_STORAGE_ACCESS_TOKEN_VERSION, } from './ukyc/constants.js';
13
+ export { deriveClientMaterial, encodeClientMaterial, } from './ukyc/deriveClientMaterial.js';
14
+ export type { EncodedUkycClientMaterial, UkycClientMaterial, } from './ukyc/deriveClientMaterial.js';
15
+ export { encodeStorageAccessTokenForHeader, signStorageAccessToken, } from './ukyc/storageAccessToken.js';
16
+ export type { SignStorageAccessTokenParams, UkycStorageAccessToken, UkycStorageAccessTokenPayload, UkycStorageOperation, UkycTokenPresenter, } from './ukyc/storageAccessToken.js';
17
+ export { mintUkycTestToken } from './ukyc/testToken.js';
18
+ export type { MintedUkycTestToken, MintUkycTestTokenParams, } from './ukyc/testToken.js';
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,4BAA4B,EAC5B,wCAAwC,EACxC,sCAAsC,EACtC,cAAc,GACf,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EACV,oBAAoB,EACpB,mBAAmB,EACnB,2BAA2B,EAC3B,sBAAsB,EACtB,oBAAoB,EACpB,kBAAkB,EAClB,6BAA6B,EAC7B,+BAA+B,EAC/B,6BAA6B,GAC9B,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EACV,6CAA6C,EAC7C,oCAAoC,EACpC,qCAAqC,EACrC,qCAAqC,EACrC,mCAAmC,EACnC,kCAAkC,EAClC,6BAA6B,EAC7B,uCAAuC,EACvC,0CAA0C,EAC1C,sCAAsC,EACtC,+BAA+B,EAC/B,mCAAmC,EACnC,qCAAqC,EACrC,6BAA6B,EAC7B,kCAAkC,EAClC,mCAAmC,EACnC,wBAAwB,EACxB,8BAA8B,GAC/B,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC1D,YAAY,EACV,4BAA4B,EAC5B,uBAAuB,EACvB,sBAAsB,EACtB,0BAA0B,EAC1B,mBAAmB,EACnB,uBAAuB,EACvB,gBAAgB,EAChB,sCAAsC,EACtC,wCAAwC,EACxC,sBAAsB,EACtB,sBAAsB,EACtB,YAAY,EACZ,iBAAiB,EACjB,2BAA2B,EAC3B,gBAAgB,EAChB,mCAAmC,EACnC,iCAAiC,EACjC,mBAAmB,EACnB,iBAAiB,EACjB,uBAAuB,EACvB,8BAA8B,EAC9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AsB,GACvB,MAAM,8BAA8B,CAAC;AACtC,YAAY,EACV,4BAA4B,EAC5B,sBAAsB,EACtB,6BAA6B,EAC7B,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,YAAY,EACV,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ export { KycController, getDefaultKycControllerState, getDefaultKycProviderDisclaimersAccepted, getDefaultKycVendorDisclaimersAccepted, controllerName, } from './KycController.js';
2
+ export { KycService, serviceName } from './KycService.js';
3
+ export { selectIsKycRequiredForProduct, selectKycPhase, selectKycSumSub, } from './selectors.js';
4
+ export { alpha2ToAlpha3, ALPHA2_TO_ALPHA3 } from './countryCodes.js';
5
+ export { decryptCredentials, generateKeyPair } from './crypto.js';
6
+ // UKYC storage-access-token utilities. Exported so a signed capability token can
7
+ // be minted for testing UKYC Storage (see `mintUkycTestToken`).
8
+ export { UKYC_CAPABILITY_AUTH_SCHEME, UKYC_KWIL_AUDIENCE, UKYC_STORAGE_ACCESS_TOKEN_AUDIENCE, UKYC_STORAGE_ACCESS_TOKEN_AUDIENCES, UKYC_STORAGE_ACCESS_TOKEN_VERSION, } from './ukyc/constants.js';
9
+ export { deriveClientMaterial, encodeClientMaterial, } from './ukyc/deriveClientMaterial.js';
10
+ export { encodeStorageAccessTokenForHeader, signStorageAccessToken, } from './ukyc/storageAccessToken.js';
11
+ export { mintUkycTestToken } from './ukyc/testToken.js';
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,4BAA4B,EAC5B,wCAAwC,EACxC,sCAAsC,EACtC,cAAc,GACf,MAAM,oBAAoB,CAAC;AAiC5B,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AA6C1D,OAAO,EACL,6BAA6B,EAC7B,cAAc,EACd,eAAe,GAChB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAiClE,iFAAiF;AACjF,gEAAgE;AAChE,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,kCAAkC,EAClC,mCAAmC,EACnC,iCAAiC,GAClC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,gCAAgC,CAAC;AAKxC,OAAO,EACL,iCAAiC,EACjC,sBAAsB,GACvB,MAAM,8BAA8B,CAAC;AAQtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["export {\n KycController,\n getDefaultKycControllerState,\n getDefaultKycProviderDisclaimersAccepted,\n getDefaultKycVendorDisclaimersAccepted,\n controllerName,\n} from './KycController.js';\nexport type {\n KycControllerActions,\n KycControllerEvents,\n KycControllerGetStateAction,\n KycControllerMessenger,\n KycControllerOptions,\n KycControllerState,\n KycControllerStateChangeEvent,\n KycControllerStatusChangedEvent,\n FetchSessionDisclaimersParams,\n} from './KycController.js';\nexport type {\n KycControllerAcceptTermsAndStartSessionAction,\n KycControllerBuildAuthFrameUrlAction,\n KycControllerBuildCheckFrameUrlAction,\n KycControllerBuildResetFrameUrlAction,\n KycControllerCheckKycRequiredAction,\n KycControllerClearSavedTermsAction,\n KycControllerClearStateAction,\n KycControllerCreateVendorCustomerAction,\n KycControllerFetchSessionDisclaimersAction,\n KycControllerGetCustomerIdentityAction,\n KycControllerGetKycStatusAction,\n KycControllerGetSessionStatusAction,\n KycControllerHandleFrameMessageAction,\n KycControllerInitializeAction,\n KycControllerLoadDisclaimersAction,\n KycControllerRefreshKycStatusAction,\n KycControllerResetAction,\n KycControllerStartSumSubAction,\n} from './KycController-method-action-types.js';\n\nexport { KycService, serviceName } from './KycService.js';\nexport type {\n ApplicantAccessTokenResponse,\n CapabilityAuthorization,\n CheckKycRequiredParams,\n CreateVendorCustomerParams,\n CreateSessionParams,\n CreateUkycSessionParams,\n EncryptionSchema,\n FetchSessionDisclaimersByCountryParams,\n FetchSessionDisclaimersBySessionIdParams,\n GetSessionStatusParams,\n VendorCustomerResponse,\n JwksResponse,\n KycServiceActions,\n KycServiceCacheUpdatedEvent,\n KycServiceEvents,\n KycServiceGranularCacheUpdatedEvent,\n KycServiceInvalidateQueriesAction,\n KycServiceMessenger,\n KycServiceOptions,\n SetAuthorizationsParams,\n SubmitSessionDisclaimersParams,\n SubmitVendorDisclaimersParams,\n UkycSessionResponse,\n} from './KycService.js';\nexport type {\n KycServiceCheckKycRequiredAction,\n KycServiceCreateVendorCustomerAction,\n KycServiceCreateJourneyAction,\n KycServiceCreateSessionAction,\n KycServiceCreateUkycSessionAction,\n KycServiceFetchIdosEnclaveJwksAction,\n KycServiceFetchIdosRelayJwksAction,\n KycServiceFetchKycStatusAction,\n KycServiceFetchSessionDisclaimersByCountryAction,\n KycServiceFetchSessionDisclaimersBySessionIdAction,\n KycServiceFetchVendorDisclaimersAction,\n KycServiceGetGeoCountryAction,\n KycServiceGetSessionStatusAction,\n KycServiceSetAuthorizationsAction,\n KycServiceSubmitSessionDisclaimersAction,\n KycServiceSubmitVendorDisclaimersAction,\n} from './KycService-method-action-types.js';\n\nexport {\n selectIsKycRequiredForProduct,\n selectKycPhase,\n selectKycSumSub,\n} from './selectors.js';\n\nexport { alpha2ToAlpha3, ALPHA2_TO_ALPHA3 } from './countryCodes.js';\nexport { decryptCredentials, generateKeyPair } from './crypto.js';\nexport type {\n DecryptedCredentials,\n DecryptResult,\n EncryptedCredentialsEnvelope,\n X25519KeyPair,\n} from './crypto.js';\n\nexport type {\n KycCatalogDocument,\n KycConsentDocument,\n KycConsentRecord,\n KycCustomerIdentity,\n KycDisclaimer,\n KycDisclaimersCatalog,\n KycPhase,\n KycProduct,\n KycProviderDisclaimersAccepted,\n KycSessionDisclaimers,\n KycSessionStatus,\n KycSumSubLaunchParams,\n KycSumSubLauncher,\n KycSumSubSdkStatus,\n KycSumSubStatus,\n KycUserStatus,\n KycUserStatusResponse,\n KycVendor,\n KycIronVendorDisclaimersAccepted,\n KycMoonpayVendorDisclaimersAccepted,\n KycVendorDisclaimersAccepted,\n KycVendorSigning,\n} from './types.js';\n\n// UKYC storage-access-token utilities. Exported so a signed capability token can\n// be minted for testing UKYC Storage (see `mintUkycTestToken`).\nexport {\n UKYC_CAPABILITY_AUTH_SCHEME,\n UKYC_KWIL_AUDIENCE,\n UKYC_STORAGE_ACCESS_TOKEN_AUDIENCE,\n UKYC_STORAGE_ACCESS_TOKEN_AUDIENCES,\n UKYC_STORAGE_ACCESS_TOKEN_VERSION,\n} from './ukyc/constants.js';\nexport {\n deriveClientMaterial,\n encodeClientMaterial,\n} from './ukyc/deriveClientMaterial.js';\nexport type {\n EncodedUkycClientMaterial,\n UkycClientMaterial,\n} from './ukyc/deriveClientMaterial.js';\nexport {\n encodeStorageAccessTokenForHeader,\n signStorageAccessToken,\n} from './ukyc/storageAccessToken.js';\nexport type {\n SignStorageAccessTokenParams,\n UkycStorageAccessToken,\n UkycStorageAccessTokenPayload,\n UkycStorageOperation,\n UkycTokenPresenter,\n} from './ukyc/storageAccessToken.js';\nexport { mintUkycTestToken } from './ukyc/testToken.js';\nexport type {\n MintedUkycTestToken,\n MintUkycTestTokenParams,\n} from './ukyc/testToken.js';\n"]}
@@ -1,6 +1,5 @@
1
- /// <reference types="debug" />
2
- import { createModuleLogger } from "@metamask/utils";
1
+ import { createModuleLogger } from '@metamask/utils';
3
2
  export declare const projectLogger: import("debug").Debugger;
4
3
  export declare const controllerLog: import("debug").Debugger;
5
4
  export { createModuleLogger };
6
- //# sourceMappingURL=logger.d.cts.map
5
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1E,eAAO,MAAM,aAAa,0BAAwC,CAAC;AAEnE,eAAO,MAAM,aAAa,0BAAqD,CAAC;AAEhF,OAAO,EAAE,kBAAkB,EAAE,CAAC"}
@@ -1,6 +1,6 @@
1
1
  /* istanbul ignore file */
2
- import { createProjectLogger, createModuleLogger } from "@metamask/utils";
2
+ import { createProjectLogger, createModuleLogger } from '@metamask/utils';
3
3
  export const projectLogger = createProjectLogger('kyc-controller');
4
4
  export const controllerLog = createModuleLogger(projectLogger, 'KycController');
5
5
  export { createModuleLogger };
6
- //# sourceMappingURL=logger.mjs.map
6
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,0BAA0B;AAE1B,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1E,MAAM,CAAC,MAAM,aAAa,GAAG,mBAAmB,CAAC,gBAAgB,CAAC,CAAC;AAEnE,MAAM,CAAC,MAAM,aAAa,GAAG,kBAAkB,CAAC,aAAa,EAAE,eAAe,CAAC,CAAC;AAEhF,OAAO,EAAE,kBAAkB,EAAE,CAAC","sourcesContent":["/* istanbul ignore file */\n\nimport { createProjectLogger, createModuleLogger } from '@metamask/utils';\n\nexport const projectLogger = createProjectLogger('kyc-controller');\n\nexport const controllerLog = createModuleLogger(projectLogger, 'KycController');\n\nexport { createModuleLogger };\n"]}
@@ -1,5 +1,5 @@
1
- import type { KycControllerState } from "./KycController.mjs";
2
- import type { KycProduct } from "./types.mjs";
1
+ import type { KycControllerState } from './KycController.js';
2
+ import type { KycProduct } from './types.js';
3
3
  /**
4
4
  * Selects the current flow phase.
5
5
  *
@@ -20,5 +20,5 @@ export declare const selectKycSumSub: (state: KycControllerState) => KycControll
20
20
  * @param product - The consuming feature.
21
21
  * @returns A selector returning the cached requirement, or `undefined`.
22
22
  */
23
- export declare const selectIsKycRequiredForProduct: (product: KycProduct) => (state: KycControllerState) => boolean | undefined;
24
- //# sourceMappingURL=selectors.d.mts.map
23
+ export declare const selectIsKycRequiredForProduct: (product: KycProduct) => ((state: KycControllerState) => boolean | undefined);
24
+ //# sourceMappingURL=selectors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"selectors.d.ts","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAM7C;;;;;GAKG;AACH,eAAO,MAAM,cAAc,UAClB,kBAAkB,KACxB,kBAAkB,CAAC,OAAO,CAAgB,CAAC;AAE9C;;;;;GAKG;AACH,eAAO,MAAM,eAAe,UACnB,kBAAkB,KACxB,kBAAkB,CAAC,QAAQ,CAAiB,CAAC;AAEhD;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,YAC/B,UAAU,KAClB,CAAC,CAAC,KAAK,EAAE,kBAAkB,KAAK,OAAO,GAAG,SAAS,CAInD,CAAC"}
@@ -1,4 +1,4 @@
1
- import { createSelector } from "reselect";
1
+ import { createSelector } from 'reselect';
2
2
  const selectKycRequiredByProduct = (state) => state.kycRequiredByProduct;
3
3
  /**
4
4
  * Selects the current flow phase.
@@ -21,4 +21,4 @@ export const selectKycSumSub = (state) => state.sumsub;
21
21
  * @returns A selector returning the cached requirement, or `undefined`.
22
22
  */
23
23
  export const selectIsKycRequiredForProduct = (product) => createSelector([selectKycRequiredByProduct], (map) => map[product]);
24
- //# sourceMappingURL=selectors.mjs.map
24
+ //# sourceMappingURL=selectors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"selectors.js","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAK1C,MAAM,0BAA0B,GAAG,CACjC,KAAyB,EACmB,EAAE,CAAC,KAAK,CAAC,oBAAoB,CAAC;AAE5E;;;;;GAKG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAC5B,KAAyB,EACI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC;AAE9C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,KAAyB,EACK,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC;AAEhD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAG,CAC3C,OAAmB,EACmC,EAAE,CACxD,cAAc,CACZ,CAAC,0BAA0B,CAAC,EAC5B,CAAC,GAAG,EAAuB,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,CAC3C,CAAC","sourcesContent":["import { createSelector } from 'reselect';\n\nimport type { KycControllerState } from './KycController.js';\nimport type { KycProduct } from './types.js';\n\nconst selectKycRequiredByProduct = (\n state: KycControllerState,\n): KycControllerState['kycRequiredByProduct'] => state.kycRequiredByProduct;\n\n/**\n * Selects the current flow phase.\n *\n * @param state - The KycController state.\n * @returns The current phase.\n */\nexport const selectKycPhase = (\n state: KycControllerState,\n): KycControllerState['phase'] => state.phase;\n\n/**\n * Selects the SumSub sub-flow state.\n *\n * @param state - The KycController state.\n * @returns The SumSub state.\n */\nexport const selectKycSumSub = (\n state: KycControllerState,\n): KycControllerState['sumsub'] => state.sumsub;\n\n/**\n * Creates a selector that returns whether KYC is required for a product.\n *\n * @param product - The consuming feature.\n * @returns A selector returning the cached requirement, or `undefined`.\n */\nexport const selectIsKycRequiredForProduct = (\n product: KycProduct,\n): ((state: KycControllerState) => boolean | undefined) =>\n createSelector(\n [selectKycRequiredByProduct],\n (map): boolean | undefined => map[product],\n );\n"]}
@@ -80,8 +80,28 @@ export type KycPhase = 'idle' | 'terms' | 'session' | 'check' | 'auth' | 'form'
80
80
  * already approved on the relay (`kycStatus`) while the vendor is still
81
81
  * finalizing its own decision (`finalStatus`). There is nothing left for the
82
82
  * applicant to do, so the SDK is not launched; see `statusMessage`.
83
+ * - `abandoned` — the applicant closed the SDK before submitting. Unlike
84
+ * `failed`, nothing went wrong, so `error` is left unset and consumers should
85
+ * offer a retry rather than report a problem.
83
86
  */
84
- export type KycSumSubStatus = 'idle' | 'creatingSession' | 'fetchingToken' | 'launching' | 'inProgress' | 'polling' | 'complete' | 'failed' | 'vendorProcessing';
87
+ export type KycSumSubStatus = 'idle' | 'creatingSession' | 'fetchingToken' | 'launching' | 'inProgress' | 'polling' | 'complete' | 'abandoned' | 'failed' | 'vendorProcessing';
88
+ /**
89
+ * Status strings a SumSub SDK reports, through either the status-change
90
+ * callback or the `launch` result. Distinct from {@link KycSumSubStatus},
91
+ * which tracks the controller's own sub-flow.
92
+ *
93
+ * - `Ready` — initialized and presented; no step reported yet.
94
+ * - `Failed` — the SDK itself could not run.
95
+ * - `Initial` — no verification step has been passed.
96
+ * - `Incomplete` — some but not all verification steps have been passed.
97
+ * - `Pending` — the applicant submitted and review is pending.
98
+ * - `TemporarilyDeclined` — the applicant was declined but may resubmit.
99
+ * - `FinallyRejected` — the applicant was rejected for good.
100
+ * - `Approved` — the applicant was approved.
101
+ * - `ActionCompleted` — an applicant action (e.g. a liveness check) finished.
102
+ * - `Completed` — normalized completion reported by non-native launchers.
103
+ */
104
+ export type KycSumSubSdkStatus = 'Ready' | 'Failed' | 'Initial' | 'Incomplete' | 'Pending' | 'TemporarilyDeclined' | 'FinallyRejected' | 'Approved' | 'ActionCompleted' | 'Completed';
85
105
  /**
86
106
  * The status of a UKYC session, returned by the `GET /sessions/{id}/status`
87
107
  * endpoint and polled after the SumSub SDK completes to determine the final
@@ -124,10 +144,11 @@ export type KycVendorSigning = {
124
144
  content_id?: string;
125
145
  };
126
146
  /**
127
- * A legal document in the idOS / KYC-provider catalog
128
- * (`GET /disclaimers`, or `GET`/`POST /sessions/{sessionId}/disclaimers`).
147
+ * A legal document in the global idOS / KYC-provider catalog
148
+ * (`GET /disclaimers`). Carries no consent state, which only exists within a
149
+ * session.
129
150
  */
130
- export type KycConsentDocument = {
151
+ export type KycCatalogDocument = {
131
152
  /** Stable identifier of the legal document. */
132
153
  key: string;
133
154
  /** Version of the document currently in force. */
@@ -136,10 +157,13 @@ export type KycConsentDocument = {
136
157
  title: string;
137
158
  /** URL the document body is hosted at. */
138
159
  url: string;
139
- /**
140
- * Whether the document version has already been consented to (session-scoped
141
- * fetches). For the global catalog this is typically `false`.
142
- */
160
+ };
161
+ /**
162
+ * A legal document in the session-scoped idOS / KYC-provider catalog
163
+ * (`GET`/`POST /sessions/{sessionId}/disclaimers`).
164
+ */
165
+ export type KycConsentDocument = KycCatalogDocument & {
166
+ /** Whether the document version has already been consented to. */
143
167
  consented: boolean;
144
168
  };
145
169
  /**
@@ -150,21 +174,56 @@ export type KycConsentRecord = {
150
174
  key: string;
151
175
  version: string;
152
176
  };
177
+ /**
178
+ * MoonPay vendor T&C1 acceptance persisted under
179
+ * {@link KycVendorDisclaimersAccepted.moonpay}.
180
+ */
181
+ export type KycMoonpayVendorDisclaimersAccepted = {
182
+ /** ISO-8601 timestamp of terms acceptance for MoonPay. */
183
+ termsAcceptedAt: string;
184
+ };
185
+ /**
186
+ * Iron vendor T&C1 acceptance persisted under
187
+ * {@link KycVendorDisclaimersAccepted.iron}.
188
+ */
189
+ export type KycIronVendorDisclaimersAccepted = {
190
+ /** IDs of Iron vendor disclaimers the customer accepted. */
191
+ disclaimerIds: string[];
192
+ };
193
+ /**
194
+ * Persisted KYC-provider disclaimer acceptance (T&C2) with a fixed `sumsub`
195
+ * key.
196
+ */
197
+ export type KycProviderDisclaimersAccepted = {
198
+ sumsub: KycConsentRecord[] | null;
199
+ };
200
+ /**
201
+ * Persisted vendor-disclaimer acceptance with fixed `moonpay` and `iron` keys.
202
+ */
203
+ export type KycVendorDisclaimersAccepted = {
204
+ moonpay: KycMoonpayVendorDisclaimersAccepted | null;
205
+ iron: KycIronVendorDisclaimersAccepted | null;
206
+ };
153
207
  /**
154
208
  * idOS / KYC-provider disclaimer catalog returned by
155
209
  * `GET /disclaimers?country=` (no session — no credential-reuse consent state).
156
210
  */
157
211
  export type KycDisclaimersCatalog = {
158
212
  /** idOS legal documents. */
159
- idOS: KycConsentDocument[];
213
+ idOS: KycCatalogDocument[];
160
214
  /** KYC provider (SumSub) legal documents. */
161
- kycProvider: KycConsentDocument[];
215
+ kycProvider: KycCatalogDocument[];
162
216
  };
163
217
  /**
164
218
  * Session-scoped disclaimer catalog returned by
165
- * `GET`/`POST /sessions/{sessionId}/disclaimers`.
219
+ * `GET`/`POST /sessions/{sessionId}/disclaimers`. Documents additionally report
220
+ * whether that version was already consented to for the session.
166
221
  */
167
- export type KycSessionDisclaimers = KycDisclaimersCatalog & {
222
+ export type KycSessionDisclaimers = {
223
+ /** idOS legal documents. */
224
+ idOS: KycConsentDocument[];
225
+ /** KYC provider (SumSub) legal documents. */
226
+ kycProvider: KycConsentDocument[];
168
227
  /** Whether the user consented to reuse existing idOS credentials. */
169
228
  credentialReusabilityConsentGiven: boolean;
170
229
  };
@@ -214,4 +273,4 @@ export type KycSumSubLauncher = {
214
273
  */
215
274
  launch(params: KycSumSubLaunchParams): Promise<Record<string, unknown>>;
216
275
  };
217
- //# sourceMappingURL=types.d.cts.map
276
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,CAAC;AAEpD;;;;;;GAMG;AACH,MAAM,MAAM,SAAS,GAAG,SAAS,GAAG,MAAM,CAAC;AAE3C;;;;;;;;GAQG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,sEAAsE;IACtE,MAAM,EAAE,SAAS,CAAC;I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/C,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,4BAA4B;IAC5B,IAAI,EAAE,kBAAkB,EAAE,CAAC;IAC3B,6CAA6C;IAC7C,WAAW,EAAE,kBAAkB,EAAE,CAAC;CACnC,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,4BAA4B;IAC5B,IAAI,EAAE,kBAAkB,EAAE,CAAC;IAC3B,6CAA6C;IAC7C,WAAW,EAAE,kBAAkB,EAAE,CAAC;IAClC,qEAAqE;IACrE,iCAAiC,EAAE,OAAO,CAAC;CAC5C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC;;OAEG;IACH,oBAAoB,EAAE,MAAM,CAAC;IAE7B;;;OAGG;IACH,iBAAiB,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAEzC;;OAEG;IACH,cAAc,CAAC,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;IAEjE;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B;;;OAGG;IACH,WAAW,IAAI,OAAO,CAAC;IAEvB;;OAEG;IACH,MAAM,CAAC,MAAM,EAAE,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACzE,CAAC"}
@@ -6,4 +6,4 @@
6
6
  * intentionally vendor-neutral so a future vendor swap does not ripple out.
7
7
  */
8
8
  export {};
9
- //# sourceMappingURL=types.mjs.map
9
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG","sourcesContent":["/**\n * Shared types for the KYC controller and service.\n *\n * The KYC flow is vendor-backed (currently MoonPay for identity + SumSub for\n * document verification) but the surface exposed to consumers (ramps, card) is\n * intentionally vendor-neutral so a future vendor swap does not ripple out.\n */\n\n/**\n * A MetaMask feature that consumes KYC. Used to key the per-product\n * \"is KYC required\" cache so ramps, card, and money can share one controller.\n */\nexport type KycProduct = 'ramps' | 'card' | 'money';\n\n/**\n * Identity vendors supported behind the KYC surface.\n *\n * - `moonpay` — MoonPay Check/Auth frames + SumSub documents.\n * - `iron` — Iron-only Money/VBA path: empty-shell customer → consents →\n * SumSub, with no MoonPay Check/Auth frames.\n */\nexport type KycVendor = 'moonpay' | 'iron';\n\n/**\n * Vendor-scoped identity for the currently authenticated KYC customer.\n *\n * Exposed to consumers (e.g. ramps) that must attach the vendor customer id to\n * downstream provider calls without reading the full KYC state, which also\n * holds session/access tokens. The identifier is session-scoped: it is only\n * available once the customer has authenticated through the current flow and\n * is cleared on `reset()`.\n */\nexport type KycCustomerIdentity = {\n /** The identity vendor that issued {@link KycCustomerIdentity.id}. */\n vendor: KycVendor;\n /** The vendor customer id (e.g. MoonPay customer UUID). */\n id: string;\n};\n\n/**\n * User-keyed KYC status returned by `GET /kyc/status` and stored for toast /\n * banner rendering. Collapses vendor + SumSub / relay state into the offsite\n * contract.\n */\nexport type KycUserStatus =\n | 'not-started'\n | 'pending'\n | 'need-more-information'\n | 'terminal-failure'\n | 'completed';\n\n/**\n * Payload from `GET /kyc/status`, including optional fields that power the\n * 3-state error contract (retryable SumSub vs terminal vs EDD).\n */\nexport type KycUserStatusResponse = {\n status: KycUserStatus;\n /** Present when the user can reopen a SumSub session (retryable path). */\n sumsubSessionId?: string;\n /** Machine-readable error code for terminal / EDD UX. */\n errorCode?: string;\n};\n\n/**\n * Phases of the end-to-end identity flow.\n *\n * - `idle` — nothing started.\n * - `terms` — waiting for the customer to accept the vendor terms.\n * - `session` — creating the vendor session (MoonPay) or creating the UKYC\n * session and recording session-scoped disclaimers (non-MoonPay vendors).\n * - `check` — running the invisible connection-check frame (MoonPay only).\n * - `auth` — running the visible authentication (OTP) frame (MoonPay only).\n * - `form` — authenticated. When the flow is scoped to a product, the\n * KYC-required check runs automatically from here; otherwise the consumer\n * drives it manually via `checkKycRequired`. Consents-path vendors skip\n * this phase.\n * - `submit` — submitting the KYC-required check / launching SumSub.\n * - `done` — flow complete; see `kycRequiredByProduct` / `sumsub` /\n * `userStatus`. When KYC is required, the document-verification sub-flow is\n * launched automatically.\n * - `error` — flow halted; see `error`.\n */\nexport type KycPhase =\n | 'idle'\n | 'terms'\n | 'session'\n | 'check'\n | 'auth'\n | 'form'\n | 'submit'\n | 'done'\n | 'error';\n\n/**\n * Progress of the SumSub document-verification sub-flow.\n *\n * - `polling` — the SDK finished and the controller is polling the UKYC\n * backend for the session's final decision (see `KycSessionStatus`). The\n * sub-flow resolves to `complete` or `failed` once a terminal status arrives.\n * - `vendorProcessing` — session creation reported that the applicant is\n * already approved on the relay (`kycStatus`) while the vendor is still\n * finalizing its own decision (`finalStatus`). There is nothing left for the\n * applicant to do, so the SDK is not launched; see `statusMessage`.\n * - `abandoned` — the applicant closed the SDK before submitting. Unlike\n * `failed`, nothing went wrong, so `error` is left unset and consumers should\n * offer a retry rather than report a problem.\n */\nexport type KycSumSubStatus =\n | 'idle'\n | 'creatingSession'\n | 'fetchingToken'\n | 'launching'\n | 'inProgress'\n | 'polling'\n | 'complete'\n | 'abandoned'\n | 'failed'\n | 'vendorProcessing';\n\n/**\n * Status strings a SumSub SDK reports, through either the status-change\n * callback or the `launch` result. Distinct from {@link KycSumSubStatus},\n * which tracks the controller's own sub-flow.\n *\n * - `Ready` — initialized and presented; no step reported yet.\n * - `Failed` — the SDK itself could not run.\n * - `Initial` — no verification step has been passed.\n * - `Incomplete` — some but not all verification steps have been passed.\n * - `Pending` — the applicant submitted and review is pending.\n * - `TemporarilyDeclined` — the applicant was declined but may resubmit.\n * - `FinallyRejected` — the applicant was rejected for good.\n * - `Approved` — the applicant was approved.\n * - `ActionCompleted` — an applicant action (e.g. a liveness check) finished.\n * - `Completed` — normalized completion reported by non-native launchers.\n */\nexport type KycSumSubSdkStatus =\n | 'Ready'\n | 'Failed'\n | 'Initial'\n | 'Incomplete'\n | 'Pending'\n | 'TemporarilyDeclined'\n | 'FinallyRejected'\n | 'Approved'\n | 'ActionCompleted'\n | 'Completed';\n\n/**\n * The status of a UKYC session, returned by the `GET /sessions/{id}/status`\n * endpoint and polled after the SumSub SDK completes to determine the final\n * verification decision.\n */\nexport type KycSessionStatus = {\n /**\n * The overall status of the session. Terminal values (e.g. `approved`,\n * `completed`, `rejected`, `failed`, `blocked`) end polling; any other value\n * keeps polling.\n */\n finalStatus: string;\n /** Optional human-readable message describing the status. */\n statusMessage?: string;\n /** The vendor-agnostic external user id associated with the session. */\n externalUserId: string;\n /** The KYC decision status. */\n kycStatus: string;\n /** The identity vendor that handled the session. */\n vendor: string;\n /** The vendor-specific status. */\n vendorStatus: string;\n};\n\n/**\n * A single disclaimer/term the customer must accept before a vendor session is\n * created (`GET /vendors/{vendor}/disclaimers`).\n */\nexport type KycDisclaimer = {\n id: string;\n // Mirrors the vendor API response field, which is snake_case.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n display_name: string;\n url: string;\n};\n\n/**\n * A vendor T&C signing returned by `POST /vendors/{vendor}/disclaimers`.\n */\nexport type KycVendorSigning = {\n /** Iron signing id. */\n id: string;\n // Mirrors the vendor API response field, which is snake_case.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n customer_id: string;\n // Mirrors the vendor API response field, which is snake_case.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n content_id?: string;\n};\n\n/**\n * A legal document in the global idOS / KYC-provider catalog\n * (`GET /disclaimers`). Carries no consent state, which only exists within a\n * session.\n */\nexport type KycCatalogDocument = {\n /** Stable identifier of the legal document. */\n key: string;\n /** Version of the document currently in force. */\n version: string;\n /** Human-readable document title. */\n title: string;\n /** URL the document body is hosted at. */\n url: string;\n};\n\n/**\n * A legal document in the session-scoped idOS / KYC-provider catalog\n * (`GET`/`POST /sessions/{sessionId}/disclaimers`).\n */\nexport type KycConsentDocument = KycCatalogDocument & {\n /** Whether the document version has already been consented to. */\n consented: boolean;\n};\n\n/**\n * A consent record posted for a catalog document. `key` and `version` must\n * match the current session catalog.\n */\nexport type KycConsentRecord = {\n key: string;\n version: string;\n};\n\n/**\n * MoonPay vendor T&C1 acceptance persisted under\n * {@link KycVendorDisclaimersAccepted.moonpay}.\n */\nexport type KycMoonpayVendorDisclaimersAccepted = {\n /** ISO-8601 timestamp of terms acceptance for MoonPay. */\n termsAcceptedAt: string;\n};\n\n/**\n * Iron vendor T&C1 acceptance persisted under\n * {@link KycVendorDisclaimersAccepted.iron}.\n */\nexport type KycIronVendorDisclaimersAccepted = {\n /** IDs of Iron vendor disclaimers the customer accepted. */\n disclaimerIds: string[];\n};\n\n/**\n * Persisted KYC-provider disclaimer acceptance (T&C2) with a fixed `sumsub`\n * key.\n */\nexport type KycProviderDisclaimersAccepted = {\n sumsub: KycConsentRecord[] | null;\n};\n\n/**\n * Persisted vendor-disclaimer acceptance with fixed `moonpay` and `iron` keys.\n */\nexport type KycVendorDisclaimersAccepted = {\n moonpay: KycMoonpayVendorDisclaimersAccepted | null;\n iron: KycIronVendorDisclaimersAccepted | null;\n};\n\n/**\n * idOS / KYC-provider disclaimer catalog returned by\n * `GET /disclaimers?country=` (no session — no credential-reuse consent state).\n */\nexport type KycDisclaimersCatalog = {\n /** idOS legal documents. */\n idOS: KycCatalogDocument[];\n /** KYC provider (SumSub) legal documents. */\n kycProvider: KycCatalogDocument[];\n};\n\n/**\n * Session-scoped disclaimer catalog returned by\n * `GET`/`POST /sessions/{sessionId}/disclaimers`. Documents additionally report\n * whether that version was already consented to for the session.\n */\nexport type KycSessionDisclaimers = {\n /** idOS legal documents. */\n idOS: KycConsentDocument[];\n /** KYC provider (SumSub) legal documents. */\n kycProvider: KycConsentDocument[];\n /** Whether the user consented to reuse existing idOS credentials. */\n credentialReusabilityConsentGiven: boolean;\n};\n\n/**\n * Parameters passed to a platform SumSub launcher.\n */\nexport type KycSumSubLaunchParams = {\n /**\n * The applicant access token used to initialize the SumSub SDK.\n */\n applicantAccessToken: string;\n\n /**\n * Called by the SDK when the access token expires; must resolve with a fresh\n * applicant access token.\n */\n onTokenExpiration: () => Promise<string>;\n\n /**\n * Called when the SDK reports a status transition.\n */\n onStatusChange?: (prevStatus: string, newStatus: string) => void;\n\n /**\n * BCP-47 locale for the SDK UI.\n */\n locale?: string;\n\n /**\n * Enables SDK debug logging.\n */\n debug?: boolean;\n};\n\n/**\n * Platform adapter that launches the native/web SumSub SDK.\n *\n * The KYC controller is platform-agnostic and does not import any SDK; each\n * client (mobile / extension / web) injects an implementation of this\n * interface. The controller owns all orchestration (session creation, token\n * exchange, token refresh, state) and only delegates the actual SDK\n * presentation to `launch`.\n */\nexport type KycSumSubLauncher = {\n /**\n * Whether the underlying SDK is available in the current runtime (e.g. the\n * native module is linked). When `false`, `startSumSub` fails fast.\n */\n isAvailable(): boolean;\n\n /**\n * Presents the SumSub verification flow and resolves with the SDK result.\n */\n launch(params: KycSumSubLaunchParams): Promise<Record<string, unknown>>;\n};\n"]}