@metamask-previews/kyc-controller 0.0.0-preview-823dcff → 0.0.0-preview-e57e5c3dc

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 (155) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +10 -2
  3. package/dist/KycController-method-action-types.cjs +7 -0
  4. package/dist/KycController-method-action-types.cjs.map +1 -0
  5. package/dist/KycController-method-action-types.d.cts +168 -0
  6. package/dist/KycController-method-action-types.d.cts.map +1 -0
  7. package/dist/KycController-method-action-types.d.mts +168 -0
  8. package/dist/KycController-method-action-types.d.mts.map +1 -0
  9. package/dist/KycController-method-action-types.mjs +6 -0
  10. package/dist/KycController-method-action-types.mjs.map +1 -0
  11. package/dist/KycController.cjs +1085 -0
  12. package/dist/KycController.cjs.map +1 -0
  13. package/dist/KycController.d.cts +255 -0
  14. package/dist/KycController.d.cts.map +1 -0
  15. package/dist/KycController.d.mts +255 -0
  16. package/dist/KycController.d.mts.map +1 -0
  17. package/dist/KycController.mjs +1080 -0
  18. package/dist/KycController.mjs.map +1 -0
  19. package/dist/KycService-method-action-types.cjs +7 -0
  20. package/dist/KycService-method-action-types.cjs.map +1 -0
  21. package/dist/KycService-method-action-types.d.cts +121 -0
  22. package/dist/KycService-method-action-types.d.cts.map +1 -0
  23. package/dist/KycService-method-action-types.d.mts +121 -0
  24. package/dist/KycService-method-action-types.d.mts.map +1 -0
  25. package/dist/KycService-method-action-types.mjs +6 -0
  26. package/dist/KycService-method-action-types.mjs.map +1 -0
  27. package/dist/KycService.cjs +417 -0
  28. package/dist/KycService.cjs.map +1 -0
  29. package/dist/KycService.d.cts +307 -0
  30. package/dist/KycService.d.cts.map +1 -0
  31. package/dist/KycService.d.mts +307 -0
  32. package/dist/KycService.d.mts.map +1 -0
  33. package/dist/KycService.mjs +413 -0
  34. package/dist/KycService.mjs.map +1 -0
  35. package/dist/countryCodes.cjs +274 -0
  36. package/dist/countryCodes.cjs.map +1 -0
  37. package/dist/countryCodes.d.cts +18 -0
  38. package/dist/countryCodes.d.cts.map +1 -0
  39. package/dist/countryCodes.d.mts +18 -0
  40. package/dist/countryCodes.d.mts.map +1 -0
  41. package/dist/countryCodes.mjs +270 -0
  42. package/dist/countryCodes.mjs.map +1 -0
  43. package/dist/crypto.cjs +154 -0
  44. package/dist/crypto.cjs.map +1 -0
  45. package/dist/crypto.d.cts +84 -0
  46. package/dist/crypto.d.cts.map +1 -0
  47. package/dist/crypto.d.mts +84 -0
  48. package/dist/crypto.d.mts.map +1 -0
  49. package/dist/crypto.mjs +149 -0
  50. package/dist/crypto.mjs.map +1 -0
  51. package/dist/encoding.cjs +40 -0
  52. package/dist/encoding.cjs.map +1 -0
  53. package/dist/encoding.d.cts +24 -0
  54. package/dist/encoding.d.cts.map +1 -0
  55. package/dist/encoding.d.mts +24 -0
  56. package/dist/encoding.d.mts.map +1 -0
  57. package/dist/encoding.mjs +35 -0
  58. package/dist/encoding.mjs.map +1 -0
  59. package/dist/index.cjs +34 -10
  60. package/dist/index.cjs.map +1 -1
  61. package/dist/index.d.cts +18 -7
  62. package/dist/index.d.cts.map +1 -1
  63. package/dist/index.d.mts +18 -7
  64. package/dist/index.d.mts.map +1 -1
  65. package/dist/index.mjs +11 -9
  66. package/dist/index.mjs.map +1 -1
  67. package/dist/selectors.cjs +30 -0
  68. package/dist/selectors.cjs.map +1 -0
  69. package/dist/selectors.d.cts +24 -0
  70. package/dist/selectors.d.cts.map +1 -0
  71. package/dist/selectors.d.mts +24 -0
  72. package/dist/selectors.d.mts.map +1 -0
  73. package/dist/selectors.mjs +24 -0
  74. package/dist/selectors.mjs.map +1 -0
  75. package/dist/types.cjs +10 -0
  76. package/dist/types.cjs.map +1 -0
  77. package/dist/types.d.cts +124 -0
  78. package/dist/types.d.cts.map +1 -0
  79. package/dist/types.d.mts +124 -0
  80. package/dist/types.d.mts.map +1 -0
  81. package/dist/types.mjs +9 -0
  82. package/dist/types.mjs.map +1 -0
  83. package/dist/ukyc/constants.cjs +75 -0
  84. package/dist/ukyc/constants.cjs.map +1 -0
  85. package/dist/ukyc/constants.d.cts +69 -0
  86. package/dist/ukyc/constants.d.cts.map +1 -0
  87. package/dist/ukyc/constants.d.mts +69 -0
  88. package/dist/ukyc/constants.d.mts.map +1 -0
  89. package/dist/ukyc/constants.mjs +72 -0
  90. package/dist/ukyc/constants.mjs.map +1 -0
  91. package/dist/ukyc/deriveClientMaterial.cjs +65 -0
  92. package/dist/ukyc/deriveClientMaterial.cjs.map +1 -0
  93. package/dist/ukyc/deriveClientMaterial.d.cts +54 -0
  94. package/dist/ukyc/deriveClientMaterial.d.cts.map +1 -0
  95. package/dist/ukyc/deriveClientMaterial.d.mts +54 -0
  96. package/dist/ukyc/deriveClientMaterial.d.mts.map +1 -0
  97. package/dist/ukyc/deriveClientMaterial.mjs +60 -0
  98. package/dist/ukyc/deriveClientMaterial.mjs.map +1 -0
  99. package/dist/ukyc/jwtChain.cjs +54 -0
  100. package/dist/ukyc/jwtChain.cjs.map +1 -0
  101. package/dist/ukyc/jwtChain.d.cts +40 -0
  102. package/dist/ukyc/jwtChain.d.cts.map +1 -0
  103. package/dist/ukyc/jwtChain.d.mts +40 -0
  104. package/dist/ukyc/jwtChain.d.mts.map +1 -0
  105. package/dist/ukyc/jwtChain.mjs +50 -0
  106. package/dist/ukyc/jwtChain.mjs.map +1 -0
  107. package/dist/ukyc/localUserSecret.cjs +98 -0
  108. package/dist/ukyc/localUserSecret.cjs.map +1 -0
  109. package/dist/ukyc/localUserSecret.d.cts +65 -0
  110. package/dist/ukyc/localUserSecret.d.cts.map +1 -0
  111. package/dist/ukyc/localUserSecret.d.mts +65 -0
  112. package/dist/ukyc/localUserSecret.d.mts.map +1 -0
  113. package/dist/ukyc/localUserSecret.mjs +92 -0
  114. package/dist/ukyc/localUserSecret.mjs.map +1 -0
  115. package/dist/ukyc/storageAccessToken.cjs +139 -0
  116. package/dist/ukyc/storageAccessToken.cjs.map +1 -0
  117. package/dist/ukyc/storageAccessToken.d.cts +99 -0
  118. package/dist/ukyc/storageAccessToken.d.cts.map +1 -0
  119. package/dist/ukyc/storageAccessToken.d.mts +99 -0
  120. package/dist/ukyc/storageAccessToken.d.mts.map +1 -0
  121. package/dist/ukyc/storageAccessToken.mjs +133 -0
  122. package/dist/ukyc/storageAccessToken.mjs.map +1 -0
  123. package/dist/ukyc/testToken.cjs +61 -0
  124. package/dist/ukyc/testToken.cjs.map +1 -0
  125. package/dist/ukyc/testToken.d.cts +50 -0
  126. package/dist/ukyc/testToken.d.cts.map +1 -0
  127. package/dist/ukyc/testToken.d.mts +50 -0
  128. package/dist/ukyc/testToken.d.mts.map +1 -0
  129. package/dist/ukyc/testToken.mjs +57 -0
  130. package/dist/ukyc/testToken.mjs.map +1 -0
  131. package/dist/ukyc/wrapEncryptionKey.cjs +28 -0
  132. package/dist/ukyc/wrapEncryptionKey.cjs.map +1 -0
  133. package/dist/ukyc/wrapEncryptionKey.d.cts +34 -0
  134. package/dist/ukyc/wrapEncryptionKey.d.cts.map +1 -0
  135. package/dist/ukyc/wrapEncryptionKey.d.mts +34 -0
  136. package/dist/ukyc/wrapEncryptionKey.d.mts.map +1 -0
  137. package/dist/ukyc/wrapEncryptionKey.mjs +25 -0
  138. package/dist/ukyc/wrapEncryptionKey.mjs.map +1 -0
  139. package/dist/ukyc/wrapUserKey.cjs +80 -0
  140. package/dist/ukyc/wrapUserKey.cjs.map +1 -0
  141. package/dist/ukyc/wrapUserKey.d.cts +26 -0
  142. package/dist/ukyc/wrapUserKey.d.cts.map +1 -0
  143. package/dist/ukyc/wrapUserKey.d.mts +26 -0
  144. package/dist/ukyc/wrapUserKey.d.mts.map +1 -0
  145. package/dist/ukyc/wrapUserKey.mjs +76 -0
  146. package/dist/ukyc/wrapUserKey.mjs.map +1 -0
  147. package/dist/ukyc/wrappedRelayPayload.cjs +32 -0
  148. package/dist/ukyc/wrappedRelayPayload.cjs.map +1 -0
  149. package/dist/ukyc/wrappedRelayPayload.d.cts +35 -0
  150. package/dist/ukyc/wrappedRelayPayload.d.cts.map +1 -0
  151. package/dist/ukyc/wrappedRelayPayload.d.mts +35 -0
  152. package/dist/ukyc/wrappedRelayPayload.d.mts.map +1 -0
  153. package/dist/ukyc/wrappedRelayPayload.mjs +28 -0
  154. package/dist/ukyc/wrappedRelayPayload.mjs.map +1 -0
  155. package/package.json +24 -3
