@metamask-previews/kyc-controller 0.0.0-preview-4f4c98e → 0.0.0-preview-eb263b0ee

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