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