@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
@@ -1,1877 +0,0 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _KycController_instances, _KycController_sumsubLauncher, _KycController_moonpayFrameKeypair, _KycController_authClientToken, _KycController_generation, _KycController_sessionStatusPollIntervalMs, _KycController_pollTimer, _KycController_pollToken, _KycController_userStatusPollIntervalMs, _KycController_userStatusPollTimer, _KycController_userStatusPolling, _KycController_userStatusPollToken, _KycController_localUserSecretStore, _KycController_startConsentsSession, _KycController_recordSessionDisclaimers, _KycController_createSession, _KycController_clearAcceptedTerms, _KycController_clearMoonPaySession, _KycController_dropTermsUnlessForVendor, _KycController_hasTermsForVendor, _KycController_handleCheckOutcome, _KycController_handleAuthOutcome, _KycController_continueAfterAuthentication, _KycController_requireTermsReacceptance, _KycController_buildUkycSessionVendorFields, _KycController_createUkycSession, _KycController_fetchAndApplyUserStatus, _KycController_applyUserStatus, _KycController_ensureUserStatusPolling, _KycController_stopUserStatusPolling, _KycController_startSessionStatusPolling, _KycController_pollSessionStatusOnce, _KycController_stopPolling, _KycController_cancelPendingSession, _KycController_updateIfCurrent, _KycController_applyUpdate, _KycController_assertAttestedServerPublicKey, _KycController_fail;
13
- import { BaseController } from "@metamask/base-controller";
14
- import { stringToBytes } from "@metamask/utils";
15
- import { x25519 } from "@noble/curves/ed25519";
16
- import { decryptCredentials, generateKeyPair } from "./crypto.mjs";
17
- import { toBase64Url } from "./encoding.mjs";
18
- import { controllerLog } from "./logger.mjs";
19
- import { deriveClientMaterial } from "./ukyc/deriveClientMaterial.mjs";
20
- import { verifyJwtChain } from "./ukyc/jwtChain.mjs";
21
- import { getOrCreateLocalUserSecret } from "./ukyc/localUserSecret.mjs";
22
- import { encodeStorageAccessTokenForHeader, signStorageAccessToken } from "./ukyc/storageAccessToken.mjs";
23
- import { wrapEncryptionKey } from "./ukyc/wrapEncryptionKey.mjs";
24
- // === GENERAL ===
25
- export const controllerName = 'KycController';
26
- const FRAMES_BASE_URL = 'https://blocks.moonpay.com/platform/v1';
27
- const CHANNEL_CHECK = 'ch_1';
28
- const CHANNEL_AUTH = 'ch_2';
29
- const CHANNEL_RESET = 'ch_reset';
30
- // Placeholder credentials for the SumSub sub-flow. These are demo values that
31
- // must be replaced with real UKYC-issued material before production use.
32
- const MOCK_JWT_TOKEN = 'mock-jwt-token';
33
- // Lifetime of the read-only `ukyc_capability_token` minted when creating a
34
- // UKYC session. The storage-and-auth spec requires the token's `expires_at` to
35
- // cover the KYC session's expected lifetime — including the provider journey —
36
- // rather than a fixed short window, so this is a session-scoped window.
37
- const UKYC_CAPABILITY_TOKEN_TTL_MS = 4 * 60 * 60 * 1000;
38
- // The SumSub SDK status that signals the applicant finished the flow
39
- // successfully. Any other resolution (abandonment, failure, or a non-success
40
- // outcome) must not be recorded as `complete`.
41
- const SUMSUB_COMPLETED_STATUS = 'Completed';
42
- // Phases that represent an active vendor-session flow (tokens issued and/or
43
- // Check/Auth frames in progress). A repeat `initialize` while in one of these
44
- // must not restart the session and disrupt the in-flight flow.
45
- const IN_PROGRESS_PHASES = [
46
- 'session',
47
- 'check',
48
- 'auth',
49
- 'form',
50
- 'submit',
51
- ];
52
- // How often to poll the UKYC session status after the SumSub SDK completes,
53
- // until a terminal status is reached. Overridable via the constructor.
54
- const DEFAULT_SESSION_STATUS_POLL_INTERVAL_MS = 15000;
55
- // UKYC status values. `kycStatus` (the relay-side decision) and `finalStatus`
56
- // (the vendor-side outcome) draw from the same vocabulary, so they are defined
57
- // once here and composed into the sets/checks below rather than repeated as
58
- // literals.
59
- const KYC_STATUSES = {
60
- approved: 'approved',
61
- completed: 'completed',
62
- rejected: 'rejected',
63
- failed: 'failed',
64
- blocked: 'blocked',
65
- pending: 'pending',
66
- };
67
- // `finalStatus` values that end the polling loop. Anything else (e.g.
68
- // `KYC_STATUSES.pending`) keeps polling.
69
- const TERMINAL_SESSION_STATUSES = new Set([
70
- KYC_STATUSES.approved,
71
- KYC_STATUSES.completed,
72
- KYC_STATUSES.rejected,
73
- KYC_STATUSES.failed,
74
- KYC_STATUSES.blocked,
75
- ]);
76
- // Terminal `finalStatus` values that represent a successful verification. Any
77
- // other terminal status resolves the sub-flow to `failed`.
78
- const SUCCESSFUL_SESSION_STATUSES = new Set([
79
- KYC_STATUSES.approved,
80
- KYC_STATUSES.completed,
81
- ]);
82
- // Session creation can report that the applicant is already approved on the
83
- // relay (`kycStatus === KYC_STATUSES.approved`) while the vendor is still
84
- // finalizing its decision (`finalStatus === KYC_STATUSES.pending`, a
85
- // non-terminal status). In that case there is nothing left for the applicant
86
- // to do, so the sub-flow stops before launching the SDK and surfaces this
87
- // message.
88
- const VENDOR_PROCESSING_MESSAGE = 'Your KYC has been submitted and is being processed by the vendor.';
89
- // UKYC / relay error indicating the applicant already finished KYC. Mapped to
90
- // the simplified `completed` user status for the Money toast surface.
91
- const SESSION_NOT_IN_VALID_STATE = 'session_not_in_valid_state';
92
- // How often to refresh the user-keyed `GET /kyc/status` while the simplified
93
- // status is still `pending`. Overridable via the constructor.
94
- const DEFAULT_USER_STATUS_POLL_INTERVAL_MS = 15000;
95
- const kycControllerMetadata = {
96
- phase: {
97
- includeInDebugSnapshot: true,
98
- includeInStateLogs: true,
99
- persist: false,
100
- usedInUi: true,
101
- },
102
- statusMessage: {
103
- includeInDebugSnapshot: true,
104
- includeInStateLogs: true,
105
- persist: false,
106
- usedInUi: true,
107
- },
108
- error: {
109
- includeInDebugSnapshot: true,
110
- includeInStateLogs: true,
111
- persist: false,
112
- usedInUi: true,
113
- },
114
- email: {
115
- includeInDebugSnapshot: false,
116
- includeInStateLogs: false,
117
- persist: false,
118
- usedInUi: false,
119
- },
120
- termsAcceptedAt: {
121
- includeInDebugSnapshot: true,
122
- includeInStateLogs: true,
123
- persist: true,
124
- usedInUi: false,
125
- },
126
- acceptedDisclaimerIds: {
127
- includeInDebugSnapshot: true,
128
- includeInStateLogs: true,
129
- persist: true,
130
- usedInUi: false,
131
- },
132
- termsAcceptedVendor: {
133
- includeInDebugSnapshot: true,
134
- includeInStateLogs: true,
135
- persist: true,
136
- usedInUi: false,
137
- },
138
- sumsubTncAccepted: {
139
- includeInDebugSnapshot: true,
140
- includeInStateLogs: true,
141
- persist: true,
142
- usedInUi: false,
143
- },
144
- idosTncAccepted: {
145
- includeInDebugSnapshot: true,
146
- includeInStateLogs: true,
147
- persist: true,
148
- usedInUi: false,
149
- },
150
- credentialReusabilityConsentGiven: {
151
- includeInDebugSnapshot: true,
152
- includeInStateLogs: true,
153
- persist: false,
154
- usedInUi: false,
155
- },
156
- disclaimers: {
157
- includeInDebugSnapshot: false,
158
- includeInStateLogs: false,
159
- persist: false,
160
- usedInUi: true,
161
- },
162
- disclaimersError: {
163
- includeInDebugSnapshot: true,
164
- includeInStateLogs: true,
165
- persist: false,
166
- usedInUi: true,
167
- },
168
- sessionDisclaimers: {
169
- includeInDebugSnapshot: false,
170
- includeInStateLogs: false,
171
- persist: false,
172
- usedInUi: true,
173
- },
174
- geoCountry: {
175
- includeInDebugSnapshot: true,
176
- includeInStateLogs: true,
177
- persist: false,
178
- usedInUi: true,
179
- },
180
- sessionToken: {
181
- includeInDebugSnapshot: false,
182
- includeInStateLogs: false,
183
- persist: false,
184
- usedInUi: false,
185
- },
186
- accessToken: {
187
- includeInDebugSnapshot: false,
188
- includeInStateLogs: false,
189
- persist: false,
190
- usedInUi: false,
191
- },
192
- moonpayCustomerId: {
193
- includeInDebugSnapshot: false,
194
- includeInStateLogs: false,
195
- persist: false,
196
- usedInUi: false,
197
- },
198
- activeVendor: {
199
- includeInDebugSnapshot: true,
200
- includeInStateLogs: true,
201
- persist: false,
202
- usedInUi: true,
203
- },
204
- activeProduct: {
205
- includeInDebugSnapshot: true,
206
- includeInStateLogs: true,
207
- persist: false,
208
- usedInUi: true,
209
- },
210
- kycRequiredByProduct: {
211
- includeInDebugSnapshot: true,
212
- includeInStateLogs: true,
213
- persist: true,
214
- usedInUi: true,
215
- },
216
- lastCheckedAt: {
217
- includeInDebugSnapshot: true,
218
- includeInStateLogs: true,
219
- persist: true,
220
- usedInUi: false,
221
- },
222
- userStatus: {
223
- includeInDebugSnapshot: true,
224
- includeInStateLogs: true,
225
- persist: true,
226
- usedInUi: true,
227
- },
228
- userStatusSumsubSessionId: {
229
- includeInDebugSnapshot: false,
230
- includeInStateLogs: false,
231
- persist: true,
232
- usedInUi: true,
233
- },
234
- userStatusErrorCode: {
235
- includeInDebugSnapshot: true,
236
- includeInStateLogs: true,
237
- persist: true,
238
- usedInUi: true,
239
- },
240
- sumsub: {
241
- includeInDebugSnapshot: false,
242
- includeInStateLogs: false,
243
- persist: false,
244
- usedInUi: true,
245
- },
246
- };
247
- /**
248
- * Constructs the default {@link KycController} state.
249
- *
250
- * @returns The default state.
251
- */
252
- export function getDefaultKycControllerState() {
253
- return {
254
- phase: 'idle',
255
- statusMessage: '',
256
- error: null,
257
- email: null,
258
- termsAcceptedAt: null,
259
- acceptedDisclaimerIds: [],
260
- termsAcceptedVendor: null,
261
- sumsubTncAccepted: null,
262
- idosTncAccepted: null,
263
- credentialReusabilityConsentGiven: null,
264
- disclaimers: [],
265
- disclaimersError: null,
266
- sessionDisclaimers: null,
267
- geoCountry: null,
268
- sessionToken: null,
269
- accessToken: null,
270
- moonpayCustomerId: null,
271
- activeVendor: 'moonpay',
272
- activeProduct: null,
273
- kycRequiredByProduct: {},
274
- lastCheckedAt: null,
275
- userStatus: null,
276
- userStatusSumsubSessionId: null,
277
- userStatusErrorCode: null,
278
- sumsub: {
279
- status: 'idle',
280
- result: null,
281
- sessionId: null,
282
- applicantAccessToken: null,
283
- sessionStatus: null,
284
- },
285
- };
286
- }
287
- /**
288
- * Whether an error indicates the applicant already finished KYC — the UKYC /
289
- * relay `session_not_in_valid_state` signal — which the controller maps to the
290
- * simplified `completed` user status.
291
- *
292
- * @param error - The caught error.
293
- * @returns `true` when the error carries the `session_not_in_valid_state`
294
- * marker.
295
- */
296
- function isSessionAlreadyCompletedError(error) {
297
- return String(error).includes(SESSION_NOT_IN_VALID_STATE);
298
- }
299
- /**
300
- * Whether recording session disclaimers failed because those document
301
- * versions were already consented for the session (`409 Conflict`).
302
- *
303
- * @param error - The caught error.
304
- * @returns `true` when the error is an HTTP 409.
305
- */
306
- function isConsentConflictError(error) {
307
- return (typeof error === 'object' &&
308
- error !== null &&
309
- typeof error.httpStatus === 'number' &&
310
- error.httpStatus === 409);
311
- }
312
- /**
313
- * Maps a session-disclaimer catalog into the `{ key, version }` records the
314
- * record-consents API expects, or an empty list when the user declined that
315
- * category.
316
- *
317
- * @param documents - Catalog documents for one consent category.
318
- * @param accepted - Whether the user accepted that category.
319
- * @returns Consent records, or `[]` when not accepted.
320
- */
321
- function consentRecordsFromCatalog(documents, accepted) {
322
- if (!accepted) {
323
- return [];
324
- }
325
- return documents
326
- .filter((document) => !document.consented)
327
- .map(({ key, version }) => ({ key, version }));
328
- }
329
- /**
330
- * Whether an accepted T&C2 category has no catalog documents. An empty list
331
- * would otherwise skip the POST and count as success.
332
- *
333
- * @param documents - Catalog documents for one consent category.
334
- * @param accepted - Whether the user accepted that category.
335
- * @returns `true` when the user accepted and the catalog is empty.
336
- */
337
- function isAcceptedCategoryEmpty(documents, accepted) {
338
- return accepted && documents.length === 0;
339
- }
340
- /**
341
- * Whether an accepted category is still missing consent after a 409 re-GET:
342
- * empty catalog or any document still unconsented.
343
- *
344
- * @param documents - Latest catalog documents for one consent category.
345
- * @param accepted - Whether the user accepted that category.
346
- * @returns `true` when accepted documents are not fully consented.
347
- */
348
- function acceptedCategoryStillMissing(documents, accepted) {
349
- return (accepted &&
350
- (documents.length === 0 ||
351
- documents.some((document) => !document.consented)));
352
- }
353
- /**
354
- * Vendors other than MoonPay skip Check/Auth frames and use the empty-shell
355
- * customer + consents path instead.
356
- *
357
- * @param vendor - The identity vendor for the current flow.
358
- * @returns `true` when the vendor uses the consents session path.
359
- */
360
- function usesConsentsFlow(vendor) {
361
- return vendor !== 'moonpay';
362
- }
363
- // === MESSENGER ===
364
- const MESSENGER_EXPOSED_METHODS = [
365
- 'initialize',
366
- 'loadDisclaimers',
367
- 'acceptTermsAndStartSession',
368
- 'createVendorCustomer',
369
- 'clearSavedTerms',
370
- 'handleFrameMessage',
371
- 'buildCheckFrameUrl',
372
- 'buildAuthFrameUrl',
373
- 'buildResetFrameUrl',
374
- 'checkKycRequired',
375
- 'getKycStatus',
376
- 'getCustomerIdentity',
377
- 'refreshKycStatus',
378
- 'startSumSub',
379
- 'getSessionStatus',
380
- 'reset',
381
- 'clearState',
382
- ];
383
- // === CONTROLLER DEFINITION ===
384
- /**
385
- * `KycController` orchestrates the vendor-backed KYC / identity-verification
386
- * flow (MoonPay identity + SumSub documents) behind a vendor-neutral, per
387
- * product surface used by ramps and card. It owns all state, HTTP
388
- * orchestration (via `KycService`), crypto, and the frame message protocol;
389
- * platform-specific presentation (WebView/iframe, SumSub SDK) is injected.
390
- */
391
- export class KycController extends BaseController {
392
- /**
393
- * Constructs a new {@link KycController}.
394
- *
395
- * @param options - The constructor options.
396
- * @param options.messenger - The messenger suited for this controller.
397
- * @param options.state - Partial initial state; merged over defaults.
398
- * @param options.sumsubLauncher - The platform SumSub launcher adapter.
399
- * @param options.sessionStatusPollIntervalMs - How often to poll the UKYC
400
- * session status after the SumSub SDK completes.
401
- * @param options.userStatusPollIntervalMs - How often to refresh the
402
- * user-keyed KYC status while it is still `pending`.
403
- */
404
- constructor({ messenger, state, sumsubLauncher, sessionStatusPollIntervalMs = DEFAULT_SESSION_STATUS_POLL_INTERVAL_MS, userStatusPollIntervalMs = DEFAULT_USER_STATUS_POLL_INTERVAL_MS, }) {
405
- super({
406
- messenger,
407
- metadata: kycControllerMetadata,
408
- name: controllerName,
409
- state: { ...getDefaultKycControllerState(), ...state },
410
- });
411
- _KycController_instances.add(this);
412
- _KycController_sumsubLauncher.set(this, void 0);
413
- /** MoonPay Check/Auth frame X25519 keypair (never persisted). */
414
- _KycController_moonpayFrameKeypair.set(this, null);
415
- /** Auth-frame client token, kept out of state. */
416
- _KycController_authClientToken.set(this, null);
417
- /**
418
- * Monotonic flow generation. Incremented by {@link reset} and
419
- * {@link clearState} so in-flight async work (e.g. the KYC-required check)
420
- * can detect that it was superseded and avoid writing stale results onto a
421
- * reset controller.
422
- */
423
- _KycController_generation.set(this, 0);
424
- /** Interval, in milliseconds, between session-status polls. */
425
- _KycController_sessionStatusPollIntervalMs.set(this, void 0);
426
- /** Handle for the scheduled next session-status poll, or `null`. */
427
- _KycController_pollTimer.set(this, null);
428
- /**
429
- * Monotonic polling token. Bumped by {@link #stopPolling} (called on reset, a
430
- * new sub-flow, and once a terminal status is reached) so an in-flight poll
431
- * `tick` can detect it was superseded and neither write state nor schedule a
432
- * follow-up. This closes the gap where clearing the timer alone would still
433
- * let an already-awaiting request finish and reschedule.
434
- */
435
- _KycController_pollToken.set(this, 0);
436
- /** Interval, in milliseconds, between user-keyed status polls. */
437
- _KycController_userStatusPollIntervalMs.set(this, void 0);
438
- /** Handle for the scheduled next user-status poll, or `null`. */
439
- _KycController_userStatusPollTimer.set(this, null);
440
- /**
441
- * Whether a user-status poll loop is currently active. Tracked separately
442
- * from {@link #userStatusPollTimer} because a scheduled tick clears the timer
443
- * handle before awaiting `fetchKycStatus`; relying on the handle alone would
444
- * let a concurrent {@link refreshKycStatus} start a second loop on the same
445
- * token during that in-flight window.
446
- */
447
- _KycController_userStatusPolling.set(this, false);
448
- /** Monotonic token for the user-status poll loop (see `#pollToken`). */
449
- _KycController_userStatusPollToken.set(this, 0);
450
- __classPrivateFieldSet(this, _KycController_sumsubLauncher, sumsubLauncher, "f");
451
- __classPrivateFieldSet(this, _KycController_sessionStatusPollIntervalMs, sessionStatusPollIntervalMs, "f");
452
- __classPrivateFieldSet(this, _KycController_userStatusPollIntervalMs, userStatusPollIntervalMs, "f");
453
- this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
454
- }
455
- /**
456
- * Resolves persisted terms + geolocation, and auto-creates a session when
457
- * terms are already accepted and an email is available.
458
- *
459
- * @param params - Optional parameters.
460
- * @param params.email - The account email to associate with the session.
461
- * @param params.product - The consuming feature the flow runs for. When
462
- * provided, the controller automatically runs the KYC-required check once
463
- * authentication completes (and chains into document verification when KYC
464
- * is required). When omitted, the flow stops at `form` and the consumer must
465
- * call `checkKycRequired` manually.
466
- * @param params.vendor - Identity vendor for this flow. Non-MoonPay vendors
467
- * skip Check/Auth frames and use the consents path. Defaults to `moonpay`.
468
- */
469
- async initialize(params) {
470
- // A repeat `initialize` while a session flow is already in progress must
471
- // not tear it down: creating a new vendor session clears the tokens and
472
- // forces `phase` back through `session`/`check`, breaking an in-flight
473
- // Check/Auth frame flow. Leave the active flow untouched and let the
474
- // consumer drive it (or call `reset` first to start over).
475
- const vendor = params?.vendor ?? 'moonpay';
476
- if (IN_PROGRESS_PHASES.includes(this.state.phase)) {
477
- if (vendor === 'moonpay' && !__classPrivateFieldGet(this, _KycController_moonpayFrameKeypair, "f")) {
478
- __classPrivateFieldSet(this, _KycController_moonpayFrameKeypair, generateKeyPair(), "f");
479
- }
480
- return;
481
- }
482
- if (vendor === 'moonpay') {
483
- __classPrivateFieldSet(this, _KycController_moonpayFrameKeypair, generateKeyPair(), "f");
484
- }
485
- else {
486
- __classPrivateFieldSet(this, _KycController_moonpayFrameKeypair, null, "f");
487
- }
488
- // `initialize` starts a fresh flow, so `activeProduct` is always reset to
489
- // this call's product (or `null`). Otherwise a prior run's product could
490
- // linger and cause `#continueAfterAuthentication` to auto-run the check /
491
- // sub-flow when the caller intended the manual (product-less) flow.
492
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
493
- if (params?.email) {
494
- state.email = params.email;
495
- }
496
- state.activeVendor = vendor;
497
- // MoonPay Check/Auth artifacts must not survive a switch to another
498
- // vendor: leftover `sessionToken` would keep `buildCheckFrameUrl` alive,
499
- // leftover `accessToken` / `#authClientToken` would keep Auth / KYC
500
- // calls bound to MoonPay, and leftover `moonpayCustomerId` would make
501
- // `getCustomerIdentity` report a MoonPay id under the wrong vendor.
502
- if (vendor !== 'moonpay') {
503
- __classPrivateFieldSet(this, _KycController_authClientToken, null, "f");
504
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearMoonPaySession).call(this, state);
505
- }
506
- state.activeProduct = params?.product ?? null;
507
- });
508
- // Capture the flow generation so a `reset()` landing while the async
509
- // geolocation / session steps below are in flight cannot write results
510
- // onto an idle controller.
511
- const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
512
- // Resolve country for display; non-blocking.
513
- try {
514
- const country = await this.messenger.call('KycService:getGeoCountry');
515
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
516
- state.geoCountry = country;
517
- });
518
- }
519
- catch {
520
- // Ignore; disclaimers loading will surface a country error if needed.
521
- }
522
- // A `reset()` / `clearState()` that landed while the geolocation request
523
- // was in flight supersedes this flow. Stop here rather than driving the
524
- // controller on into `terms` (or a new session): the steps below write
525
- // unconditionally, and `loadDisclaimers` captures the post-reset
526
- // generation, so its own guard would not catch this.
527
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
528
- return;
529
- }
530
- if (usesConsentsFlow(vendor) && this.state.email) {
531
- try {
532
- await this.messenger.call('KycService:createVendorCustomer', {
533
- vendor,
534
- email: this.state.email,
535
- });
536
- }
537
- catch (error) {
538
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
539
- return;
540
- }
541
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, `Vendor customer creation failed: ${String(error)}`);
542
- return;
543
- }
544
- }
545
- // Drop another vendor's persisted acceptance only after this flow has
546
- // committed (customer creation succeeded, or there was none to wait for).
547
- // Clearing earlier would permanently lose ramps/card terms if Iron
548
- // customer creation failed or a reset landed while it was in flight.
549
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
550
- return;
551
- }
552
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_dropTermsUnlessForVendor).call(this, vendor);
553
- const hasTerms = Boolean(this.state.termsAcceptedAt) &&
554
- this.state.acceptedDisclaimerIds.length > 0;
555
- if (hasTerms && this.state.email) {
556
- if (usesConsentsFlow(vendor)) {
557
- // Consents-path vendors require T&C2 flags; if they weren't persisted
558
- // (i.e. null from pre-migration state), require reacceptance.
559
- const sumsubTncSigned = this.state.sumsubTncAccepted;
560
- const idosTncSigned = this.state.idosTncAccepted;
561
- if (sumsubTncSigned === null || idosTncSigned === null) {
562
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
563
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearAcceptedTerms).call(this, state);
564
- state.phase = 'terms';
565
- });
566
- await this.loadDisclaimers();
567
- return;
568
- }
569
- await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_startConsentsSession).call(this, {
570
- sumsubTncSigned,
571
- idosTncSigned,
572
- credentialReusabilityConsentGiven: this.state.credentialReusabilityConsentGiven ?? false,
573
- });
574
- }
575
- else {
576
- await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_createSession).call(this);
577
- }
578
- return;
579
- }
580
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
581
- state.phase = 'terms';
582
- });
583
- await this.loadDisclaimers();
584
- }
585
- /**
586
- * Creates (or resumes) an empty-shell customer for the given identity
587
- * vendor. Exposed so a consumer can ensure the customer exists before
588
- * showing T&C screens independently of {@link initialize}.
589
- *
590
- * A call while a session flow is already in progress is a no-op — matching
591
- * {@link initialize} — so a vendor switch cannot leave Check/Auth frames
592
- * attached to the wrong vendor. Call {@link reset} first to start over.
593
- *
594
- * @param params - The parameters.
595
- * @param params.vendor - Identity vendor for the customer.
596
- * @param params.email - Email for the vendor customer.
597
- */
598
- async createVendorCustomer(params) {
599
- if (IN_PROGRESS_PHASES.includes(this.state.phase)) {
600
- return;
601
- }
602
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
603
- state.email = params.email;
604
- // MoonPay Check/Auth artifacts must not survive a switch to another
605
- // vendor — see `initialize`. Terms for another vendor are dropped only
606
- // after this request succeeds.
607
- state.activeVendor = params.vendor;
608
- if (params.vendor !== 'moonpay') {
609
- __classPrivateFieldSet(this, _KycController_authClientToken, null, "f");
610
- __classPrivateFieldSet(this, _KycController_moonpayFrameKeypair, null, "f");
611
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearMoonPaySession).call(this, state);
612
- }
613
- });
614
- const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
615
- try {
616
- await this.messenger.call('KycService:createVendorCustomer', {
617
- vendor: params.vendor,
618
- email: params.email,
619
- });
620
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
621
- return;
622
- }
623
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_dropTermsUnlessForVendor).call(this, params.vendor);
624
- }
625
- catch (error) {
626
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
627
- return;
628
- }
629
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, `Vendor customer creation failed: ${String(error)}`);
630
- }
631
- }
632
- /**
633
- * Loads the disclaimers for the resolved (or provided) country.
634
- *
635
- * @param params - Optional parameters.
636
- * @param params.country - ISO 3166-1 alpha-3 country code override.
637
- */
638
- async loadDisclaimers(params) {
639
- // Capture the flow generation so a `reset()` landing while the geo /
640
- // disclaimers requests are in flight cannot write results onto an idle
641
- // controller.
642
- const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
643
- try {
644
- const country = params?.country ??
645
- this.state.geoCountry ??
646
- (await this.messenger.call('KycService:getGeoCountry'));
647
- if (country !== this.state.geoCountry) {
648
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
649
- state.geoCountry = country;
650
- });
651
- }
652
- const disclaimers = await this.messenger.call('KycService:fetchVendorDisclaimers', {
653
- vendor: this.state.activeVendor,
654
- country,
655
- });
656
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
657
- state.disclaimers = disclaimers;
658
- state.disclaimersError = null;
659
- });
660
- }
661
- catch (error) {
662
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
663
- state.disclaimersError = `Failed to load disclaimers: ${String(error)}`;
664
- });
665
- }
666
- }
667
- /**
668
- * Captures terms acceptance for the currently loaded disclaimers and creates
669
- * a session.
670
- *
671
- * @param params - The parameters.
672
- * @param params.email - The account email to associate with the session.
673
- * @param params.product - The consuming feature the flow runs for. See
674
- * {@link initialize} for how the product drives the automatic post
675
- * authentication continuation.
676
- * @param params.sumsubTncSigned - Whether Sumsub T&C were accepted (T&C2).
677
- * Required for every vendor so callers explicitly declare acceptance.
678
- * @param params.idosTncSigned - Whether idOS T&C were accepted (T&C2).
679
- * Required for every vendor so callers explicitly declare acceptance.
680
- * @param params.credentialReusabilityConsentGiven - Whether the customer
681
- * consented to reuse existing idOS credentials. Used when recording
682
- * session-scoped disclaimers on the consents path. Defaults to `false`.
683
- */
684
- async acceptTermsAndStartSession(params) {
685
- const sumsubTncSigned = params?.sumsubTncSigned;
686
- const idosTncSigned = params?.idosTncSigned;
687
- if (typeof sumsubTncSigned !== 'boolean' ||
688
- typeof idosTncSigned !== 'boolean') {
689
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing T&C2 acceptance flags.');
690
- return;
691
- }
692
- const credentialReusabilityConsentGiven = params.credentialReusabilityConsentGiven ?? false;
693
- const termsAcceptedAt = new Date().toISOString();
694
- const disclaimerIds = this.state.disclaimers.map((disclaimer) => disclaimer.id);
695
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
696
- if (params.email) {
697
- state.email = params.email;
698
- }
699
- if (params.product) {
700
- state.activeProduct = params.product;
701
- }
702
- state.termsAcceptedAt = termsAcceptedAt;
703
- state.acceptedDisclaimerIds = disclaimerIds;
704
- state.termsAcceptedVendor = state.activeVendor;
705
- state.sumsubTncAccepted = sumsubTncSigned;
706
- state.idosTncAccepted = idosTncSigned;
707
- state.credentialReusabilityConsentGiven =
708
- credentialReusabilityConsentGiven;
709
- });
710
- if (usesConsentsFlow(this.state.activeVendor)) {
711
- await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_startConsentsSession).call(this, {
712
- sumsubTncSigned,
713
- idosTncSigned,
714
- credentialReusabilityConsentGiven,
715
- });
716
- return;
717
- }
718
- await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_createSession).call(this);
719
- }
720
- /**
721
- * Clears the persisted terms acceptance.
722
- */
723
- clearSavedTerms() {
724
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
725
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearAcceptedTerms).call(this, state);
726
- });
727
- }
728
- /**
729
- * Handles a message posted by a Check/Auth frame and advances the flow.
730
- *
731
- * The transport-agnostic caller (WebView on mobile, iframe on web) forwards
732
- * the raw message and injects the returned `reply` back into the frame.
733
- *
734
- * @param params - The parameters.
735
- * @param params.message - The raw message posted by the frame.
736
- * @returns An object whose optional `reply` should be posted back.
737
- */
738
- async handleFrameMessage(params) {
739
- const payload = params.message;
740
- if (!payload) {
741
- return {};
742
- }
743
- if (payload.kind === 'handshake') {
744
- const channelId = payload.meta?.channelId;
745
- return { reply: { version: 2, meta: { channelId }, kind: 'ack' } };
746
- }
747
- if (payload.kind !== 'complete') {
748
- return {};
749
- }
750
- const channelId = payload.meta?.channelId;
751
- // Only honor a Check/Auth `complete` for the MoonPay frame the flow is
752
- // currently waiting on. This drops stale or duplicate messages — e.g. a
753
- // late post after `reset()` (phase `idle`), after the flow already
754
- // advanced past this frame, or after a vendor switch — so they cannot
755
- // resurrect tokens, rewind `phase`, or recapture `moonpayCustomerId` on a
756
- // controller that has moved on. Frame messages are external input and,
757
- // unlike the async steps, are not covered by the `#generation` guard.
758
- let expectedPhase = null;
759
- if (channelId === CHANNEL_CHECK) {
760
- expectedPhase = 'check';
761
- }
762
- else if (channelId === CHANNEL_AUTH) {
763
- expectedPhase = 'auth';
764
- }
765
- if (!expectedPhase ||
766
- this.state.phase !== expectedPhase ||
767
- this.state.activeVendor !== 'moonpay') {
768
- return {};
769
- }
770
- const status = payload.payload?.status;
771
- const credsEnvelope = payload.payload?.credentials;
772
- const customerId = payload.payload?.customer?.id ?? null;
773
- if (customerId) {
774
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
775
- state.moonpayCustomerId = customerId;
776
- });
777
- }
778
- if (!status) {
779
- return {};
780
- }
781
- let accessToken;
782
- let clientToken;
783
- if (credsEnvelope && __classPrivateFieldGet(this, _KycController_moonpayFrameKeypair, "f")) {
784
- try {
785
- const { credentials } = decryptCredentials(credsEnvelope, __classPrivateFieldGet(this, _KycController_moonpayFrameKeypair, "f").privateKey);
786
- accessToken = credentials.accessToken;
787
- clientToken = credentials.clientToken;
788
- }
789
- catch (error) {
790
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, `Failed to decrypt frame credentials: ${String(error)}`);
791
- return {};
792
- }
793
- }
794
- if (channelId === CHANNEL_CHECK) {
795
- await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_handleCheckOutcome).call(this, status, accessToken, clientToken);
796
- return {};
797
- }
798
- // channelId === CHANNEL_AUTH, guaranteed by the expectedPhase guard above.
799
- await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_handleAuthOutcome).call(this, status, accessToken);
800
- return {};
801
- }
802
- /**
803
- * Builds the Check-frame URL, or `null` when no session exists yet.
804
- *
805
- * @returns The Check-frame URL or `null`.
806
- */
807
- buildCheckFrameUrl() {
808
- if (this.state.activeVendor !== 'moonpay' ||
809
- !this.state.sessionToken ||
810
- !__classPrivateFieldGet(this, _KycController_moonpayFrameKeypair, "f")) {
811
- return null;
812
- }
813
- const url = new URL(`${FRAMES_BASE_URL}/check-connection`);
814
- url.searchParams.set('sessionToken', this.state.sessionToken);
815
- url.searchParams.set('publicKey', __classPrivateFieldGet(this, _KycController_moonpayFrameKeypair, "f").publicKeyHex);
816
- url.searchParams.set('channelId', CHANNEL_CHECK);
817
- url.searchParams.set('skipKyc', 'true');
818
- return url.toString();
819
- }
820
- /**
821
- * Builds the Auth-frame URL, or `null` when no client token is available.
822
- *
823
- * @returns The Auth-frame URL or `null`.
824
- */
825
- buildAuthFrameUrl() {
826
- if (this.state.activeVendor !== 'moonpay' ||
827
- !__classPrivateFieldGet(this, _KycController_authClientToken, "f") ||
828
- !__classPrivateFieldGet(this, _KycController_moonpayFrameKeypair, "f")) {
829
- return null;
830
- }
831
- const url = new URL(`${FRAMES_BASE_URL}/auth`);
832
- url.searchParams.set('clientToken', __classPrivateFieldGet(this, _KycController_authClientToken, "f"));
833
- url.searchParams.set('publicKey', __classPrivateFieldGet(this, _KycController_moonpayFrameKeypair, "f").publicKeyHex);
834
- url.searchParams.set('channelId', CHANNEL_AUTH);
835
- return url.toString();
836
- }
837
- /**
838
- * Builds the Reset-frame URL.
839
- *
840
- * @returns The Reset-frame URL.
841
- */
842
- buildResetFrameUrl() {
843
- const url = new URL(`${FRAMES_BASE_URL}/reset`);
844
- url.searchParams.set('channelId', CHANNEL_RESET);
845
- return url.toString();
846
- }
847
- /**
848
- * Checks whether KYC is required for a product and caches the result.
849
- *
850
- * @param params - The parameters.
851
- * @param params.product - The consuming feature.
852
- * @param params.country - Optional alpha-3 country override.
853
- * @returns Whether KYC is required.
854
- */
855
- async checkKycRequired(params) {
856
- const { accessToken } = this.state;
857
- if (!accessToken) {
858
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing accessToken — repeat the authentication step.');
859
- return false;
860
- }
861
- const country = params.country ?? this.state.geoCountry;
862
- if (!country) {
863
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing country for KYC-required check.');
864
- return false;
865
- }
866
- // Capture the flow generation so we can detect a `reset()` that happens
867
- // while the HTTP call is in flight and avoid writing stale results.
868
- const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
869
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
870
- state.phase = 'submit';
871
- state.statusMessage = 'Checking KYC status...';
872
- });
873
- try {
874
- const { kycRequired } = await this.messenger.call('KycService:checkKycRequired', { accessToken, country, capabilities: [{ product: params.product }] });
875
- // The flow was reset while the check was in flight; discard the result
876
- // rather than resurrecting a done/cached state on an idle controller.
877
- const applied = __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
878
- state.kycRequiredByProduct[params.product] = kycRequired;
879
- state.lastCheckedAt = new Date().toISOString();
880
- state.phase = 'done';
881
- state.statusMessage = 'KYC check complete.';
882
- });
883
- if (!applied) {
884
- return false;
885
- }
886
- return kycRequired;
887
- }
888
- catch (error) {
889
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
890
- return false;
891
- }
892
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, `KYC check failed: ${String(error)}`);
893
- return false;
894
- }
895
- }
896
- /**
897
- * Reads the cached "is KYC required" result for a product.
898
- *
899
- * @param params - The parameters.
900
- * @param params.product - The consuming feature.
901
- * @returns The cached value, or `undefined` if not yet checked.
902
- */
903
- getKycStatus(params) {
904
- return this.state.kycRequiredByProduct[params.product];
905
- }
906
- /**
907
- * Returns the vendor-scoped identity for the currently authenticated
908
- * customer, or `null` when the flow has not yet captured a vendor customer
909
- * id (before authentication or after {@link reset}), or when a MoonPay id
910
- * is present under a different `activeVendor`.
911
- *
912
- * Exposed so consumers (e.g. ramps autoramp creation) can attach the vendor
913
- * customer id to downstream calls without reading the full KYC state, which
914
- * also holds session/access tokens. The id is session-scoped and never
915
- * persisted.
916
- *
917
- * @returns The current {@link KycCustomerIdentity}, or `null`.
918
- */
919
- getCustomerIdentity() {
920
- const { moonpayCustomerId, activeVendor } = this.state;
921
- // `moonpayCustomerId` is issued only by MoonPay Check/Auth frames. Never
922
- // pair it with another vendor, even if a switch left the fields out of
923
- // sync, so consumers cannot attach a MoonPay id to an Iron (or other)
924
- // downstream call.
925
- if (!moonpayCustomerId || activeVendor !== 'moonpay') {
926
- return null;
927
- }
928
- return { vendor: 'moonpay', id: moonpayCustomerId };
929
- }
930
- /**
931
- * Runs the SumSub document-verification sub-flow end to end:
932
- *
933
- * 1. creates a UKYC session, receiving per-secret encryption schemas;
934
- * 2. verifies the `encryptionDataKey` schema's `jwtChain` against the
935
- * idOS enclave JWKS and the `ukycCapabilityToken` schema's `jwtChain` against
936
- * the idOS relay JWKS, then confirms each attested session server public
937
- * key;
938
- * 3. derives the `data_encryption_key` from the wallet's UKYC
939
- * `local_user_secret` and wraps it for the session server;
940
- * 4. mints a client-signed, read-only `ukyc_capability_token`, wraps it the
941
- * same way as the encryption key, and submits both via authorizations;
942
- * 5. fetches the SumSub applicant access token; and
943
- * 6. presents the SDK via the injected launcher.
944
- *
945
- * If a UKYC session already exists (the consents path creates it before
946
- * recording session disclaimers), steps 1–4 are skipped.
947
- *
948
- * If authorizations report the applicant is already approved on the relay
949
- * while the vendor is still finalizing (`kycStatus: approved`,
950
- * `finalStatus: pending`), the sub-flow stops at step 4 with a
951
- * `vendorProcessing` status and a message rather than launching the SDK.
952
- *
953
- * @param params - Optional parameters.
954
- * @param params.locale - BCP-47 locale for the SDK UI.
955
- * @param params.debug - Enables SDK debug logging.
956
- * @returns The SDK result.
957
- */
958
- async startSumSub(params) {
959
- // A new sub-flow supersedes any polling still running from a prior run.
960
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopPolling).call(this);
961
- if (!__classPrivateFieldGet(this, _KycController_sumsubLauncher, "f").isAvailable()) {
962
- const error = 'SumSub SDK is not available in this runtime.';
963
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
964
- state.sumsub.status = 'failed';
965
- state.sumsub.result = { error };
966
- });
967
- throw new Error(error);
968
- }
969
- // Capture the flow generation so each async step can detect a `reset()`
970
- // that lands mid-flight and avoid writing stale sub-flow state (or, worse,
971
- // presenting the SDK) on a controller that is now idle.
972
- const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
973
- try {
974
- if (!this.state.sumsub.sessionId) {
975
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
976
- state.sumsub.status = 'creatingSession';
977
- state.sumsub.result = null;
978
- state.sumsub.sessionStatus = null;
979
- });
980
- const created = await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_createUkycSession).call(this, generation);
981
- if (!created) {
982
- return {};
983
- }
984
- // A user who already finished the journey can return to a session the
985
- // relay has already approved (`kycStatus`) while the vendor is still
986
- // finalizing its own decision (`finalStatus`). There is nothing left to
987
- // verify, so stop here and surface a message rather than launching the
988
- // SDK again.
989
- if (created.vendorProcessing) {
990
- return {
991
- kycStatus: created.kycStatus,
992
- finalStatus: created.finalStatus,
993
- };
994
- }
995
- }
996
- // Empty string is a valid "no id to poll" session id used by tests and
997
- // must not be coalesced away as missing.
998
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
999
- const sessionId = this.state.sumsub.sessionId || '';
1000
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1001
- state.sumsub.status = 'fetchingToken';
1002
- state.sumsub.sessionId = sessionId;
1003
- });
1004
- const { applicantAccessToken } = await this.messenger.call('KycService:createJourney', sessionId);
1005
- // A reset() may have landed while the session/token was being prepared.
1006
- // Gate the `launching` write and the decision to open the SDK behind a
1007
- // single generation check: `#updateIfCurrent` only writes when still
1008
- // current and reports whether it did. Since there is no `await` between
1009
- // this check and `launch` below, a successful result guarantees the SDK
1010
- // is never presented on a flow that a concurrent reset() returned to idle.
1011
- const stillCurrent = __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1012
- state.sumsub.status = 'launching';
1013
- state.sumsub.applicantAccessToken = applicantAccessToken;
1014
- });
1015
- if (!stillCurrent) {
1016
- return {};
1017
- }
1018
- // Track whether the SDK ever reported a successful completion. A resolved
1019
- // `launch` alone does not imply success — the applicant may have
1020
- // abandoned the flow or the SDK may have reported a non-success outcome.
1021
- let reachedCompletion = false;
1022
- const result = await __classPrivateFieldGet(this, _KycController_sumsubLauncher, "f").launch({
1023
- applicantAccessToken,
1024
- onTokenExpiration: async () => {
1025
- // A reset() may have superseded this flow while the SDK stayed open.
1026
- // Refuse to refresh against the now-stale UKYC session rather than
1027
- // silently keeping an orphaned SDK alive.
1028
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1029
- throw new Error('KYC flow was reset; SumSub session is no longer active.');
1030
- }
1031
- const refreshed = await this.messenger.call('KycService:createJourney', sessionId);
1032
- return refreshed.applicantAccessToken;
1033
- },
1034
- onStatusChange: (_prev, next) => {
1035
- if (next === SUMSUB_COMPLETED_STATUS) {
1036
- reachedCompletion = true;
1037
- }
1038
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1039
- state.sumsub.status =
1040
- next === SUMSUB_COMPLETED_STATUS ? 'complete' : 'inProgress';
1041
- });
1042
- },
1043
- locale: params?.locale ?? 'en',
1044
- debug: params?.debug ?? false,
1045
- });
1046
- // A resolved `launch` alone is not the final outcome: only a SDK-reported
1047
- // completion is worth polling for a verification decision. Anything else
1048
- // (abandonment, non-success) is `failed` and must not be polled.
1049
- const applied = __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1050
- state.sumsub.status = reachedCompletion ? 'polling' : 'failed';
1051
- state.sumsub.result = result;
1052
- });
1053
- // Once the SDK completes, the authoritative verification decision comes
1054
- // from the UKYC backend, not the SDK result. Poll the session status
1055
- // until it reaches a terminal decision. Guard on `applied` so a `reset()`
1056
- // that landed during `launch` cannot start polling on an idle flow.
1057
- if (applied && reachedCompletion) {
1058
- if (sessionId) {
1059
- await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_startSessionStatusPolling).call(this, sessionId);
1060
- }
1061
- else {
1062
- // No session id to poll against; fall back to treating the SDK
1063
- // completion as the final outcome.
1064
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1065
- state.sumsub.status = 'complete';
1066
- });
1067
- }
1068
- }
1069
- return result;
1070
- }
1071
- catch (error) {
1072
- // Applicant already finished KYC — treat as completed for Money toast.
1073
- if (isSessionAlreadyCompletedError(error)) {
1074
- // A reset() may have landed while `launch` was in flight; forcing
1075
- // `completed` (and publishing `statusChanged`) on an idle controller
1076
- // would resurrect a flow the consumer already tore down.
1077
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1078
- return { alreadyCompleted: true };
1079
- }
1080
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUserStatus).call(this, {
1081
- status: 'completed',
1082
- sumsubSessionId: null,
1083
- errorCode: null,
1084
- });
1085
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1086
- state.sumsub.status = 'complete';
1087
- state.sumsub.result = { alreadyCompleted: true };
1088
- state.statusMessage = 'KYC already completed.';
1089
- state.phase = 'done';
1090
- state.error = null;
1091
- });
1092
- return { alreadyCompleted: true };
1093
- }
1094
- const result = { error: String(error) };
1095
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1096
- state.sumsub.status = 'failed';
1097
- state.sumsub.result = result;
1098
- });
1099
- return result;
1100
- }
1101
- }
1102
- /**
1103
- * Refreshes the user-keyed simplified KYC status from `GET /kyc/status`,
1104
- * stores it on state, publishes {@link KycControllerStatusChangedEvent}, and
1105
- * schedules short-interval polling while the status is `pending`.
1106
- *
1107
- * @returns The latest status payload.
1108
- */
1109
- async refreshKycStatus() {
1110
- const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
1111
- const payload = await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fetchAndApplyUserStatus).call(this);
1112
- // A `reset()` landing while the request was in flight already stopped
1113
- // polling and left the flow idle, and the payload above is the pre-reset
1114
- // cached status. Starting a loop from it would poll — and publish
1115
- // `statusChanged` — on a torn-down flow.
1116
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1117
- return payload;
1118
- }
1119
- if (payload.status === 'pending') {
1120
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_ensureUserStatusPolling).call(this);
1121
- }
1122
- else {
1123
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopUserStatusPolling).call(this);
1124
- }
1125
- return payload;
1126
- }
1127
- /**
1128
- * Fetches the current UKYC session status for the active sub-flow and records
1129
- * it on state. Useful for a one-off refresh outside the automatic polling
1130
- * loop that {@link startSumSub} runs.
1131
- *
1132
- * @returns The fetched session status.
1133
- * @throws If there is no active SumSub session to query.
1134
- */
1135
- async getSessionStatus() {
1136
- const { sessionId } = this.state.sumsub;
1137
- if (!sessionId) {
1138
- throw new Error('Cannot fetch session status: no active SumSub session.');
1139
- }
1140
- // Capture the flow generation so a `reset()` landing while the request is
1141
- // in flight cannot write the result onto an idle controller.
1142
- const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
1143
- const sessionStatus = await this.messenger.call('KycService:getSessionStatus', { sessionId });
1144
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1145
- state.sumsub.sessionStatus = sessionStatus;
1146
- });
1147
- return sessionStatus;
1148
- }
1149
- /**
1150
- * Resets the flow to idle, clearing session tokens and sub-flow state while
1151
- * preserving persisted terms acceptance and the per-product cache.
1152
- */
1153
- reset() {
1154
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_cancelPendingSession).call(this);
1155
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1156
- state.phase = 'idle';
1157
- state.statusMessage = '';
1158
- state.error = null;
1159
- state.disclaimers = [];
1160
- state.disclaimersError = null;
1161
- state.sessionDisclaimers = null;
1162
- state.credentialReusabilityConsentGiven = null;
1163
- state.sessionToken = null;
1164
- state.accessToken = null;
1165
- state.moonpayCustomerId = null;
1166
- state.activeVendor = 'moonpay';
1167
- state.activeProduct = null;
1168
- state.sumsub = {
1169
- status: 'idle',
1170
- result: null,
1171
- sessionId: null,
1172
- applicantAccessToken: null,
1173
- sessionStatus: null,
1174
- };
1175
- });
1176
- }
1177
- /**
1178
- * Restores the controller to its default state, discarding everything
1179
- * {@link reset} deliberately keeps: the session email, the persisted terms
1180
- * acceptance, the per-product KYC-required cache and the user-keyed status.
1181
- *
1182
- * Intended for a full wallet reset, where no trace of the previous
1183
- * customer may survive into the next wallet.
1184
- */
1185
- clearState() {
1186
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_cancelPendingSession).call(this);
1187
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1188
- Object.assign(state, getDefaultKycControllerState());
1189
- });
1190
- }
1191
- }
1192
- _KycController_sumsubLauncher = new WeakMap(), _KycController_moonpayFrameKeypair = new WeakMap(), _KycController_authClientToken = new WeakMap(), _KycController_generation = new WeakMap(), _KycController_sessionStatusPollIntervalMs = new WeakMap(), _KycController_pollTimer = new WeakMap(), _KycController_pollToken = new WeakMap(), _KycController_userStatusPollIntervalMs = new WeakMap(), _KycController_userStatusPollTimer = new WeakMap(), _KycController_userStatusPolling = new WeakMap(), _KycController_userStatusPollToken = new WeakMap(), _KycController_instances = new WeakSet(), _KycController_localUserSecretStore = function _KycController_localUserSecretStore() {
1193
- return {
1194
- get: async (path, entropySourceId) => this.messenger.call('UserStorageController:performGetStorage', path, entropySourceId),
1195
- set: async (path, value, entropySourceId) => this.messenger.call('UserStorageController:performSetStorage', path, value, entropySourceId),
1196
- };
1197
- }, _KycController_startConsentsSession =
1198
- /**
1199
- * Consents-path vendors: record vendor T&Cs, create a UKYC session,
1200
- * record session-scoped idOS / KYC-provider disclaimers, then launch
1201
- * SumSub — skipping MoonPay Check/Auth frames.
1202
- *
1203
- * @param consents - T&C2 flags mapped onto the session disclaimer catalog.
1204
- * @param consents.sumsubTncSigned - Whether Sumsub T&C were accepted.
1205
- * @param consents.idosTncSigned - Whether idOS T&C were accepted.
1206
- * @param consents.credentialReusabilityConsentGiven - Whether credential
1207
- * reuse was accepted.
1208
- */
1209
- async function _KycController_startConsentsSession(consents) {
1210
- const { email, acceptedDisclaimerIds } = this.state;
1211
- if (!email) {
1212
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing email for consents session.');
1213
- return;
1214
- }
1215
- if (acceptedDisclaimerIds.length === 0) {
1216
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing disclaimer acceptance.');
1217
- return;
1218
- }
1219
- const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
1220
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1221
- state.error = null;
1222
- state.phase = 'session';
1223
- state.statusMessage = 'Submitting consents...';
1224
- state.sumsub.status = 'creatingSession';
1225
- state.sumsub.result = null;
1226
- state.sumsub.sessionStatus = null;
1227
- // Consents-path vendors have no MoonPay session/access tokens.
1228
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearMoonPaySession).call(this, state);
1229
- });
1230
- try {
1231
- await this.messenger.call('KycService:submitVendorDisclaimers', {
1232
- vendor: this.state.activeVendor,
1233
- disclaimerIds: acceptedDisclaimerIds,
1234
- });
1235
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1236
- return;
1237
- }
1238
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1239
- state.statusMessage = 'Creating session...';
1240
- });
1241
- const created = await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_createUkycSession).call(this, generation);
1242
- if (!created || __classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1243
- return;
1244
- }
1245
- await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_recordSessionDisclaimers).call(this, created.sessionId, consents, generation);
1246
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1247
- return;
1248
- }
1249
- if (created.vendorProcessing) {
1250
- try {
1251
- await this.refreshKycStatus();
1252
- }
1253
- catch (statusError) {
1254
- controllerLog('KYC status refresh failed:', statusError);
1255
- }
1256
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1257
- state.phase = 'done';
1258
- state.statusMessage = VENDOR_PROCESSING_MESSAGE;
1259
- });
1260
- return;
1261
- }
1262
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1263
- state.phase = 'submit';
1264
- state.statusMessage = 'Starting document verification...';
1265
- });
1266
- const sumsubResult = await this.startSumSub();
1267
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1268
- return;
1269
- }
1270
- // `startSumSub` records `sumsub.status = 'failed'` for thrown steps,
1271
- // an SDK close without Completed, *and* a terminal UKYC rejection
1272
- // after the SDK reported Completed. Only rewind when there is no
1273
- // session-status decision yet (abandonment / thrown step). A
1274
- // Completed-then-rejected poll writes `sessionStatus` and is a
1275
- // finished flow: refresh user status and land on `done`.
1276
- if (this.state.sumsub.status === 'failed' &&
1277
- this.state.sumsub.sessionStatus === null) {
1278
- const sumsubError = sumsubResult?.error;
1279
- throw new Error(typeof sumsubError === 'string'
1280
- ? sumsubError
1281
- : 'SumSub verification did not complete.');
1282
- }
1283
- // After SumSub, refresh user-keyed status for the Money toast and start
1284
- // polling while still pending. Soft-fail: toast refresh must not rewind
1285
- // the consent / SumSub outcome.
1286
- try {
1287
- await this.refreshKycStatus();
1288
- }
1289
- catch (statusError) {
1290
- controllerLog('KYC status refresh failed:', statusError);
1291
- }
1292
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1293
- if (state.phase !== 'error' && state.phase !== 'done') {
1294
- state.phase = 'done';
1295
- state.statusMessage = 'KYC submitted.';
1296
- }
1297
- });
1298
- }
1299
- catch (error) {
1300
- if (isSessionAlreadyCompletedError(error)) {
1301
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1302
- return;
1303
- }
1304
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUserStatus).call(this, {
1305
- status: 'completed',
1306
- sumsubSessionId: null,
1307
- errorCode: null,
1308
- });
1309
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1310
- state.sumsub.status = 'complete';
1311
- state.sumsub.result = { alreadyCompleted: true };
1312
- state.statusMessage = 'KYC already completed.';
1313
- state.phase = 'done';
1314
- state.error = null;
1315
- });
1316
- return;
1317
- }
1318
- controllerLog('Consents session failed:', error);
1319
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1320
- return;
1321
- }
1322
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1323
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearAcceptedTerms).call(this, state);
1324
- state.activeProduct = null;
1325
- state.sessionDisclaimers = null;
1326
- // Session create ran before recording disclaimers. Drop the leftover
1327
- // UKYC session so a later `startSumSub` cannot skip consent recording.
1328
- state.sumsub = { ...getDefaultKycControllerState().sumsub };
1329
- state.error = `Consents session failed: ${String(error)}`;
1330
- state.statusMessage =
1331
- 'Consent / verification failed — accept the terms to try again.';
1332
- state.phase = 'terms';
1333
- });
1334
- await this.loadDisclaimers();
1335
- }
1336
- }, _KycController_recordSessionDisclaimers =
1337
- /**
1338
- * Fetches the session-scoped disclaimer catalog and records consents
1339
- * derived from the T&C2 flags. Already-consented catalog rows are omitted
1340
- * from the POST. A 409 is re-checked with a GET: continue only when every
1341
- * accepted document is now consented, otherwise fail closed.
1342
- *
1343
- * @param sessionId - The UKYC session id.
1344
- * @param consents - T&C2 flags mapped onto catalog documents.
1345
- * @param consents.sumsubTncSigned - Whether Sumsub T&C were accepted.
1346
- * @param consents.idosTncSigned - Whether idOS T&C were accepted.
1347
- * @param consents.credentialReusabilityConsentGiven - Whether credential
1348
- * reuse was accepted.
1349
- * @param generation - Flow generation captured by the caller.
1350
- */
1351
- async function _KycController_recordSessionDisclaimers(sessionId, consents, generation) {
1352
- const catalog = await this.messenger.call('KycService:fetchSessionDisclaimers', { sessionId });
1353
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1354
- return;
1355
- }
1356
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1357
- state.sessionDisclaimers = catalog;
1358
- state.statusMessage = 'Submitting consents...';
1359
- });
1360
- if (isAcceptedCategoryEmpty(catalog.idOS, consents.idosTncSigned) ||
1361
- isAcceptedCategoryEmpty(catalog.kycProvider, consents.sumsubTncSigned)) {
1362
- throw new Error('Session disclaimer catalog is missing documents for an accepted category.');
1363
- }
1364
- const idOS = consentRecordsFromCatalog(catalog.idOS, consents.idosTncSigned);
1365
- const kycProvider = consentRecordsFromCatalog(catalog.kycProvider, consents.sumsubTncSigned);
1366
- const reuseUnchanged = catalog.credentialReusabilityConsentGiven ===
1367
- consents.credentialReusabilityConsentGiven;
1368
- if (idOS.length === 0 && kycProvider.length === 0 && reuseUnchanged) {
1369
- return;
1370
- }
1371
- try {
1372
- const recorded = await this.messenger.call('KycService:submitSessionDisclaimers', {
1373
- sessionId,
1374
- idOS,
1375
- kycProvider,
1376
- credentialReusabilityConsentGiven: consents.credentialReusabilityConsentGiven,
1377
- });
1378
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1379
- state.sessionDisclaimers = recorded;
1380
- });
1381
- }
1382
- catch (error) {
1383
- if (!isConsentConflictError(error)) {
1384
- throw error;
1385
- }
1386
- // 409 means some document version was already recorded. Re-fetch and
1387
- // continue only when every document the user accepted is now consented;
1388
- // otherwise fail closed so a version bump cannot skip new docs.
1389
- const latest = await this.messenger.call('KycService:fetchSessionDisclaimers', { sessionId });
1390
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1391
- return;
1392
- }
1393
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1394
- state.sessionDisclaimers = latest;
1395
- });
1396
- const stillMissingIdos = acceptedCategoryStillMissing(latest.idOS, consents.idosTncSigned);
1397
- const stillMissingProvider = acceptedCategoryStillMissing(latest.kycProvider, consents.sumsubTncSigned);
1398
- const stillMissingReuse = consents.credentialReusabilityConsentGiven &&
1399
- !latest.credentialReusabilityConsentGiven;
1400
- if (stillMissingIdos || stillMissingProvider || stillMissingReuse) {
1401
- throw error;
1402
- }
1403
- }
1404
- }, _KycController_createSession =
1405
- /**
1406
- * Creates a vendor session from the currently stored terms + email.
1407
- */
1408
- async function _KycController_createSession() {
1409
- const { email, termsAcceptedAt, acceptedDisclaimerIds } = this.state;
1410
- if (!email) {
1411
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing email for session creation.');
1412
- return;
1413
- }
1414
- if (!termsAcceptedAt || acceptedDisclaimerIds.length === 0) {
1415
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing terms acceptance for session creation.');
1416
- return;
1417
- }
1418
- // A new session invalidates any authentication carried over from a prior
1419
- // session. Clear the stale session token, access token, and auth-frame
1420
- // client token so `buildCheckFrameUrl` cannot return a URL bound to an old
1421
- // (or, on failure, invalid) session token, `buildAuthFrameUrl` cannot
1422
- // return a URL tied to an old client token, and `checkKycRequired` cannot
1423
- // run with an access token from an earlier authentication. The Check/Auth
1424
- // frames re-populate these for the new session. Because `sessionToken` is
1425
- // cleared here and only re-set on success, a failed creation leaves it
1426
- // `null` rather than resurrecting the previous session.
1427
- // Capture the flow generation so a `reset()` landing while the create
1428
- // request is in flight cannot resurrect a session (success) or overwrite
1429
- // the now-idle controller (failure). The synchronous update below runs
1430
- // before any `await`, so it needs no guard.
1431
- const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
1432
- __classPrivateFieldSet(this, _KycController_authClientToken, null, "f");
1433
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1434
- state.error = null;
1435
- state.phase = 'session';
1436
- state.statusMessage = 'Creating session...';
1437
- state.sessionToken = null;
1438
- state.accessToken = null;
1439
- });
1440
- try {
1441
- const { sessionToken } = await this.messenger.call('KycService:createSession', { email, termsAcceptedAt, disclaimerIds: acceptedDisclaimerIds });
1442
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1443
- state.sessionToken = sessionToken;
1444
- state.phase = 'check';
1445
- state.statusMessage = 'Authenticating via Check frame...';
1446
- });
1447
- }
1448
- catch (error) {
1449
- controllerLog('Session creation failed:', error);
1450
- // A reset() superseded this flow while the request was in flight; leave
1451
- // the idle controller alone rather than forcing it back to `terms`.
1452
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1453
- return;
1454
- }
1455
- // Invalidate the stored acceptance so the customer can retry. Also clear
1456
- // `activeProduct` so a later `acceptTermsAndStartSession` that omits a
1457
- // product cannot auto-run the KYC check / SumSub chain for this failed
1458
- // flow's product — matching how `initialize` starts from a clean product.
1459
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1460
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearAcceptedTerms).call(this, state);
1461
- state.activeProduct = null;
1462
- state.error = `Session creation failed: ${String(error)}`;
1463
- state.statusMessage =
1464
- 'Session creation failed — accept the terms to try again.';
1465
- state.phase = 'terms';
1466
- });
1467
- await this.loadDisclaimers();
1468
- }
1469
- }, _KycController_clearAcceptedTerms = function _KycController_clearAcceptedTerms(state) {
1470
- state.termsAcceptedAt = null;
1471
- state.acceptedDisclaimerIds = [];
1472
- state.termsAcceptedVendor = null;
1473
- state.sumsubTncAccepted = null;
1474
- state.idosTncAccepted = null;
1475
- state.credentialReusabilityConsentGiven = null;
1476
- }, _KycController_clearMoonPaySession = function _KycController_clearMoonPaySession(state) {
1477
- state.moonpayCustomerId = null;
1478
- state.sessionToken = null;
1479
- state.accessToken = null;
1480
- }, _KycController_dropTermsUnlessForVendor = function _KycController_dropTermsUnlessForVendor(vendor) {
1481
- if (__classPrivateFieldGet(this, _KycController_instances, "m", _KycController_hasTermsForVendor).call(this, vendor)) {
1482
- return;
1483
- }
1484
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1485
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearAcceptedTerms).call(this, state);
1486
- });
1487
- }, _KycController_hasTermsForVendor = function _KycController_hasTermsForVendor(vendor) {
1488
- if (this.state.termsAcceptedVendor === null) {
1489
- return false;
1490
- }
1491
- return this.state.termsAcceptedVendor === vendor;
1492
- }, _KycController_handleCheckOutcome =
1493
- /**
1494
- * Applies a Check-frame outcome.
1495
- *
1496
- * @param status - The frame status.
1497
- * @param accessToken - The decrypted access token, if any.
1498
- * @param clientToken - The decrypted client token, if any.
1499
- */
1500
- async function _KycController_handleCheckOutcome(status, accessToken, clientToken) {
1501
- if (status === 'active' && accessToken) {
1502
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1503
- state.accessToken = accessToken;
1504
- state.phase = 'form';
1505
- state.statusMessage = 'Already authenticated. Review to submit.';
1506
- });
1507
- await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_continueAfterAuthentication).call(this);
1508
- return;
1509
- }
1510
- if (status === 'connectionRequired' && clientToken) {
1511
- __classPrivateFieldSet(this, _KycController_authClientToken, clientToken, "f");
1512
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1513
- state.phase = 'auth';
1514
- state.statusMessage = 'Verify your email via OTP in the Auth frame.';
1515
- });
1516
- return;
1517
- }
1518
- if (status === 'termsAcceptanceRequired') {
1519
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_requireTermsReacceptance).call(this);
1520
- return;
1521
- }
1522
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, `Check frame returned status: ${status}`);
1523
- }, _KycController_handleAuthOutcome =
1524
- /**
1525
- * Applies an Auth-frame outcome.
1526
- *
1527
- * @param status - The frame status.
1528
- * @param accessToken - The decrypted access token, if any.
1529
- */
1530
- async function _KycController_handleAuthOutcome(status, accessToken) {
1531
- if (status === 'active' && accessToken) {
1532
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1533
- state.accessToken = accessToken;
1534
- state.phase = 'form';
1535
- state.statusMessage = 'Authenticated. Review to submit.';
1536
- });
1537
- await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_continueAfterAuthentication).call(this);
1538
- return;
1539
- }
1540
- if (status === 'termsAcceptanceRequired') {
1541
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_requireTermsReacceptance).call(this);
1542
- return;
1543
- }
1544
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, `Auth frame returned status: ${status}`);
1545
- }, _KycController_continueAfterAuthentication =
1546
- /**
1547
- * Continues the flow once authentication has completed (phase `form`).
1548
- *
1549
- * When the flow is scoped to a product (see {@link initialize}), the
1550
- * KYC-required check runs automatically, and — when KYC is required — the
1551
- * document-verification sub-flow is launched. When no product is set, this is
1552
- * a no-op and the flow stays at `form` for the consumer to drive manually.
1553
- *
1554
- * Errors are already recorded on state by `checkKycRequired` (`error`
1555
- * phase) and `startSumSub` (`sumsub.status = 'failed'`); this method swallows
1556
- * them so it can be awaited safely from the frame-message handler.
1557
- */
1558
- async function _KycController_continueAfterAuthentication() {
1559
- const product = this.state.activeProduct;
1560
- if (!product) {
1561
- return;
1562
- }
1563
- // Re-entry protection lives at the frame boundary: `handleFrameMessage`
1564
- // only honors a Check/Auth `complete` while `phase` matches and
1565
- // `activeVendor` is MoonPay, and both outcome handlers move `phase` to
1566
- // `form` before awaiting this method. A duplicate, late, or cross-vendor
1567
- // `complete` therefore lands after the phase moved on (or on the wrong
1568
- // vendor) and is dropped before it can start a second continuation. Any
1569
- // writes here are additionally guarded by `#generation` (see
1570
- // `checkKycRequired` / `startSumSub`) so a `reset()` mid-continuation
1571
- // cannot corrupt state.
1572
- const kycRequired = await this.checkKycRequired({ product });
1573
- if (!kycRequired) {
1574
- return;
1575
- }
1576
- try {
1577
- await this.startSumSub();
1578
- }
1579
- catch {
1580
- // `startSumSub` already records `sumsub.status = 'failed'`; swallow the
1581
- // rethrown error (e.g. SDK unavailable) so the awaited continuation
1582
- // resolves cleanly rather than surfacing as an unhandled rejection.
1583
- }
1584
- }, _KycController_requireTermsReacceptance = function _KycController_requireTermsReacceptance() {
1585
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1586
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearAcceptedTerms).call(this, state);
1587
- state.phase = 'terms';
1588
- state.statusMessage =
1589
- 'The vendor updated its Terms of Use — please re-accept.';
1590
- });
1591
- }, _KycController_buildUkycSessionVendorFields = function _KycController_buildUkycSessionVendorFields() {
1592
- if (this.state.activeVendor === 'moonpay') {
1593
- return {
1594
- vendor: 'moonpay',
1595
- vendorMetadata: {
1596
- moonPayAccessToken: this.state.accessToken,
1597
- moonPayUserId: this.state.moonpayCustomerId,
1598
- },
1599
- };
1600
- }
1601
- return { vendor: this.state.activeVendor };
1602
- }, _KycController_createUkycSession =
1603
- /**
1604
- * Creates a UKYC session, wraps the `data_encryption_key` and
1605
- * `ukyc_capability_token` against the returned encryption schemas, and
1606
- * submits both via authorizations. Stores `sumsub.sessionId`. Returns `null`
1607
- * when a `reset()` superseded the flow.
1608
- *
1609
- * @param generation - Flow generation captured by the caller.
1610
- * @returns The created session, or `null` if superseded.
1611
- */
1612
- async function _KycController_createUkycSession(generation) {
1613
- const jwtToken = MOCK_JWT_TOKEN;
1614
- // Establish a per-session X25519 keypair used to seal both secrets. The
1615
- // private half stays on the device; the public half is registered on the
1616
- // session so the server can open later authorizations. Each encryption
1617
- // schema from session creation supplies the matching server public key.
1618
- const sessionClientPrivateKey = x25519.utils.randomSecretKey();
1619
- const sessionClientPublicKey = toBase64Url(x25519.getPublicKey(sessionClientPrivateKey));
1620
- // Residence is the ISO 3166-1 alpha-3 country already resolved for
1621
- // disclaimers / KYC-required; fetch it if this sub-flow started without
1622
- // that earlier step.
1623
- const residenceCountry = this.state.geoCountry ??
1624
- (await this.messenger.call('KycService:getGeoCountry'));
1625
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1626
- return null;
1627
- }
1628
- if (residenceCountry !== this.state.geoCountry) {
1629
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1630
- state.geoCountry = residenceCountry;
1631
- });
1632
- }
1633
- const { sessionId, encryptionDataKey, ukycCapabilityToken: capabilityTokenSchema, } = await this.messenger.call('KycService:createUkycSession', {
1634
- jwtToken,
1635
- sessionClientPublicKey,
1636
- residenceCountry,
1637
- ...__classPrivateFieldGet(this, _KycController_instances, "m", _KycController_buildUkycSessionVendorFields).call(this),
1638
- });
1639
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1640
- return null;
1641
- }
1642
- // Verify each schema's jwtChain against the matching issuer JWKS, then
1643
- // confirm the returned server public key matches the value attested inside
1644
- // the verified JWT payload before trusting it for wrapping.
1645
- // `encryptionDataKey` is attested by the idOS enclave; `ukycCapabilityToken` by the
1646
- // idOS relay.
1647
- const [{ keys: idosEnclaveKeys }, { keys: idosRelayKeys }] = await Promise.all([
1648
- this.messenger.call('KycService:fetchIdosEnclaveJwks'),
1649
- this.messenger.call('KycService:fetchIdosRelayJwks'),
1650
- ]);
1651
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_assertAttestedServerPublicKey).call(this, idosEnclaveKeys, encryptionDataKey);
1652
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_assertAttestedServerPublicKey).call(this, idosRelayKeys, capabilityTokenSchema);
1653
- // Derive the data_encryption_key from the local_user_secret, mint a
1654
- // read-only capability token, and wrap both for the session server. Only
1655
- // the wrapped (encrypted) material ever leaves the device.
1656
- const localUserSecret = await getOrCreateLocalUserSecret(__classPrivateFieldGet(this, _KycController_instances, "m", _KycController_localUserSecretStore).call(this));
1657
- const clientMaterial = deriveClientMaterial(localUserSecret);
1658
- const wrappedEncryptionDataKey = wrapEncryptionKey(sessionClientPrivateKey, encryptionDataKey.serverPublicKey.x, clientMaterial.dataEncryptionKey);
1659
- // Only the client holds the signing key derived from `local_user_secret`,
1660
- // so only the client can mint the token; scoping it to `read` means it
1661
- // authorizes later storage reads without granting write or delete access.
1662
- const ukycCapabilityToken = signStorageAccessToken({
1663
- material: clientMaterial,
1664
- operations: ['read'],
1665
- expiresAt: new Date(Date.now() + UKYC_CAPABILITY_TOKEN_TTL_MS),
1666
- });
1667
- const wrappedUkycCapabilityToken = wrapEncryptionKey(sessionClientPrivateKey, capabilityTokenSchema.serverPublicKey.x, stringToBytes(encodeStorageAccessTokenForHeader(ukycCapabilityToken)));
1668
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1669
- return null;
1670
- }
1671
- const { kycStatus, finalStatus } = await this.messenger.call('KycService:setAuthorizations', {
1672
- sessionId,
1673
- wrappedEncryptionDataKey,
1674
- wrappedUkycCapabilityToken,
1675
- });
1676
- const vendorProcessing = kycStatus === KYC_STATUSES.approved &&
1677
- finalStatus === KYC_STATUSES.pending;
1678
- const stillCurrent = __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
1679
- state.sumsub.sessionId = sessionId;
1680
- if (vendorProcessing) {
1681
- state.sumsub.status = 'vendorProcessing';
1682
- state.statusMessage = VENDOR_PROCESSING_MESSAGE;
1683
- }
1684
- });
1685
- if (!stillCurrent) {
1686
- return null;
1687
- }
1688
- return { sessionId, kycStatus, finalStatus, vendorProcessing };
1689
- }, _KycController_fetchAndApplyUserStatus =
1690
- /**
1691
- * Fetches `GET /kyc/status` and applies it to state without managing the
1692
- * poll loop (used by both {@link refreshKycStatus} and the poll tick).
1693
- *
1694
- * @returns The latest status payload.
1695
- */
1696
- async function _KycController_fetchAndApplyUserStatus() {
1697
- const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
1698
- const response = await this.messenger.call('KycService:fetchKycStatus');
1699
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1700
- return {
1701
- status: this.state.userStatus ?? 'not-started',
1702
- sumsubSessionId: this.state.userStatusSumsubSessionId,
1703
- errorCode: this.state.userStatusErrorCode,
1704
- };
1705
- }
1706
- const payload = {
1707
- status: response.status,
1708
- sumsubSessionId: response.sumsubSessionId ?? null,
1709
- errorCode: response.errorCode ?? null,
1710
- };
1711
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUserStatus).call(this, payload);
1712
- return payload;
1713
- }, _KycController_applyUserStatus = function _KycController_applyUserStatus(payload) {
1714
- const previous = this.state.userStatus;
1715
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1716
- state.userStatus = payload.status;
1717
- state.userStatusSumsubSessionId = payload.sumsubSessionId;
1718
- state.userStatusErrorCode = payload.errorCode;
1719
- });
1720
- if (previous !== payload.status) {
1721
- this.messenger.publish(`${controllerName}:statusChanged`, payload);
1722
- }
1723
- }, _KycController_ensureUserStatusPolling = function _KycController_ensureUserStatusPolling() {
1724
- if (__classPrivateFieldGet(this, _KycController_userStatusPolling, "f")) {
1725
- return;
1726
- }
1727
- __classPrivateFieldSet(this, _KycController_userStatusPolling, true, "f");
1728
- const token = __classPrivateFieldGet(this, _KycController_userStatusPollToken, "f");
1729
- const tick = async () => {
1730
- try {
1731
- const payload = await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fetchAndApplyUserStatus).call(this);
1732
- // Race with `reset()` / `#stopUserStatusPolling` while the request was
1733
- // in flight — do not reschedule onto an idle controller.
1734
- /* istanbul ignore next */
1735
- if (__classPrivateFieldGet(this, _KycController_userStatusPollToken, "f") !== token) {
1736
- return;
1737
- }
1738
- if (payload.status !== 'pending') {
1739
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopUserStatusPolling).call(this);
1740
- return;
1741
- }
1742
- }
1743
- catch {
1744
- // Keep polling on transient errors, unless the loop was superseded.
1745
- /* istanbul ignore next */
1746
- if (__classPrivateFieldGet(this, _KycController_userStatusPollToken, "f") !== token) {
1747
- return;
1748
- }
1749
- }
1750
- __classPrivateFieldSet(this, _KycController_userStatusPollTimer, setTimeout(() => {
1751
- __classPrivateFieldSet(this, _KycController_userStatusPollTimer, null, "f");
1752
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
1753
- tick();
1754
- }, __classPrivateFieldGet(this, _KycController_userStatusPollIntervalMs, "f")), "f");
1755
- // Allow the process to exit while a pending-status poll is scheduled.
1756
- // React Native / browser timers are numbers with no `unref`, hence the
1757
- // optional call.
1758
- __classPrivateFieldGet(this, _KycController_userStatusPollTimer, "f").unref?.();
1759
- };
1760
- __classPrivateFieldSet(this, _KycController_userStatusPollTimer, setTimeout(() => {
1761
- __classPrivateFieldSet(this, _KycController_userStatusPollTimer, null, "f");
1762
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
1763
- tick();
1764
- }, __classPrivateFieldGet(this, _KycController_userStatusPollIntervalMs, "f")), "f");
1765
- __classPrivateFieldGet(this, _KycController_userStatusPollTimer, "f").unref?.();
1766
- }, _KycController_stopUserStatusPolling = function _KycController_stopUserStatusPolling() {
1767
- __classPrivateFieldSet(this, _KycController_userStatusPollToken, __classPrivateFieldGet(this, _KycController_userStatusPollToken, "f") + 1, "f");
1768
- __classPrivateFieldSet(this, _KycController_userStatusPolling, false, "f");
1769
- if (__classPrivateFieldGet(this, _KycController_userStatusPollTimer, "f") !== null) {
1770
- clearTimeout(__classPrivateFieldGet(this, _KycController_userStatusPollTimer, "f"));
1771
- __classPrivateFieldSet(this, _KycController_userStatusPollTimer, null, "f");
1772
- }
1773
- }, _KycController_startSessionStatusPolling =
1774
- /**
1775
- * Begins polling the UKYC session status until a terminal decision is
1776
- * reached. The first poll runs immediately (and is awaited by
1777
- * {@link startSumSub}); subsequent polls are scheduled every
1778
- * `#sessionStatusPollIntervalMs`.
1779
- *
1780
- * @param sessionId - The UKYC session id to poll.
1781
- * @returns A promise that resolves once the first poll settles.
1782
- */
1783
- async function _KycController_startSessionStatusPolling(sessionId) {
1784
- // Supersede any prior loop and claim a fresh token for this one. Because
1785
- // `#stopPolling` bumps the token, any in-flight poll from a previous loop
1786
- // sees a mismatch and neither writes state nor reschedules.
1787
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopPolling).call(this);
1788
- const token = __classPrivateFieldGet(this, _KycController_pollToken, "f");
1789
- const tick = async () => {
1790
- const shouldStop = await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_pollSessionStatusOnce).call(this, sessionId, token);
1791
- if (shouldStop) {
1792
- return;
1793
- }
1794
- __classPrivateFieldSet(this, _KycController_pollTimer, setTimeout(() => {
1795
- __classPrivateFieldSet(this, _KycController_pollTimer, null, "f");
1796
- // `tick` swallows its own errors (see `#pollSessionStatusOnce`) and
1797
- // therefore never rejects, so this fire-and-forget scheduled poll
1798
- // cannot surface as an unhandled rejection.
1799
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
1800
- tick();
1801
- }, __classPrivateFieldGet(this, _KycController_sessionStatusPollIntervalMs, "f")), "f");
1802
- };
1803
- await tick();
1804
- }, _KycController_pollSessionStatusOnce =
1805
- /**
1806
- * Performs a single session-status poll: fetches the status, records it, and
1807
- * resolves the sub-flow when the status is terminal.
1808
- *
1809
- * Transient errors are swallowed so the loop keeps polling; the last good
1810
- * `sessionStatus` is deliberately preserved rather than being overwritten
1811
- * with the error.
1812
- *
1813
- * @param sessionId - The UKYC session id to poll.
1814
- * @param token - The polling token captured when the loop started.
1815
- * @returns `true` when the loop should stop (terminal status or superseded
1816
- * by a reset / new sub-flow), `false` when it should keep polling.
1817
- */
1818
- async function _KycController_pollSessionStatusOnce(sessionId, token) {
1819
- try {
1820
- const sessionStatus = await this.messenger.call('KycService:getSessionStatus', { sessionId });
1821
- // Superseded while the request was in flight — drop the result.
1822
- if (__classPrivateFieldGet(this, _KycController_pollToken, "f") !== token) {
1823
- return true;
1824
- }
1825
- const isTerminal = TERMINAL_SESSION_STATUSES.has(sessionStatus.finalStatus);
1826
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1827
- state.sumsub.sessionStatus = sessionStatus;
1828
- if (isTerminal) {
1829
- state.sumsub.status = SUCCESSFUL_SESSION_STATUSES.has(sessionStatus.finalStatus)
1830
- ? 'complete'
1831
- : 'failed';
1832
- }
1833
- });
1834
- if (isTerminal) {
1835
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopPolling).call(this);
1836
- }
1837
- return isTerminal;
1838
- }
1839
- catch {
1840
- // Keep polling on transient errors, preserving the last good status.
1841
- // Stop only when a reset / new sub-flow superseded this loop.
1842
- return __classPrivateFieldGet(this, _KycController_pollToken, "f") !== token;
1843
- }
1844
- }, _KycController_stopPolling = function _KycController_stopPolling() {
1845
- __classPrivateFieldSet(this, _KycController_pollToken, __classPrivateFieldGet(this, _KycController_pollToken, "f") + 1, "f");
1846
- if (__classPrivateFieldGet(this, _KycController_pollTimer, "f") !== null) {
1847
- clearTimeout(__classPrivateFieldGet(this, _KycController_pollTimer, "f"));
1848
- __classPrivateFieldSet(this, _KycController_pollTimer, null, "f");
1849
- }
1850
- }, _KycController_cancelPendingSession = function _KycController_cancelPendingSession() {
1851
- __classPrivateFieldSet(this, _KycController_authClientToken, null, "f");
1852
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopPolling).call(this);
1853
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopUserStatusPolling).call(this);
1854
- __classPrivateFieldSet(this, _KycController_generation, __classPrivateFieldGet(this, _KycController_generation, "f") + 1, "f");
1855
- }, _KycController_updateIfCurrent = function _KycController_updateIfCurrent(generation, updater) {
1856
- if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1857
- return false;
1858
- }
1859
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, updater);
1860
- return true;
1861
- }, _KycController_applyUpdate = function _KycController_applyUpdate(updater) {
1862
- this.update((state) => {
1863
- // @ts-expect-error Avoid "type instantiation is excessively deep".
1864
- updater(state);
1865
- });
1866
- }, _KycController_assertAttestedServerPublicKey = function _KycController_assertAttestedServerPublicKey(keys, schema) {
1867
- const jwtChainPayload = verifyJwtChain(keys, schema.jwtChain);
1868
- if (jwtChainPayload.sessionServerPublicKeyX !== schema.serverPublicKey.x) {
1869
- throw new Error('sessionServerPublicKey does not match the verified jwtChain payload (sessionServerPublicKeyX).');
1870
- }
1871
- }, _KycController_fail = function _KycController_fail(message) {
1872
- __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1873
- state.error = message;
1874
- state.phase = 'error';
1875
- });
1876
- };
1877
- //# sourceMappingURL=KycController.mjs.map