@@ -0,0 +1,1085 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _KycController_instances, _KycController_sumsubLauncher, _KycController_keypair, _KycController_authClientToken, _KycController_generation, _KycController_sessionStatusPollIntervalMs, _KycController_pollTimer, _KycController_pollToken, _KycController_localUserSecretStore, _KycController_createSession, _KycController_clearAcceptedTerms, _KycController_handleCheckOutcome, _KycController_handleAuthOutcome, _KycController_continueAfterAuthentication, _KycController_requireTermsReacceptance, _KycController_startSessionStatusPolling, _KycController_pollSessionStatusOnce, _KycController_stopPolling, _KycController_updateIfCurrent, _KycController_applyUpdate, _KycController_fail;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.KycController = exports.getDefaultKycControllerState = exports.controllerName = void 0;
16
+ const base_controller_1 = require("@metamask/base-controller");
17
+ const ed25519_1 = require("@noble/curves/ed25519");
18
+ const crypto_js_1 = require("./crypto.cjs");
19
+ const deriveClientMaterial_js_1 = require("./ukyc/deriveClientMaterial.cjs");
20
+ const encoding_js_1 = require("./encoding.cjs");
21
+ const jwtChain_js_1 = require("./ukyc/jwtChain.cjs");
22
+ const localUserSecret_js_1 = require("./ukyc/localUserSecret.cjs");
23
+ const storageAccessToken_js_1 = require("./ukyc/storageAccessToken.cjs");
24
+ const wrapEncryptionKey_js_1 = require("./ukyc/wrapEncryptionKey.cjs");
25
+ // === GENERAL ===
26
+ exports.controllerName = 'KycController';
27
+ const FRAMES_BASE_URL = 'https://blocks.moonpay.com/platform/v1';
28
+ const CHANNEL_CHECK = 'ch_1';
29
+ const CHANNEL_AUTH = 'ch_2';
30
+ const CHANNEL_RESET = 'ch_reset';
31
+ // Placeholder credentials for the SumSub sub-flow. These are demo values that
32
+ // must be replaced with real UKYC-issued material before production use.
33
+ const MOCK_JWT_TOKEN = 'mock-jwt-token';
34
+ // Lifetime of the read-only `ukyc_capability_token` minted when creating a
35
+ // UKYC session. The storage-and-auth spec requires the token's `expires_at` to
36
+ // cover the KYC session's expected lifetime — including the provider journey —
37
+ // rather than a fixed short window, so this is a session-scoped window.
38
+ const UKYC_CAPABILITY_TOKEN_TTL_MS = 4 * 60 * 60 * 1000;
39
+ // The SumSub SDK status that signals the applicant finished the flow
40
+ // successfully. Any other resolution (abandonment, failure, or a non-success
41
+ // outcome) must not be recorded as `complete`.
42
+ const SUMSUB_COMPLETED_STATUS = 'Completed';
43
+ // Phases that represent an active vendor-session flow (tokens issued and/or
44
+ // Check/Auth frames in progress). A repeat `initialize` while in one of these
45
+ // must not restart the session and disrupt the in-flight flow.
46
+ const IN_PROGRESS_PHASES = [
47
+ 'session',
48
+ 'check',
49
+ 'auth',
50
+ 'form',
51
+ 'submit',
52
+ ];
53
+ // How often to poll the UKYC session status after the SumSub SDK completes,
54
+ // until a terminal status is reached. Overridable via the constructor.
55
+ const DEFAULT_SESSION_STATUS_POLL_INTERVAL_MS = 15000;
56
+ // UKYC status values. `kycStatus` (the relay-side decision) and `finalStatus`
57
+ // (the vendor-side outcome) draw from the same vocabulary, so they are defined
58
+ // once here and composed into the sets/checks below rather than repeated as
59
+ // literals.
60
+ const KYC_STATUSES = {
61
+ approved: 'approved',
62
+ completed: 'completed',
63
+ rejected: 'rejected',
64
+ failed: 'failed',
65
+ blocked: 'blocked',
66
+ pending: 'pending',
67
+ };
68
+ // `finalStatus` values that end the polling loop. Anything else (e.g.
69
+ // `KYC_STATUSES.pending`) keeps polling.
70
+ const TERMINAL_SESSION_STATUSES = new Set([
71
+ KYC_STATUSES.approved,
72
+ KYC_STATUSES.completed,
73
+ KYC_STATUSES.rejected,
74
+ KYC_STATUSES.failed,
75
+ KYC_STATUSES.blocked,
76
+ ]);
77
+ // Terminal `finalStatus` values that represent a successful verification. Any
78
+ // other terminal status resolves the sub-flow to `failed`.
79
+ const SUCCESSFUL_SESSION_STATUSES = new Set([
80
+ KYC_STATUSES.approved,
81
+ KYC_STATUSES.completed,
82
+ ]);
83
+ // Session creation can report that the applicant is already approved on the
84
+ // relay (`kycStatus === KYC_STATUSES.approved`) while the vendor is still
85
+ // finalizing its decision (`finalStatus === KYC_STATUSES.pending`, a
86
+ // non-terminal status). In that case there is nothing left for the applicant
87
+ // to do, so the sub-flow stops before launching the SDK and surfaces this
88
+ // message.
89
+ const VENDOR_PROCESSING_MESSAGE = 'Your KYC has been submitted and is being processed by the vendor.';
90
+ const kycControllerMetadata = {
91
+ phase: {
92
+ includeInDebugSnapshot: true,
93
+ includeInStateLogs: true,
94
+ persist: false,
95
+ usedInUi: true,
96
+ },
97
+ statusMessage: {
98
+ includeInDebugSnapshot: true,
99
+ includeInStateLogs: true,
100
+ persist: false,
101
+ usedInUi: true,
102
+ },
103
+ error: {
104
+ includeInDebugSnapshot: true,
105
+ includeInStateLogs: true,
106
+ persist: false,
107
+ usedInUi: true,
108
+ },
109
+ email: {
110
+ includeInDebugSnapshot: false,
111
+ includeInStateLogs: false,
112
+ persist: false,
113
+ usedInUi: false,
114
+ },
115
+ termsAcceptedAt: {
116
+ includeInDebugSnapshot: true,
117
+ includeInStateLogs: true,
118
+ persist: true,
119
+ usedInUi: false,
120
+ },
121
+ acceptedDisclaimerIds: {
122
+ includeInDebugSnapshot: true,
123
+ includeInStateLogs: true,
124
+ persist: true,
125
+ usedInUi: false,
126
+ },
127
+ disclaimers: {
128
+ includeInDebugSnapshot: false,
129
+ includeInStateLogs: false,
130
+ persist: false,
131
+ usedInUi: true,
132
+ },
133
+ disclaimersError: {
134
+ includeInDebugSnapshot: true,
135
+ includeInStateLogs: true,
136
+ persist: false,
137
+ usedInUi: true,
138
+ },
139
+ geoCountry: {
140
+ includeInDebugSnapshot: true,
141
+ includeInStateLogs: true,
142
+ persist: false,
143
+ usedInUi: true,
144
+ },
145
+ sessionToken: {
146
+ includeInDebugSnapshot: false,
147
+ includeInStateLogs: false,
148
+ persist: false,
149
+ usedInUi: false,
150
+ },
151
+ accessToken: {
152
+ includeInDebugSnapshot: false,
153
+ includeInStateLogs: false,
154
+ persist: false,
155
+ usedInUi: false,
156
+ },
157
+ moonpayCustomerId: {
158
+ includeInDebugSnapshot: false,
159
+ includeInStateLogs: false,
160
+ persist: false,
161
+ usedInUi: false,
162
+ },
163
+ activeProduct: {
164
+ includeInDebugSnapshot: true,
165
+ includeInStateLogs: true,
166
+ persist: false,
167
+ usedInUi: true,
168
+ },
169
+ kycRequiredByProduct: {
170
+ includeInDebugSnapshot: true,
171
+ includeInStateLogs: true,
172
+ persist: true,
173
+ usedInUi: true,
174
+ },
175
+ lastCheckedAt: {
176
+ includeInDebugSnapshot: true,
177
+ includeInStateLogs: true,
178
+ persist: true,
179
+ usedInUi: false,
180
+ },
181
+ sumsub: {
182
+ includeInDebugSnapshot: false,
183
+ includeInStateLogs: false,
184
+ persist: false,
185
+ usedInUi: true,
186
+ },
187
+ };
188
+ /**
189
+ * Constructs the default {@link KycController} state.
190
+ *
191
+ * @returns The default state.
192
+ */
193
+ function getDefaultKycControllerState() {
194
+ return {
195
+ phase: 'idle',
196
+ statusMessage: '',
197
+ error: null,
198
+ email: null,
199
+ termsAcceptedAt: null,
200
+ acceptedDisclaimerIds: [],
201
+ disclaimers: [],
202
+ disclaimersError: null,
203
+ geoCountry: null,
204
+ sessionToken: null,
205
+ accessToken: null,
206
+ moonpayCustomerId: null,
207
+ activeProduct: null,
208
+ kycRequiredByProduct: {},
209
+ lastCheckedAt: null,
210
+ sumsub: {
211
+ status: 'idle',
212
+ result: null,
213
+ sessionId: null,
214
+ applicantAccessToken: null,
215
+ sessionStatus: null,
216
+ },
217
+ };
218
+ }
219
+ exports.getDefaultKycControllerState = getDefaultKycControllerState;
220
+ // === MESSENGER ===
221
+ const MESSENGER_EXPOSED_METHODS = [
222
+ 'initialize',
223
+ 'loadDisclaimers',
224
+ 'acceptTermsAndStartSession',
225
+ 'clearSavedTerms',
226
+ 'handleFrameMessage',
227
+ 'buildCheckFrameUrl',
228
+ 'buildAuthFrameUrl',
229
+ 'buildResetFrameUrl',
230
+ 'checkKycRequired',
231
+ 'getKycStatus',
232
+ 'startSumSub',
233
+ 'getSessionStatus',
234
+ 'reset',
235
+ ];
236
+ // === CONTROLLER DEFINITION ===
237
+ /**
238
+ * `KycController` orchestrates the vendor-backed KYC / identity-verification
239
+ * flow (MoonPay identity + SumSub documents) behind a vendor-neutral, per
240
+ * product surface used by ramps and card. It owns all state, HTTP
241
+ * orchestration (via `KycService`), crypto, and the frame message protocol;
242
+ * platform-specific presentation (WebView/iframe, SumSub SDK) is injected.
243
+ */
244
+ class KycController extends base_controller_1.BaseController {
245
+ /**
246
+ * Constructs a new {@link KycController}.
247
+ *
248
+ * @param options - The constructor options.
249
+ * @param options.messenger - The messenger suited for this controller.
250
+ * @param options.state - Partial initial state; merged over defaults.
251
+ * @param options.sumsubLauncher - The platform SumSub launcher adapter.
252
+ * @param options.sessionStatusPollIntervalMs - How often to poll the UKYC
253
+ * session status after the SumSub SDK completes.
254
+ */
255
+ constructor({ messenger, state, sumsubLauncher, sessionStatusPollIntervalMs = DEFAULT_SESSION_STATUS_POLL_INTERVAL_MS, }) {
256
+ super({
257
+ messenger,
258
+ metadata: kycControllerMetadata,
259
+ name: exports.controllerName,
260
+ state: { ...getDefaultKycControllerState(), ...state },
261
+ });
262
+ _KycController_instances.add(this);
263
+ _KycController_sumsubLauncher.set(this, void 0);
264
+ /** Ephemeral X25519 keypair for the frame key exchange (never persisted). */
265
+ _KycController_keypair.set(this, void 0);
266
+ /** Auth-frame client token, kept out of state. */
267
+ _KycController_authClientToken.set(this, null);
268
+ /**
269
+ * Monotonic flow generation. Incremented by {@link reset} so in-flight async
270
+ * work (e.g. the KYC-required check) can detect that it was superseded and
271
+ * avoid writing stale results onto a reset controller.
272
+ */
273
+ _KycController_generation.set(this, 0);
274
+ /** Interval, in milliseconds, between session-status polls. */
275
+ _KycController_sessionStatusPollIntervalMs.set(this, void 0);
276
+ /** Handle for the scheduled next session-status poll, or `null`. */
277
+ _KycController_pollTimer.set(this, null);
278
+ /**
279
+ * Monotonic polling token. Bumped by {@link #stopPolling} (called on reset, a
280
+ * new sub-flow, and once a terminal status is reached) so an in-flight poll
281
+ * `tick` can detect it was superseded and neither write state nor schedule a
282
+ * follow-up. This closes the gap where clearing the timer alone would still
283
+ * let an already-awaiting request finish and reschedule.
284
+ */
285
+ _KycController_pollToken.set(this, 0);
286
+ __classPrivateFieldSet(this, _KycController_sumsubLauncher, sumsubLauncher, "f");
287
+ __classPrivateFieldSet(this, _KycController_sessionStatusPollIntervalMs, sessionStatusPollIntervalMs, "f");
288
+ __classPrivateFieldSet(this, _KycController_keypair, (0, crypto_js_1.generateKeyPair)(), "f");
289
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
290
+ }
291
+ /**
292
+ * Resolves persisted terms + geolocation, and auto-creates a session when
293
+ * terms are already accepted and an email is available.
294
+ *
295
+ * @param params - Optional parameters.
296
+ * @param params.email - The account email to associate with the session.
297
+ * @param params.product - The consuming feature the flow runs for. When
298
+ * provided, the controller automatically runs the KYC-required check once
299
+ * authentication completes (and chains into document verification when KYC
300
+ * is required). When omitted, the flow stops at `form` and the consumer must
301
+ * call `checkKycRequired` manually.
302
+ */
303
+ async initialize(params) {
304
+ // A repeat `initialize` while a session flow is already in progress must
305
+ // not tear it down: creating a new vendor session clears the tokens and
306
+ // forces `phase` back through `session`/`check`, breaking an in-flight
307
+ // Check/Auth frame flow. Leave the active flow untouched and let the
308
+ // consumer drive it (or call `reset` first to start over).
309
+ if (IN_PROGRESS_PHASES.includes(this.state.phase)) {
310
+ return;
311
+ }
312
+ // `initialize` starts a fresh flow, so `activeProduct` is always reset to
313
+ // this call's product (or `null`). Otherwise a prior run's product could
314
+ // linger and cause `#continueAfterAuthentication` to auto-run the check /
315
+ // sub-flow when the caller intended the manual (product-less) flow.
316
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
317
+ if (params?.email) {
318
+ state.email = params.email;
319
+ }
320
+ state.activeProduct = params?.product ?? null;
321
+ });
322
+ // Capture the flow generation so a `reset()` landing while the async
323
+ // geolocation / session steps below are in flight cannot write results
324
+ // onto an idle controller.
325
+ const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
326
+ // Resolve country for display; non-blocking.
327
+ try {
328
+ const country = await this.messenger.call('KycService:getGeoCountry');
329
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
330
+ state.geoCountry = country;
331
+ });
332
+ }
333
+ catch {
334
+ // Ignore; disclaimers loading will surface a country error if needed.
335
+ }
336
+ const hasTerms = Boolean(this.state.termsAcceptedAt) &&
337
+ this.state.acceptedDisclaimerIds.length > 0;
338
+ if (hasTerms && this.state.email) {
339
+ await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_createSession).call(this);
340
+ return;
341
+ }
342
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
343
+ state.phase = 'terms';
344
+ });
345
+ await this.loadDisclaimers();
346
+ }
347
+ /**
348
+ * Loads the disclaimers for the resolved (or provided) country.
349
+ *
350
+ * @param params - Optional parameters.
351
+ * @param params.country - ISO 3166-1 alpha-3 country code override.
352
+ */
353
+ async loadDisclaimers(params) {
354
+ // Capture the flow generation so a `reset()` landing while the geo /
355
+ // disclaimers requests are in flight cannot write results onto an idle
356
+ // controller.
357
+ const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
358
+ try {
359
+ const country = params?.country ??
360
+ this.state.geoCountry ??
361
+ (await this.messenger.call('KycService:getGeoCountry'));
362
+ if (country !== this.state.geoCountry) {
363
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
364
+ state.geoCountry = country;
365
+ });
366
+ }
367
+ const disclaimers = await this.messenger.call('KycService:fetchDisclaimers', { country });
368
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
369
+ state.disclaimers = disclaimers;
370
+ state.disclaimersError = null;
371
+ });
372
+ }
373
+ catch (error) {
374
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
375
+ state.disclaimersError = `Failed to load disclaimers: ${String(error)}`;
376
+ });
377
+ }
378
+ }
379
+ /**
380
+ * Captures terms acceptance for the currently loaded disclaimers and creates
381
+ * a session.
382
+ *
383
+ * @param params - Optional parameters.
384
+ * @param params.email - The account email to associate with the session.
385
+ * @param params.product - The consuming feature the flow runs for. See
386
+ * {@link initialize} for how the product drives the automatic post
387
+ * authentication continuation.
388
+ */
389
+ async acceptTermsAndStartSession(params) {
390
+ const termsAcceptedAt = new Date().toISOString();
391
+ const disclaimerIds = this.state.disclaimers.map((disclaimer) => disclaimer.id);
392
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
393
+ if (params?.email) {
394
+ state.email = params.email;
395
+ }
396
+ if (params?.product) {
397
+ state.activeProduct = params.product;
398
+ }
399
+ state.termsAcceptedAt = termsAcceptedAt;
400
+ state.acceptedDisclaimerIds = disclaimerIds;
401
+ });
402
+ await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_createSession).call(this);
403
+ }
404
+ /**
405
+ * Clears the persisted terms acceptance.
406
+ */
407
+ clearSavedTerms() {
408
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
409
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearAcceptedTerms).call(this, state);
410
+ });
411
+ }
412
+ /**
413
+ * Handles a message posted by a Check/Auth frame and advances the flow.
414
+ *
415
+ * The transport-agnostic caller (WebView on mobile, iframe on web) forwards
416
+ * the raw message and injects the returned `reply` back into the frame.
417
+ *
418
+ * @param params - The parameters.
419
+ * @param params.message - The raw message posted by the frame.
420
+ * @returns An object whose optional `reply` should be posted back.
421
+ */
422
+ async handleFrameMessage(params) {
423
+ const payload = params.message;
424
+ if (!payload) {
425
+ return {};
426
+ }
427
+ if (payload.kind === 'handshake') {
428
+ const channelId = payload.meta?.channelId;
429
+ return { reply: { version: 2, meta: { channelId }, kind: 'ack' } };
430
+ }
431
+ if (payload.kind !== 'complete') {
432
+ return {};
433
+ }
434
+ const channelId = payload.meta?.channelId;
435
+ // Only honor a Check/Auth `complete` for the frame the flow is currently
436
+ // waiting on. This drops stale or duplicate messages — e.g. a late post
437
+ // after `reset()` (phase `idle`) or after the flow already advanced past
438
+ // this frame — so they cannot resurrect tokens or rewind `phase` on a
439
+ // controller that has moved on. Frame messages are external input and,
440
+ // unlike the async steps, are not covered by the `#generation` guard.
441
+ let expectedPhase = null;
442
+ if (channelId === CHANNEL_CHECK) {
443
+ expectedPhase = 'check';
444
+ }
445
+ else if (channelId === CHANNEL_AUTH) {
446
+ expectedPhase = 'auth';
447
+ }
448
+ if (!expectedPhase || this.state.phase !== expectedPhase) {
449
+ return {};
450
+ }
451
+ const status = payload.payload?.status;
452
+ const credsEnvelope = payload.payload?.credentials;
453
+ const customerId = payload.payload?.customer?.id ?? null;
454
+ if (customerId) {
455
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
456
+ state.moonpayCustomerId = customerId;
457
+ });
458
+ }
459
+ if (!status) {
460
+ return {};
461
+ }
462
+ let accessToken;
463
+ let clientToken;
464
+ if (credsEnvelope) {
465
+ try {
466
+ const { credentials } = (0, crypto_js_1.decryptCredentials)(credsEnvelope, __classPrivateFieldGet(this, _KycController_keypair, "f").privateKey);
467
+ accessToken = credentials.accessToken;
468
+ clientToken = credentials.clientToken;
469
+ }
470
+ catch (error) {
471
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, `Failed to decrypt frame credentials: ${String(error)}`);
472
+ return {};
473
+ }
474
+ }
475
+ if (channelId === CHANNEL_CHECK) {
476
+ await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_handleCheckOutcome).call(this, status, accessToken, clientToken);
477
+ return {};
478
+ }
479
+ // channelId === CHANNEL_AUTH, guaranteed by the expectedPhase guard above.
480
+ await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_handleAuthOutcome).call(this, status, accessToken);
481
+ return {};
482
+ }
483
+ /**
484
+ * Builds the Check-frame URL, or `null` when no session exists yet.
485
+ *
486
+ * @returns The Check-frame URL or `null`.
487
+ */
488
+ buildCheckFrameUrl() {
489
+ if (!this.state.sessionToken) {
490
+ return null;
491
+ }
492
+ const url = new URL(`${FRAMES_BASE_URL}/check-connection`);
493
+ url.searchParams.set('sessionToken', this.state.sessionToken);
494
+ url.searchParams.set('publicKey', __classPrivateFieldGet(this, _KycController_keypair, "f").publicKeyHex);
495
+ url.searchParams.set('channelId', CHANNEL_CHECK);
496
+ url.searchParams.set('skipKyc', 'true');
497
+ return url.toString();
498
+ }
499
+ /**
500
+ * Builds the Auth-frame URL, or `null` when no client token is available.
501
+ *
502
+ * @returns The Auth-frame URL or `null`.
503
+ */
504
+ buildAuthFrameUrl() {
505
+ if (!__classPrivateFieldGet(this, _KycController_authClientToken, "f")) {
506
+ return null;
507
+ }
508
+ const url = new URL(`${FRAMES_BASE_URL}/auth`);
509
+ url.searchParams.set('clientToken', __classPrivateFieldGet(this, _KycController_authClientToken, "f"));
510
+ url.searchParams.set('publicKey', __classPrivateFieldGet(this, _KycController_keypair, "f").publicKeyHex);
511
+ url.searchParams.set('channelId', CHANNEL_AUTH);
512
+ return url.toString();
513
+ }
514
+ /**
515
+ * Builds the Reset-frame URL.
516
+ *
517
+ * @returns The Reset-frame URL.
518
+ */
519
+ buildResetFrameUrl() {
520
+ const url = new URL(`${FRAMES_BASE_URL}/reset`);
521
+ url.searchParams.set('channelId', CHANNEL_RESET);
522
+ return url.toString();
523
+ }
524
+ /**
525
+ * Checks whether KYC is required for a product and caches the result.
526
+ *
527
+ * @param params - The parameters.
528
+ * @param params.product - The consuming feature.
529
+ * @param params.country - Optional alpha-3 country override.
530
+ * @returns Whether KYC is required.
531
+ */
532
+ async checkKycRequired(params) {
533
+ const { accessToken } = this.state;
534
+ if (!accessToken) {
535
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing accessToken — repeat the authentication step.');
536
+ return false;
537
+ }
538
+ const country = params.country ?? this.state.geoCountry;
539
+ if (!country) {
540
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing country for KYC-required check.');
541
+ return false;
542
+ }
543
+ // Capture the flow generation so we can detect a `reset()` that happens
544
+ // while the HTTP call is in flight and avoid writing stale results.
545
+ const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
546
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
547
+ state.phase = 'submit';
548
+ state.statusMessage = 'Checking KYC status...';
549
+ });
550
+ try {
551
+ const { kycRequired } = await this.messenger.call('KycService:checkKycRequired', { accessToken, country, capabilities: [{ product: params.product }] });
552
+ // The flow was reset while the check was in flight; discard the result
553
+ // rather than resurrecting a done/cached state on an idle controller.
554
+ const applied = __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
555
+ state.kycRequiredByProduct[params.product] = kycRequired;
556
+ state.lastCheckedAt = new Date().toISOString();
557
+ state.phase = 'done';
558
+ state.statusMessage = 'KYC check complete.';
559
+ });
560
+ if (!applied) {
561
+ return false;
562
+ }
563
+ return kycRequired;
564
+ }
565
+ catch (error) {
566
+ if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
567
+ return false;
568
+ }
569
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, `KYC check failed: ${String(error)}`);
570
+ return false;
571
+ }
572
+ }
573
+ /**
574
+ * Reads the cached "is KYC required" result for a product.
575
+ *
576
+ * @param params - The parameters.
577
+ * @param params.product - The consuming feature.
578
+ * @returns The cached value, or `undefined` if not yet checked.
579
+ */
580
+ getKycStatus(params) {
581
+ return this.state.kycRequiredByProduct[params.product];
582
+ }
583
+ /**
584
+ * Runs the SumSub document-verification sub-flow end to end:
585
+ *
586
+ * 1. requests a per-session wrapping key from the UKYC backend;
587
+ * 2. verifies its `jwtChain` against the Fractal JWKS and confirms the
588
+ * attested session server public key;
589
+ * 3. derives the `data_encryption_key` from the wallet's UKYC
590
+ * `local_user_secret` and wraps it for the session server;
591
+ * 4. mints a client-signed, read-only `ukyc_capability_token` and creates
592
+ * the UKYC session (handing over the wrapped key and the token);
593
+ * 5. fetches the SumSub applicant access token; and
594
+ * 6. presents the SDK via the injected launcher.
595
+ *
596
+ * If session creation reports the applicant is already approved on the relay
597
+ * while the vendor is still finalizing (`kycStatus: approved`,
598
+ * `finalStatus: pending`), the sub-flow stops at step 4 with a
599
+ * `vendorProcessing` status and a message rather than launching the SDK.
600
+ *
601
+ * @param params - Optional parameters.
602
+ * @param params.locale - BCP-47 locale for the SDK UI.
603
+ * @param params.debug - Enables SDK debug logging.
604
+ * @returns The SDK result.
605
+ */
606
+ async startSumSub(params) {
607
+ // A new sub-flow supersedes any polling still running from a prior run.
608
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopPolling).call(this);
609
+ if (!__classPrivateFieldGet(this, _KycController_sumsubLauncher, "f").isAvailable()) {
610
+ const error = 'SumSub SDK is not available in this runtime.';
611
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
612
+ state.sumsub.status = 'failed';
613
+ state.sumsub.result = { error };
614
+ });
615
+ throw new Error(error);
616
+ }
617
+ // Capture the flow generation so each async step can detect a `reset()`
618
+ // that lands mid-flight and avoid writing stale sub-flow state (or, worse,
619
+ // presenting the SDK) on a controller that is now idle.
620
+ const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
621
+ try {
622
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
623
+ state.sumsub.status = 'creatingSession';
624
+ state.sumsub.result = null;
625
+ state.sumsub.sessionStatus = null;
626
+ });
627
+ const jwtToken = MOCK_JWT_TOKEN;
628
+ // Establish a per-session X25519 keypair and exchange our public half for
629
+ // the server's wrapping key. The private half stays on the device and is
630
+ // used to derive the shared secret that seals the data_encryption_key.
631
+ const sessionClientPrivateKey = ed25519_1.x25519.utils.randomSecretKey();
632
+ const sessionClientPublicKey = ed25519_1.x25519.getPublicKey(sessionClientPrivateKey);
633
+ const wrappingKey = await this.messenger.call('KycService:getWrappingKey', { sessionClientPublicKey: (0, encoding_js_1.toBase64Url)(sessionClientPublicKey) });
634
+ // Verify the jwtChain against Fractal's JWKS, then confirm the returned
635
+ // sessionServerPublicKey matches the value attested inside the verified
636
+ // JWT payload before trusting it for key wrapping.
637
+ const { keys } = await this.messenger.call('KycService:fetchJwks');
638
+ const jwtChainPayload = (0, jwtChain_js_1.verifyJwtChain)(keys, wrappingKey.jwtChain);
639
+ if (jwtChainPayload.sessionServerPublicKeyX !==
640
+ wrappingKey.sessionServerPublicKey.x) {
641
+ throw new Error('sessionServerPublicKey does not match the verified jwtChain payload (sessionServerPublicKeyX).');
642
+ }
643
+ // Derive the data_encryption_key from the local_user_secret and wrap it
644
+ // for the session server. Only the wrapped (encrypted) key ever leaves
645
+ // the device.
646
+ const localUserSecret = await (0, localUserSecret_js_1.getOrCreateLocalUserSecret)(__classPrivateFieldGet(this, _KycController_instances, "m", _KycController_localUserSecretStore).call(this));
647
+ const clientMaterial = (0, deriveClientMaterial_js_1.deriveClientMaterial)(localUserSecret);
648
+ const wrappedEncryptionKey = {
649
+ sessionId: wrappingKey.id,
650
+ ...(0, wrapEncryptionKey_js_1.wrapEncryptionKey)(sessionClientPrivateKey, wrappingKey.sessionServerPublicKey.x, clientMaterial.dataEncryptionKey),
651
+ };
652
+ // Mint a read-only `ukyc_capability_token` for the session. Only the
653
+ // client holds the signing key derived from `local_user_secret`, so only
654
+ // the client can mint it; scoping it to `read` means it authorizes later
655
+ // storage reads without granting write or delete access.
656
+ const ukycCapabilityToken = (0, storageAccessToken_js_1.signStorageAccessToken)({
657
+ material: clientMaterial,
658
+ operations: ['read'],
659
+ expiresAt: new Date(Date.now() + UKYC_CAPABILITY_TOKEN_TTL_MS),
660
+ });
661
+ const { sessionId, kycStatus, finalStatus } = await this.messenger.call('KycService:createUkycSession', {
662
+ jwtToken,
663
+ vendorMetadata: {
664
+ moonPayAccessToken: this.state.accessToken,
665
+ moonPayUserId: this.state.moonpayCustomerId,
666
+ },
667
+ wrappedEncryptionKey,
668
+ ukycCapabilityToken,
669
+ });
670
+ // A user who already finished the journey can return to a session the
671
+ // relay has already approved (`kycStatus`) while the vendor is still
672
+ // finalizing its own decision (`finalStatus`). There is nothing left to
673
+ // verify, so stop here and surface a message rather than launching the
674
+ // SDK again.
675
+ if (kycStatus === KYC_STATUSES.approved &&
676
+ finalStatus === KYC_STATUSES.pending) {
677
+ const stillCurrent = __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
678
+ state.sumsub.status = 'vendorProcessing';
679
+ state.sumsub.sessionId = sessionId;
680
+ state.statusMessage = VENDOR_PROCESSING_MESSAGE;
681
+ });
682
+ return stillCurrent ? { kycStatus, finalStatus } : {};
683
+ }
684
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
685
+ state.sumsub.status = 'fetchingToken';
686
+ state.sumsub.sessionId = sessionId;
687
+ });
688
+ const { applicantAccessToken } = await this.messenger.call('KycService:createJourney', sessionId);
689
+ // A reset() may have landed while the session/token was being prepared.
690
+ // Gate the `launching` write and the decision to open the SDK behind a
691
+ // single generation check: `#updateIfCurrent` only writes when still
692
+ // current and reports whether it did. Since there is no `await` between
693
+ // this check and `launch` below, a successful result guarantees the SDK
694
+ // is never presented on a flow that a concurrent reset() returned to idle.
695
+ const stillCurrent = __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
696
+ state.sumsub.status = 'launching';
697
+ state.sumsub.applicantAccessToken = applicantAccessToken;
698
+ });
699
+ if (!stillCurrent) {
700
+ return {};
701
+ }
702
+ // Track whether the SDK ever reported a successful completion. A resolved
703
+ // `launch` alone does not imply success — the applicant may have
704
+ // abandoned the flow or the SDK may have reported a non-success outcome.
705
+ let reachedCompletion = false;
706
+ const result = await __classPrivateFieldGet(this, _KycController_sumsubLauncher, "f").launch({
707
+ applicantAccessToken,
708
+ onTokenExpiration: async () => {
709
+ // A reset() may have superseded this flow while the SDK stayed open.
710
+ // Refuse to refresh against the now-stale UKYC session rather than
711
+ // silently keeping an orphaned SDK alive.
712
+ if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
713
+ throw new Error('KYC flow was reset; SumSub session is no longer active.');
714
+ }
715
+ const refreshed = await this.messenger.call('KycService:createJourney', sessionId);
716
+ return refreshed.applicantAccessToken;
717
+ },
718
+ onStatusChange: (_prev, next) => {
719
+ if (next === SUMSUB_COMPLETED_STATUS) {
720
+ reachedCompletion = true;
721
+ }
722
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
723
+ state.sumsub.status =
724
+ next === SUMSUB_COMPLETED_STATUS ? 'complete' : 'inProgress';
725
+ });
726
+ },
727
+ locale: params?.locale ?? 'en',
728
+ debug: params?.debug ?? false,
729
+ });
730
+ // A resolved `launch` alone is not the final outcome: only a SDK-reported
731
+ // completion is worth polling for a verification decision. Anything else
732
+ // (abandonment, non-success) is `failed` and must not be polled.
733
+ const applied = __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
734
+ state.sumsub.status = reachedCompletion ? 'polling' : 'failed';
735
+ state.sumsub.result = result;
736
+ });
737
+ // Once the SDK completes, the authoritative verification decision comes
738
+ // from the UKYC backend, not the SDK result. Poll the session status
739
+ // until it reaches a terminal decision. Guard on `applied` so a `reset()`
740
+ // that landed during `launch` cannot start polling on an idle flow.
741
+ if (applied && reachedCompletion) {
742
+ if (sessionId) {
743
+ await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_startSessionStatusPolling).call(this, sessionId);
744
+ }
745
+ else {
746
+ // No session id to poll against; fall back to treating the SDK
747
+ // completion as the final outcome.
748
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
749
+ state.sumsub.status = 'complete';
750
+ });
751
+ }
752
+ }
753
+ return result;
754
+ }
755
+ catch (error) {
756
+ const result = { error: String(error) };
757
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
758
+ state.sumsub.status = 'failed';
759
+ state.sumsub.result = result;
760
+ });
761
+ return result;
762
+ }
763
+ }
764
+ /**
765
+ * Fetches the current UKYC session status for the active sub-flow and records
766
+ * it on state. Useful for a one-off refresh outside the automatic polling
767
+ * loop that {@link startSumSub} runs.
768
+ *
769
+ * @returns The fetched session status.
770
+ * @throws If there is no active SumSub session to query.
771
+ */
772
+ async getSessionStatus() {
773
+ const { sessionId } = this.state.sumsub;
774
+ if (!sessionId) {
775
+ throw new Error('Cannot fetch session status: no active SumSub session.');
776
+ }
777
+ // Capture the flow generation so a `reset()` landing while the request is
778
+ // in flight cannot write the result onto an idle controller.
779
+ const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
780
+ const sessionStatus = await this.messenger.call('KycService:getSessionStatus', { sessionId });
781
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
782
+ state.sumsub.sessionStatus = sessionStatus;
783
+ });
784
+ return sessionStatus;
785
+ }
786
+ /**
787
+ * Resets the flow to idle, clearing session tokens and sub-flow state while
788
+ * preserving persisted terms acceptance and the per-product cache.
789
+ */
790
+ reset() {
791
+ __classPrivateFieldSet(this, _KycController_authClientToken, null, "f");
792
+ // Stop any session-status polling so a late poll cannot write onto the
793
+ // now-idle controller.
794
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopPolling).call(this);
795
+ // Invalidate any in-flight async work started before this reset so its
796
+ // results are discarded rather than written onto the now-idle controller.
797
+ __classPrivateFieldSet(this, _KycController_generation, __classPrivateFieldGet(this, _KycController_generation, "f") + 1, "f");
798
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
799
+ state.phase = 'idle';
800
+ state.statusMessage = '';
801
+ state.error = null;
802
+ state.disclaimers = [];
803
+ state.disclaimersError = null;
804
+ state.sessionToken = null;
805
+ state.accessToken = null;
806
+ state.moonpayCustomerId = null;
807
+ state.activeProduct = null;
808
+ state.sumsub = {
809
+ status: 'idle',
810
+ result: null,
811
+ sessionId: null,
812
+ applicantAccessToken: null,
813
+ sessionStatus: null,
814
+ };
815
+ });
816
+ }
817
+ }
818
+ exports.KycController = KycController;
819
+ _KycController_sumsubLauncher = new WeakMap(), _KycController_keypair = new WeakMap(), _KycController_authClientToken = new WeakMap(), _KycController_generation = new WeakMap(), _KycController_sessionStatusPollIntervalMs = new WeakMap(), _KycController_pollTimer = new WeakMap(), _KycController_pollToken = new WeakMap(), _KycController_instances = new WeakSet(), _KycController_localUserSecretStore = function _KycController_localUserSecretStore() {
820
+ return {
821
+ get: async (path, entropySourceId) => this.messenger.call('UserStorageController:performGetStorage', path, entropySourceId),
822
+ set: async (path, value, entropySourceId) => this.messenger.call('UserStorageController:performSetStorage', path, value, entropySourceId),
823
+ };
824
+ }, _KycController_createSession =
825
+ /**
826
+ * Creates a vendor session from the currently stored terms + email.
827
+ */
828
+ async function _KycController_createSession() {
829
+ const { email, termsAcceptedAt, acceptedDisclaimerIds } = this.state;
830
+ if (!email) {
831
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing email for session creation.');
832
+ return;
833
+ }
834
+ if (!termsAcceptedAt || acceptedDisclaimerIds.length === 0) {
835
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, 'Missing terms acceptance for session creation.');
836
+ return;
837
+ }
838
+ // A new session invalidates any authentication carried over from a prior
839
+ // session. Clear the stale session token, access token, and auth-frame
840
+ // client token so `buildCheckFrameUrl` cannot return a URL bound to an old
841
+ // (or, on failure, invalid) session token, `buildAuthFrameUrl` cannot
842
+ // return a URL tied to an old client token, and `checkKycRequired` cannot
843
+ // run with an access token from an earlier authentication. The Check/Auth
844
+ // frames re-populate these for the new session. Because `sessionToken` is
845
+ // cleared here and only re-set on success, a failed creation leaves it
846
+ // `null` rather than resurrecting the previous session.
847
+ // Capture the flow generation so a `reset()` landing while the create
848
+ // request is in flight cannot resurrect a session (success) or overwrite
849
+ // the now-idle controller (failure). The synchronous update below runs
850
+ // before any `await`, so it needs no guard.
851
+ const generation = __classPrivateFieldGet(this, _KycController_generation, "f");
852
+ __classPrivateFieldSet(this, _KycController_authClientToken, null, "f");
853
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
854
+ state.error = null;
855
+ state.phase = 'session';
856
+ state.statusMessage = 'Creating session...';
857
+ state.sessionToken = null;
858
+ state.accessToken = null;
859
+ });
860
+ try {
861
+ const { sessionToken } = await this.messenger.call('KycService:createSession', { email, termsAcceptedAt, disclaimerIds: acceptedDisclaimerIds });
862
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_updateIfCurrent).call(this, generation, (state) => {
863
+ state.sessionToken = sessionToken;
864
+ state.phase = 'check';
865
+ state.statusMessage = 'Authenticating via Check frame...';
866
+ });
867
+ }
868
+ catch (error) {
869
+ console.error('Session creation failed:', error);
870
+ // A reset() superseded this flow while the request was in flight; leave
871
+ // the idle controller alone rather than forcing it back to `terms`.
872
+ if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
873
+ return;
874
+ }
875
+ // Invalidate the stored acceptance so the customer can retry. Also clear
876
+ // `activeProduct` so a later `acceptTermsAndStartSession` that omits a
877
+ // product cannot auto-run the KYC check / SumSub chain for this failed
878
+ // flow's product — matching how `initialize` starts from a clean product.
879
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
880
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearAcceptedTerms).call(this, state);
881
+ state.activeProduct = null;
882
+ state.error = `Session creation failed: ${String(error)}`;
883
+ state.statusMessage =
884
+ 'Session creation failed — accept the terms to try again.';
885
+ state.phase = 'terms';
886
+ });
887
+ await this.loadDisclaimers();
888
+ }
889
+ }, _KycController_clearAcceptedTerms = function _KycController_clearAcceptedTerms(state) {
890
+ state.termsAcceptedAt = null;
891
+ state.acceptedDisclaimerIds = [];
892
+ }, _KycController_handleCheckOutcome =
893
+ /**
894
+ * Applies a Check-frame outcome.
895
+ *
896
+ * @param status - The frame status.
897
+ * @param accessToken - The decrypted access token, if any.
898
+ * @param clientToken - The decrypted client token, if any.
899
+ */
900
+ async function _KycController_handleCheckOutcome(status, accessToken, clientToken) {
901
+ if (status === 'active' && accessToken) {
902
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
903
+ state.accessToken = accessToken;
904
+ state.phase = 'form';
905
+ state.statusMessage = 'Already authenticated. Review to submit.';
906
+ });
907
+ await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_continueAfterAuthentication).call(this);
908
+ return;
909
+ }
910
+ if (status === 'connectionRequired' && clientToken) {
911
+ __classPrivateFieldSet(this, _KycController_authClientToken, clientToken, "f");
912
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
913
+ state.phase = 'auth';
914
+ state.statusMessage = 'Verify your email via OTP in the Auth frame.';
915
+ });
916
+ return;
917
+ }
918
+ if (status === 'termsAcceptanceRequired') {
919
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_requireTermsReacceptance).call(this);
920
+ return;
921
+ }
922
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, `Check frame returned status: ${status}`);
923
+ }, _KycController_handleAuthOutcome =
924
+ /**
925
+ * Applies an Auth-frame outcome.
926
+ *
927
+ * @param status - The frame status.
928
+ * @param accessToken - The decrypted access token, if any.
929
+ */
930
+ async function _KycController_handleAuthOutcome(status, accessToken) {
931
+ if (status === 'active' && accessToken) {
932
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
933
+ state.accessToken = accessToken;
934
+ state.phase = 'form';
935
+ state.statusMessage = 'Authenticated. Review to submit.';
936
+ });
937
+ await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_continueAfterAuthentication).call(this);
938
+ return;
939
+ }
940
+ if (status === 'termsAcceptanceRequired') {
941
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_requireTermsReacceptance).call(this);
942
+ return;
943
+ }
944
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_fail).call(this, `Auth frame returned status: ${status}`);
945
+ }, _KycController_continueAfterAuthentication =
946
+ /**
947
+ * Continues the flow once authentication has completed (phase `form`).
948
+ *
949
+ * When the flow is scoped to a product (see {@link initialize}), the
950
+ * KYC-required check runs automatically, and — when KYC is required — the
951
+ * document-verification sub-flow is launched. When no product is set, this is
952
+ * a no-op and the flow stays at `form` for the consumer to drive manually.
953
+ *
954
+ * Errors are already recorded on state by `checkKycRequired` (`error`
955
+ * phase) and `startSumSub` (`sumsub.status = 'failed'`); this method swallows
956
+ * them so it can be awaited safely from the frame-message handler.
957
+ */
958
+ async function _KycController_continueAfterAuthentication() {
959
+ const product = this.state.activeProduct;
960
+ if (!product) {
961
+ return;
962
+ }
963
+ // Re-entry protection lives at the frame boundary: `handleFrameMessage`
964
+ // only honors a Check/Auth `complete` while `phase` matches, and both
965
+ // outcome handlers move `phase` to `form` before awaiting this method. A
966
+ // duplicate or late `complete` therefore lands after the phase moved on and
967
+ // is dropped before it can start a second continuation. Any writes here are
968
+ // additionally guarded by `#generation` (see `checkKycRequired` /
969
+ // `startSumSub`) so a `reset()` mid-continuation cannot corrupt state.
970
+ const kycRequired = await this.checkKycRequired({ product });
971
+ if (!kycRequired) {
972
+ return;
973
+ }
974
+ try {
975
+ await this.startSumSub();
976
+ }
977
+ catch {
978
+ // `startSumSub` already records `sumsub.status = 'failed'`; swallow the
979
+ // rethrown error (e.g. SDK unavailable) so the awaited continuation
980
+ // resolves cleanly rather than surfacing as an unhandled rejection.
981
+ }
982
+ }, _KycController_requireTermsReacceptance = function _KycController_requireTermsReacceptance() {
983
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
984
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_clearAcceptedTerms).call(this, state);
985
+ state.phase = 'terms';
986
+ state.statusMessage =
987
+ 'The vendor updated its Terms of Use — please re-accept.';
988
+ });
989
+ }, _KycController_startSessionStatusPolling =
990
+ /**
991
+ * Begins polling the UKYC session status until a terminal decision is
992
+ * reached. The first poll runs immediately (and is awaited by
993
+ * {@link startSumSub}); subsequent polls are scheduled every
994
+ * `#sessionStatusPollIntervalMs`.
995
+ *
996
+ * @param sessionId - The UKYC session id to poll.
997
+ * @returns A promise that resolves once the first poll settles.
998
+ */
999
+ async function _KycController_startSessionStatusPolling(sessionId) {
1000
+ // Supersede any prior loop and claim a fresh token for this one. Because
1001
+ // `#stopPolling` bumps the token, any in-flight poll from a previous loop
1002
+ // sees a mismatch and neither writes state nor reschedules.
1003
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopPolling).call(this);
1004
+ const token = __classPrivateFieldGet(this, _KycController_pollToken, "f");
1005
+ const tick = async () => {
1006
+ const shouldStop = await __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_pollSessionStatusOnce).call(this, sessionId, token);
1007
+ if (shouldStop) {
1008
+ return;
1009
+ }
1010
+ __classPrivateFieldSet(this, _KycController_pollTimer, setTimeout(() => {
1011
+ __classPrivateFieldSet(this, _KycController_pollTimer, null, "f");
1012
+ // `tick` swallows its own errors (see `#pollSessionStatusOnce`) and
1013
+ // therefore never rejects, so this fire-and-forget scheduled poll
1014
+ // cannot surface as an unhandled rejection.
1015
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
1016
+ tick();
1017
+ }, __classPrivateFieldGet(this, _KycController_sessionStatusPollIntervalMs, "f")), "f");
1018
+ };
1019
+ await tick();
1020
+ }, _KycController_pollSessionStatusOnce =
1021
+ /**
1022
+ * Performs a single session-status poll: fetches the status, records it, and
1023
+ * resolves the sub-flow when the status is terminal.
1024
+ *
1025
+ * Transient errors are swallowed so the loop keeps polling; the last good
1026
+ * `sessionStatus` is deliberately preserved rather than being overwritten
1027
+ * with the error.
1028
+ *
1029
+ * @param sessionId - The UKYC session id to poll.
1030
+ * @param token - The polling token captured when the loop started.
1031
+ * @returns `true` when the loop should stop (terminal status or superseded
1032
+ * by a reset / new sub-flow), `false` when it should keep polling.
1033
+ */
1034
+ async function _KycController_pollSessionStatusOnce(sessionId, token) {
1035
+ try {
1036
+ const sessionStatus = await this.messenger.call('KycService:getSessionStatus', { sessionId });
1037
+ // Superseded while the request was in flight — drop the result.
1038
+ if (__classPrivateFieldGet(this, _KycController_pollToken, "f") !== token) {
1039
+ return true;
1040
+ }
1041
+ const isTerminal = TERMINAL_SESSION_STATUSES.has(sessionStatus.finalStatus);
1042
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1043
+ state.sumsub.sessionStatus = sessionStatus;
1044
+ if (isTerminal) {
1045
+ state.sumsub.status = SUCCESSFUL_SESSION_STATUSES.has(sessionStatus.finalStatus)
1046
+ ? 'complete'
1047
+ : 'failed';
1048
+ }
1049
+ });
1050
+ if (isTerminal) {
1051
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_stopPolling).call(this);
1052
+ }
1053
+ return isTerminal;
1054
+ }
1055
+ catch {
1056
+ // Keep polling on transient errors, preserving the last good status.
1057
+ // Stop only when a reset / new sub-flow superseded this loop.
1058
+ return __classPrivateFieldGet(this, _KycController_pollToken, "f") !== token;
1059
+ }
1060
+ }, _KycController_stopPolling = function _KycController_stopPolling() {
1061
+ __classPrivateFieldSet(this, _KycController_pollToken, __classPrivateFieldGet(this, _KycController_pollToken, "f") + 1, "f");
1062
+ if (__classPrivateFieldGet(this, _KycController_pollTimer, "f") !== null) {
1063
+ clearTimeout(__classPrivateFieldGet(this, _KycController_pollTimer, "f"));
1064
+ __classPrivateFieldSet(this, _KycController_pollTimer, null, "f");
1065
+ }
1066
+ }, _KycController_updateIfCurrent = function _KycController_updateIfCurrent(generation, updater) {
1067
+ if (__classPrivateFieldGet(this, _KycController_generation, "f") !== generation) {
1068
+ return false;
1069
+ }
1070
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, updater);
1071
+ return true;
1072
+ }, _KycController_applyUpdate = function _KycController_applyUpdate(updater) {
1073
+ this.update((state) => {
1074
+ // `@ts-expect-error` cannot be used: ts-bridge does not surface
1075
+ // TS2589, so the directive is unused and fails the build.
1076
+ // type issue only happens at the IDE level.
1077
+ updater(state);
1078
+ });
1079
+ }, _KycController_fail = function _KycController_fail(message) {
1080
+ __classPrivateFieldGet(this, _KycController_instances, "m", _KycController_applyUpdate).call(this, (state) => {
1081
+ state.error = message;
1082
+ state.phase = 'error';
1083
+ });
1084
+ };
1085
+ //# sourceMappingURL=KycController.cjs.map