@dynamic-labs-wallet/browser-wallet-client 0.0.354 → 0.1.0-request-signing

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.
package/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import { AuthMode, getEnvironmentFromUrl, IFRAME_DOMAIN_MAP, WalletOperation } from '@dynamic-labs-wallet/core';
1
+ import { WaasChainEnum, AuthMode, IFRAME_DOMAIN_MAP, getEnvironmentFromUrl, generateUUID, WalletOperation, pickSignerTarget } from '@dynamic-labs-wallet/core';
2
2
  export { AuthMode, MPC_RELAY_PREPROD_API_URL, MPC_RELAY_PROD_API_URL, ThresholdSignatureScheme, WalletOperation } from '@dynamic-labs-wallet/core';
3
3
  import { createRequestChannel, parseMessageTransportData, applyDefaultMessageOrigin, createMessageTransport, applyRecoveryManager, makeWaitForUnblock } from '@dynamic-labs/message-transport';
4
4
  import { Logger } from '@dynamic-labs/logger';
@@ -14,65 +14,225 @@ function _extends() {
14
14
  return _extends.apply(this, arguments);
15
15
  }
16
16
 
17
- class iframeMessageHandler {
17
+ const limitKeys = [
18
+ 'maxGas',
19
+ 'maxFeePerGas',
20
+ 'maxPriorityFeePerGas',
21
+ 'maxTotalFee'
22
+ ];
23
+ const isHex = (value)=>typeof value === 'string' && /^0x(?:[0-9a-f]{2})*$/.test(value);
24
+ const isTransactionIntent = (intent)=>intent.operation.kind === 'transaction';
25
+ const isSvmTransactionIntent = (intent)=>intent.operation.kind === 'transaction' && intent.operation.chainName === 'SVM';
26
+ const isEvmTransactionIntent = (intent)=>intent.operation.kind === 'transaction' && intent.operation.chainName === 'EVM';
27
+ const isTronTransactionIntent = (intent)=>intent.operation.kind === 'transaction' && intent.operation.chainName === 'TRON';
28
+ const isStellarTransactionIntent = (intent)=>intent.operation.kind === 'transaction' && intent.operation.chainName === 'STELLAR';
29
+ const isBtcTransactionIntent = (intent)=>intent.operation.kind === 'transaction' && intent.operation.chainName === 'BTC';
30
+ const assertMatches = (matches, message)=>{
31
+ if (!matches) throw new Error(message);
32
+ };
33
+ const hasLifetime = (lifetime, refreshable)=>{
34
+ if (refreshable === undefined) return lifetime === undefined;
35
+ const keys = lifetime && typeof lifetime === 'object' ? Object.keys(lifetime) : [];
36
+ return keys.length === 1 && lifetime.refreshable === refreshable;
37
+ };
38
+ const hasMatchingMetadata = (intent, request)=>{
39
+ const sameAddress = request.chainName === 'EVM' ? intent.accountAddress.toLowerCase() === request.accountAddress.toLowerCase() : intent.accountAddress === request.accountAddress;
40
+ return Object.values(WaasChainEnum).includes(request.chainName) && intent.actionType === 'waasSigningQuorumApprove' && Boolean(intent.intentId) && Number.isFinite(Date.parse(intent.createdAt)) && sameAddress && intent.businessAccountId === request.businessAccountId && intent.initiatorUserId === request.initiatorUserId && Boolean(intent.walletId) && (!request.walletId || intent.walletId === request.walletId) && intent.completeBy === request.completeBy && intent.operation.chainName === request.chainName && intent.operation.kind === request.kind;
41
+ };
42
+ const hasValidSvmHeader = (intent)=>{
43
+ const { header, staticAccountKeys } = intent.operation;
44
+ return Number.isInteger(header.numRequiredSignatures) && header.numRequiredSignatures >= 1 && header.numRequiredSignatures <= staticAccountKeys.length && Number.isInteger(header.numReadonlySignedAccounts) && header.numReadonlySignedAccounts >= 0 && header.numReadonlySignedAccounts < header.numRequiredSignatures && Number.isInteger(header.numReadonlyUnsignedAccounts) && header.numReadonlyUnsignedAccounts >= 0 && header.numReadonlyUnsignedAccounts <= staticAccountKeys.length - header.numRequiredSignatures;
45
+ };
46
+ const hasValidSvmInstructions = (intent)=>{
47
+ const { instructions, staticAccountKeys } = intent.operation;
48
+ const isIndex = (value)=>Number.isInteger(value) && value >= 0 && value < staticAccountKeys.length;
49
+ return instructions.every((instruction)=>isIndex(instruction.programIdIndex) && instruction.accountKeyIndexes.every(isIndex) && isHex(instruction.data));
50
+ };
51
+ const assertSvmTransactionMatchesRequest = (intent, request)=>{
52
+ var _request_chainId;
53
+ const { operation } = intent;
54
+ const isBase58 = (value)=>/^[1-9A-HJ-NP-Za-km-z]+$/.test(value);
55
+ assertMatches(request.chainName === 'SVM' && Boolean(request.chainId) && ((_request_chainId = request.chainId) == null ? void 0 : _request_chainId.trim()) === request.chainId && operation.chainId === request.chainId && request.refreshLimits === undefined && !request.refreshableNonce && intent.limits === undefined && hasLifetime(intent.lifetime, 'blockhash') && (operation.messageVersion === 'legacy' || operation.messageVersion === 'v0') && operation.staticAccountKeys.length > 0 && operation.staticAccountKeys.every(isBase58) && operation.feePayer === request.accountAddress && operation.feePayer === operation.staticAccountKeys[0] && hasValidSvmHeader(intent) && hasValidSvmInstructions(intent), 'Prepared SVM transaction signing intent is malformed');
56
+ };
57
+ // The intent describes the network in decimal; a request may name it in hexadecimal.
58
+ const toDecimalChainId = (chainId)=>chainId && /^0x[\da-f]+$/i.test(chainId) ? BigInt(chainId).toString() : chainId;
59
+ const assertTronTransactionMatchesRequest = (intent, request)=>{
60
+ const { operation } = intent;
61
+ // Wallet-service parses the transaction it signs and rejects any mismatch with
62
+ // the approved operation, so the contract fields are not re-derived here.
63
+ assertMatches(request.chainName === 'TRON' && Boolean(request.chainId) && operation.chainId === toDecimalChainId(request.chainId) && request.refreshLimits === undefined && !request.refreshableNonce && intent.limits === undefined && hasLifetime(intent.lifetime, 'expiration') && operation.from === request.accountAddress, 'Prepared TRON transaction signing intent is malformed');
64
+ };
65
+ const assertStellarTransactionMatchesRequest = (intent, request)=>{
66
+ const { operation } = intent;
67
+ assertMatches(request.chainName === 'STELLAR' && Boolean(request.chainId) && operation.chainId === request.chainId && request.refreshLimits === undefined && !request.refreshableNonce && intent.limits === undefined && hasLifetime(intent.lifetime, 'expiration') && operation.source === request.accountAddress, 'Prepared Stellar transaction signing intent is malformed');
68
+ };
69
+ const BTC_HASH = /^[0-9a-f]{64}$/;
70
+ const DECIMAL = /^(0|[1-9]\d*)$/;
71
+ const HEX_BYTES = /^(?:[0-9a-f]{2})*$/;
72
+ const hasValidBtcOperationFields = ({ operation })=>BTC_HASH.test(operation.txid) && DECIMAL.test(operation.feeSats) && Array.isArray(operation.outputs) && operation.outputs.length > 0 && operation.outputs.every(({ script, valueSats })=>HEX_BYTES.test(script) && DECIMAL.test(valueSats)) && Array.isArray(operation.sighashes) && operation.sighashes.length > 0 && operation.sighashes.every((sighash)=>BTC_HASH.test(sighash));
73
+ const assertBtcTransactionMatchesRequest = (intent, request)=>{
74
+ var _request_bitcoinConfig;
75
+ // Wallet-service re-derives the transaction from the PSBT it signs and rejects any
76
+ // mismatch with the approved operation, so the outputs and hashes are not re-derived here.
77
+ assertMatches(request.chainName === 'BTC' && intent.operation.chainId === (((_request_bitcoinConfig = request.bitcoinConfig) == null ? void 0 : _request_bitcoinConfig.network) === 'testnet' ? '2' : '1') && request.refreshLimits === undefined && !request.refreshableNonce && intent.limits === undefined && hasLifetime(intent.lifetime, undefined) && hasValidBtcOperationFields(intent), 'Prepared BTC transaction signing intent is malformed');
78
+ };
79
+ const assertEvmTransactionMatchesRequest = (intent, request)=>{
80
+ if (request.chainName !== 'EVM') throw new Error('Unsupported transaction signing intent');
81
+ const { operation, limits } = intent;
82
+ if (!limits) throw new Error('Prepared transaction signing intent is malformed');
83
+ assertMatches(hasLifetime(intent.lifetime, request.refreshableNonce ? 'nonce' : undefined), 'Transaction lifetime does not match request');
84
+ assertMatches(operation.from === intent.accountAddress.toLowerCase(), 'Transaction signer does not match request');
85
+ assertMatches(!request.chainId || operation.chainId === request.chainId, 'Transaction chain does not match request');
86
+ assertMatches(!request.refreshLimits || limitKeys.every((key)=>{
87
+ var _request_refreshLimits;
88
+ return limits[key] === ((_request_refreshLimits = request.refreshLimits) == null ? void 0 : _request_refreshLimits[key]);
89
+ }), 'Transaction signing limits do not match request');
90
+ // Wallet-service parses the transaction it signs and rejects any mismatch with
91
+ // the approved operation, so the transaction fields are not re-derived here.
92
+ };
93
+ const assertTransactionIntentMatchesRequest = (intent, request)=>{
94
+ if (request.kind !== 'transaction') {
95
+ throw new Error('Unsupported transaction signing intent');
96
+ }
97
+ if (isSvmTransactionIntent(intent)) return assertSvmTransactionMatchesRequest(intent, request);
98
+ if (isTronTransactionIntent(intent)) return assertTronTransactionMatchesRequest(intent, request);
99
+ if (isStellarTransactionIntent(intent)) return assertStellarTransactionMatchesRequest(intent, request);
100
+ if (isBtcTransactionIntent(intent)) return assertBtcTransactionMatchesRequest(intent, request);
101
+ if (!isEvmTransactionIntent(intent)) {
102
+ throw new Error('Unsupported transaction signing intent');
103
+ }
104
+ return assertEvmTransactionMatchesRequest(intent, request);
105
+ };
106
+ const assertExactOperationMatchesRequest = ({ intent, request, preparedPayload })=>{
107
+ const { operation } = intent;
108
+ assertMatches(preparedPayload !== undefined && operation.payload === preparedPayload, 'Prepared signing intent payload does not match request');
109
+ assertMatches(intent.limits === undefined, 'Exact signing intent cannot include refresh limits');
110
+ assertMatches(hasLifetime(intent.lifetime, undefined), 'Exact signing intent cannot include a lifetime');
111
+ if (operation.kind === 'message') {
112
+ assertMatches(request.kind === 'message' && operation.message === request.message, 'Prepared signing intent message does not match request');
113
+ return;
114
+ }
115
+ if (operation.kind === 'typedData') {
116
+ assertMatches(request.kind === 'typedData' && request.chainName === 'EVM' && Boolean(request.typedData) && operation.typedData === request.typedData, 'Prepared signing intent typed data does not match request');
117
+ return;
118
+ }
119
+ if (operation.kind === 'eip7702Auth') {
120
+ assertMatches(request.kind === 'eip7702Auth' && request.chainName === 'EVM' && operation.eip7702Auth.address === request.eip7702Auth.address && operation.eip7702Auth.chainId === request.eip7702Auth.chainId && operation.eip7702Auth.nonce === request.eip7702Auth.nonce, 'Prepared EIP-7702 authorization does not match request');
121
+ return;
122
+ }
123
+ const rawSign = operation.rawSign;
124
+ assertMatches(request.kind === 'raw' && (rawSign == null ? void 0 : rawSign.payload) === request.rawSign.payload && rawSign.hashFunction === request.rawSign.hashFunction && rawSign.prefix === request.rawSign.prefix, 'Prepared raw signing intent does not match request');
125
+ };
126
+ const assertPreparedSigningIntentMatchesRequest = ({ intent, request, preparedPayload })=>{
127
+ assertMatches(hasMatchingMetadata(intent, request), 'Prepared signing intent does not match request');
128
+ if (isTransactionIntent(intent)) {
129
+ assertTransactionIntentMatchesRequest(intent, request);
130
+ return;
131
+ }
132
+ assertExactOperationMatchesRequest({
133
+ intent,
134
+ request,
135
+ preparedPayload
136
+ });
137
+ };
138
+
139
+ function _object_without_properties_loose(source, excluded) {
140
+ if (source == null) return {};
141
+ var target = {};
142
+ var sourceKeys = Object.keys(source);
143
+ var key, i;
144
+ for(i = 0; i < sourceKeys.length; i++){
145
+ key = sourceKeys[i];
146
+ if (excluded.indexOf(key) >= 0) continue;
147
+ target[key] = source[key];
148
+ }
149
+ return target;
150
+ }
151
+
152
+ class IframeMessageHandler {
153
+ async request(requestName, ...params) {
154
+ const response = await this.requestChannel.request(requestName, ...params);
155
+ this.handleIframeMessageResponseError(response);
156
+ return response;
157
+ }
18
158
  // Handle error response from iframe message handler
19
159
  handleIframeMessageResponseError(response) {
20
160
  if (typeof response === 'object' && response !== null && 'error' in response) {
21
- throw new Error(String(response.error));
161
+ const error = new Error(String(response.error));
162
+ if ('name' in response && typeof response.name === 'string') {
163
+ error.name = response.name;
164
+ }
165
+ throw error;
22
166
  }
23
167
  }
24
168
  async getWallets(request) {
25
- const response = await this.requestChannel.request('getWallets', request);
26
- this.handleIframeMessageResponseError(response);
27
- return response;
169
+ return this.request('getWallets', request);
28
170
  }
29
171
  async getAllWallets(request) {
30
- const response = await this.requestChannel.request('getAllWallets', request);
31
- this.handleIframeMessageResponseError(response);
32
- return response;
172
+ return this.request('getAllWallets', request);
33
173
  }
34
174
  async getWallet(request) {
35
- const response = await this.requestChannel.request('getWallet', request);
36
- this.handleIframeMessageResponseError(response);
37
- return response;
175
+ return this.request('getWallet', request);
176
+ }
177
+ async createBusinessAccount(request) {
178
+ return this.request('createBusinessAccount', request);
179
+ }
180
+ async listBusinessAccounts(request) {
181
+ return this.request('listBusinessAccounts', request);
182
+ }
183
+ async getBusinessAccount(request) {
184
+ return this.request('getBusinessAccount', request);
185
+ }
186
+ async linkWalletToBusinessAccount(request) {
187
+ return this.request('linkWalletToBusinessAccount', request);
188
+ }
189
+ async addBusinessAccountMember(request) {
190
+ return this.request('addBusinessAccountMember', request);
191
+ }
192
+ async addBusinessAccountSigner(request) {
193
+ return this.request('addBusinessAccountSigner', request);
194
+ }
195
+ async reshareToNewSignerShareSet(request) {
196
+ return this.request('reshareToNewSignerShareSet', request);
38
197
  }
39
198
  async createWalletAccount(request) {
40
- const response = await this.requestChannel.request('createWalletAccount', request);
41
- this.handleIframeMessageResponseError(response);
42
- return response;
199
+ return this.request('createWalletAccount', request);
43
200
  }
44
201
  async requiresPasswordForOperation(request) {
45
- const response = await this.requestChannel.request('requiresPasswordForOperation', request);
46
- this.handleIframeMessageResponseError(response);
47
- return response;
202
+ return this.request('requiresPasswordForOperation', request);
48
203
  }
49
204
  async signMessage(request) {
50
- const response = await this.requestChannel.request('signMessage', request);
51
- this.handleIframeMessageResponseError(response);
52
- return response;
205
+ return this.request('signMessage', request);
206
+ }
207
+ async createConfidentialSeed(request) {
208
+ return this.request('createConfidentialSeed', request);
209
+ }
210
+ async signConfidentialTransfer(request) {
211
+ return this.request('signConfidentialTransfer', request);
212
+ }
213
+ async getConfidentialBalance(request) {
214
+ return this.request('getConfidentialBalance', request);
215
+ }
216
+ async prepareSigningIntent(request) {
217
+ return this.request('prepareSigningIntent', request);
218
+ }
219
+ async resumeSigningIntent(request) {
220
+ return this.request('resumeSigningIntent', request);
53
221
  }
54
222
  async signRawMessage(request) {
55
- const response = await this.requestChannel.request('signRawMessage', request);
56
- this.handleIframeMessageResponseError(response);
57
- return response;
223
+ return this.request('signRawMessage', request);
58
224
  }
59
225
  async signTransaction(request) {
60
- const response = await this.requestChannel.request('signTransaction', request);
61
- this.handleIframeMessageResponseError(response);
62
- return response;
226
+ return this.request('signTransaction', request);
63
227
  }
64
228
  async isPasswordEncrypted(request) {
65
- const response = await this.requestChannel.request('isPasswordEncrypted', request);
66
- this.handleIframeMessageResponseError(response);
67
- return response;
229
+ return this.request('isPasswordEncrypted', request);
68
230
  }
69
231
  async backupKeySharesToGoogleDrive(request) {
70
- const response = await this.requestChannel.request('backupKeySharesToGoogleDrive', request);
71
- this.handleIframeMessageResponseError(response);
232
+ await this.request('backupKeySharesToGoogleDrive', request);
72
233
  }
73
234
  async backupKeySharesToICloud(request) {
74
- const response = await this.requestChannel.request('backupKeySharesToICloud', request);
75
- this.handleIframeMessageResponseError(response);
235
+ await this.request('backupKeySharesToICloud', request);
76
236
  }
77
237
  async displayICloudSignIn(chainName) {
78
238
  await this.requestChannel.request('displayICloudSignIn', {
@@ -88,90 +248,100 @@ class iframeMessageHandler {
88
248
  });
89
249
  }
90
250
  async delegateKeyShares(request) {
91
- const response = await this.requestChannel.request('delegateKeyShares', request);
92
- this.handleIframeMessageResponseError(response);
251
+ await this.request('delegateKeyShares', request);
252
+ }
253
+ async offlineRecovery(request) {
254
+ await this.request('offlineRecovery', request);
93
255
  }
94
256
  async revokeDelegation(request) {
95
- const response = await this.requestChannel.request('revokeDelegation', request);
96
- this.handleIframeMessageResponseError(response);
257
+ await this.request('revokeDelegation', request);
97
258
  }
98
259
  async exportClientKeysharesFromGoogleDrive(request) {
99
- const response = await this.requestChannel.request('exportClientKeysharesFromGoogleDrive', request);
100
- this.handleIframeMessageResponseError(response);
260
+ await this.request('exportClientKeysharesFromGoogleDrive', request);
101
261
  }
102
262
  async refreshWalletAccountShares(request) {
103
- const response = await this.requestChannel.request('refreshWalletAccountShares', request);
104
- this.handleIframeMessageResponseError(response);
263
+ await this.request('refreshWalletAccountShares', request);
105
264
  }
106
265
  async reshare(request) {
107
- const response = await this.requestChannel.request('reshare', request);
108
- this.handleIframeMessageResponseError(response);
266
+ await this.request('reshare', request);
109
267
  }
110
268
  async exportPrivateKey(request) {
111
- const response = await this.requestChannel.request('exportPrivateKey', request);
112
- this.handleIframeMessageResponseError(response);
269
+ await this.request('exportPrivateKey', request);
270
+ }
271
+ async prepareExportIntent(request) {
272
+ return this.request('prepareExportIntent', request);
273
+ }
274
+ async prepareReshareIntent(request) {
275
+ return this.request('prepareReshareIntent', request);
113
276
  }
114
277
  async proveAleoTransaction(request) {
115
- const response = await this.requestChannel.request('proveAleoTransaction', request);
116
- this.handleIframeMessageResponseError(response);
117
- return response;
278
+ return this.request('proveAleoTransaction', request);
118
279
  }
119
280
  async findAleoOwnedRecords(request) {
120
- const response = await this.requestChannel.request('findAleoOwnedRecords', request);
121
- this.handleIframeMessageResponseError(response);
122
- return response;
281
+ return this.request('findAleoOwnedRecords', request);
123
282
  }
124
283
  async isAleoFeemasterCovered(request) {
125
- const response = await this.requestChannel.request('isAleoFeemasterCovered', request);
126
- this.handleIframeMessageResponseError(response);
127
- return Boolean(response);
284
+ return Boolean(await this.request('isAleoFeemasterCovered', request));
128
285
  }
129
286
  async verifyPassword(request) {
130
- const response = await this.requestChannel.request('verifyPassword', request);
131
- this.handleIframeMessageResponseError(response);
287
+ await this.request('verifyPassword', request);
132
288
  }
133
289
  async updatePassword(request) {
134
- const response = await this.requestChannel.request('updatePassword', request);
135
- this.handleIframeMessageResponseError(response);
290
+ return this.request('updatePassword', request);
136
291
  }
137
292
  async setPassword(request) {
138
- const response = await this.requestChannel.request('setPassword', request);
139
- this.handleIframeMessageResponseError(response);
293
+ return this.request('setPassword', request);
140
294
  }
141
295
  async importPrivateKey(request) {
142
- const response = await this.requestChannel.request('importPrivateKey', request);
143
- this.handleIframeMessageResponseError(response);
144
- return response;
296
+ return this.request('importPrivateKey', request);
297
+ }
298
+ async migrateFromFireblocks(request) {
299
+ return this.request('migrateFromFireblocks', request);
145
300
  }
146
301
  async sendAuthToken(token, authMode, traceContext) {
147
302
  return this.requestChannel.request('sendAuthToken', token, authMode, traceContext);
148
303
  }
149
304
  async exportClientKeyshares(request) {
150
- const response = await this.requestChannel.request('exportClientKeyshares', request);
151
- this.handleIframeMessageResponseError(response);
305
+ await this.request('exportClientKeyshares', request);
152
306
  }
153
307
  async offlineExportPrivateKey(request) {
154
- const response = await this.requestChannel.request('offlineExportPrivateKey', request);
155
- this.handleIframeMessageResponseError(response);
156
- return response;
308
+ return this.request('offlineExportPrivateKey', request);
157
309
  }
158
310
  async signTypedData(request) {
159
- const response = await this.requestChannel.request('signTypedData', request);
160
- this.handleIframeMessageResponseError(response);
161
- return response;
311
+ return this.request('signTypedData', request);
162
312
  }
163
313
  async cleanup() {
164
314
  return this.requestChannel.request('cleanup');
165
315
  }
166
316
  async getWalletRecoveryState(request) {
167
- const response = await this.requestChannel.request('getWalletRecoveryState', request);
168
- this.handleIframeMessageResponseError(response);
169
- return response;
317
+ return this.request('getWalletRecoveryState', request);
170
318
  }
171
319
  async unlockWallet(request) {
172
- const response = await this.requestChannel.request('unlockWallet', request);
173
- this.handleIframeMessageResponseError(response);
174
- return response;
320
+ return this.request('unlockWallet', request);
321
+ }
322
+ async lockWallets(request) {
323
+ return this.request('lockWallets', request);
324
+ }
325
+ async getPrivateBalance(request) {
326
+ return this.request('getPrivateBalance', request);
327
+ }
328
+ async getWalletProvider(request) {
329
+ return this.request('getWalletProvider', request);
330
+ }
331
+ async balanceWalletProviderTransaction(request) {
332
+ return this.request('balanceWalletProviderTransaction', request);
333
+ }
334
+ async registerDust(request) {
335
+ return this.request('registerDust', request);
336
+ }
337
+ async createTransferTransaction(request) {
338
+ return this.request('createTransferTransaction', request);
339
+ }
340
+ async submitTransaction(request) {
341
+ return this.request('submitTransaction', request);
342
+ }
343
+ async revertTransaction(request) {
344
+ return this.request('revertTransaction', request);
175
345
  }
176
346
  constructor(messageTransport){
177
347
  this.requestChannel = createRequestChannel(messageTransport);
@@ -180,8 +350,28 @@ class iframeMessageHandler {
180
350
 
181
351
  const logger = new Logger('DynamicWaasWalletClient');
182
352
 
353
+ const isOpaqueOrigin = (origin)=>!origin || origin === '' || origin === 'null';
354
+ const isNativeBridgeEvent = (event)=>event.source === null && isOpaqueOrigin(event.origin);
355
+ /**
356
+ * Validate the browser-supplied `origin` and `source` of an incoming message.
357
+ * Native WebView bridge events have an opaque origin and a null source.
358
+ * Messages from the iframe must come from the iframe's contentWindow and
359
+ * declare the iframe's origin.
360
+ *
361
+ * TODO: replace with `@dynamic-labs/message-transport/isMessageEventTrusted`
362
+ * once the wallet client is on a version that exports it.
363
+ */ const isTrustedIncomingMessage = (event, source, iframe, iframeOrigin)=>{
364
+ if (source === 'document') {
365
+ return isNativeBridgeEvent(event);
366
+ }
367
+ const isFromIframe = event.source === iframe.contentWindow && event.origin === iframeOrigin;
368
+ return isFromIframe || isNativeBridgeEvent(event);
369
+ };
183
370
  const setupMessageTransportBridge = (messageTransport, iframe, iframeOrigin)=>{
184
371
  const logger = new Logger('debug');
372
+ // A detached iframe keeps failing until the recovery manager rebuilds it,
373
+ // so only the first drop per detach gets logged.
374
+ let loggedIframeUnavailable = false;
185
375
  function hostListener(message) {
186
376
  if (message.origin !== 'host') return;
187
377
  // Detached iframe (relogin / RN modal unmount left a stale ref): log and
@@ -190,26 +380,34 @@ const setupMessageTransportBridge = (messageTransport, iframe, iframeOrigin)=>{
190
380
  // bridge. Throwing here would break that recovery flow because the
191
381
  // listener runs synchronously inside emit().
192
382
  if (!(iframe == null ? void 0 : iframe.contentWindow) || iframe.isConnected === false) {
193
- logger.error('Cannot send message to iframe: contentWindow is unavailable');
383
+ if (!loggedIframeUnavailable) {
384
+ loggedIframeUnavailable = true;
385
+ logger.error('Cannot send message to iframe: contentWindow is unavailable');
386
+ }
194
387
  return;
195
388
  }
196
389
  try {
197
390
  iframe.contentWindow.postMessage(message, iframeOrigin);
391
+ loggedIframeUnavailable = false;
198
392
  } catch (error) {
199
393
  // "Attempt to postMessage on disconnected port" (Firefox) — same path: log + drop.
200
394
  logger.error('Failed to post message to iframe:', error);
201
395
  }
202
396
  }
203
397
  messageTransport.on(hostListener);
204
- const handleIncomingMessage = (message)=>{
205
- const { data } = message;
206
- if (!data) return;
207
- if ((data == null ? void 0 : data.origin) !== 'webview') {
398
+ const handleIncomingMessage = (event, source)=>{
399
+ if (!isTrustedIncomingMessage(event, source, iframe, iframeOrigin)) {
400
+ logger.debug(`skipped message: untrusted ${source} event (origin: ${event.origin}, source mismatch)`);
208
401
  return;
209
402
  }
403
+ const { data } = event;
404
+ if (!data) return;
210
405
  if (typeof data !== 'object') {
211
406
  return;
212
407
  }
408
+ if ((data == null ? void 0 : data.origin) !== 'webview') {
409
+ return;
410
+ }
213
411
  try {
214
412
  const message = parseMessageTransportData(data);
215
413
  messageTransport.emit(message);
@@ -219,23 +417,38 @@ const setupMessageTransportBridge = (messageTransport, iframe, iframeOrigin)=>{
219
417
  }
220
418
  }
221
419
  };
420
+ const handleDocumentMessage = (event)=>handleIncomingMessage(event, 'document');
421
+ const handleWindowMessage = (event)=>handleIncomingMessage(event, 'window');
222
422
  /**
223
423
  * Handle incoming message from android client
224
424
  */ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
225
425
  // @ts-expect-error
226
- document.addEventListener('message', handleIncomingMessage);
426
+ document.addEventListener('message', handleDocumentMessage);
227
427
  /**
228
428
  * Handle incoming message from iOS client
229
- */ window.addEventListener('message', handleIncomingMessage);
429
+ */ window.addEventListener('message', handleWindowMessage);
230
430
  return ()=>{
231
431
  messageTransport.off(hostListener);
232
432
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
233
433
  // @ts-expect-error
234
- document.removeEventListener('message', handleIncomingMessage);
235
- window.removeEventListener('message', handleIncomingMessage);
434
+ document.removeEventListener('message', handleDocumentMessage);
435
+ window.removeEventListener('message', handleWindowMessage);
236
436
  };
237
437
  };
238
438
 
439
+ const NON_RETRYABLE_IFRAME_LOAD_ERROR_NAME = 'NonRetryableIframeLoadError';
440
+ /**
441
+ * Tags an iframe load failure that retrying cannot fix (e.g. the embedding
442
+ * page's CSP refusing to load our iframe) so IframeManager rejects the load
443
+ * immediately instead of waiting out the timeout and burning retries.
444
+ */ const createNonRetryableIframeLoadError = (message)=>{
445
+ const error = new Error(message);
446
+ error.name = NON_RETRYABLE_IFRAME_LOAD_ERROR_NAME;
447
+ return error;
448
+ };
449
+ // Name-based check (not instanceof) so the tag survives bundler module duplication.
450
+ const isNonRetryableIframeLoadError = (error)=>error instanceof Error && error.name === NON_RETRYABLE_IFRAME_LOAD_ERROR_NAME;
451
+
239
452
  const createIframeWaasSDKContainer = ()=>{
240
453
  let iframe = null;
241
454
  const messageHandlers = new Set();
@@ -272,19 +485,51 @@ const createIframeWaasSDKContainer = ()=>{
272
485
  }
273
486
  };
274
487
  const cspViolationListener = (event)=>{
275
- var _event_blockedURI, _event_violatedDirective, _event_violatedDirective1;
276
488
  const iframeOrigin = (iframe == null ? void 0 : iframe.src) ? new URL(iframe.src).origin : undefined;
277
- const affectsIframe = iframeOrigin && ((_event_blockedURI = event.blockedURI) == null ? void 0 : _event_blockedURI.includes(iframeOrigin)) || ((_event_violatedDirective = event.violatedDirective) == null ? void 0 : _event_violatedDirective.includes('frame-src')) || ((_event_violatedDirective1 = event.violatedDirective) == null ? void 0 : _event_violatedDirective1.includes('child-src'));
278
- if (!affectsIframe) return;
279
- logger.error('CSP violation detected that may affect iframe loading:', {
489
+ let blockedOrigin;
490
+ try {
491
+ blockedOrigin = event.blockedURI ? new URL(event.blockedURI).origin : undefined;
492
+ } catch (e) {
493
+ // blockedURI can be a non-URL keyword ("inline", "eval", "data", ...)
494
+ blockedOrigin = undefined;
495
+ }
496
+ // Violations for other origins (third-party widgets, analytics) are noise
497
+ // we never act on and dominated this log's volume — only OUR iframe
498
+ // origin is relevant.
499
+ if (!iframeOrigin || blockedOrigin !== iframeOrigin) return;
500
+ const context = {
280
501
  blockedURI: event.blockedURI,
281
502
  violatedDirective: event.violatedDirective,
503
+ disposition: event.disposition,
282
504
  originalPolicy: event.originalPolicy,
283
505
  sourceFile: event.sourceFile,
284
506
  lineNumber: event.lineNumber,
285
507
  columnNumber: event.columnNumber,
286
508
  iframeOrigin
287
- });
509
+ };
510
+ // Report-only policies (Content-Security-Policy-Report-Only) fire the
511
+ // same violation event but do NOT block anything — keep them visible and
512
+ // filterable without polluting error streams or aborting the load.
513
+ if (event.disposition === 'report') {
514
+ logger.info('Report-only CSP violation for the wallet iframe origin:', context);
515
+ return;
516
+ }
517
+ logger.error('CSP violation detected that may affect iframe loading:', context);
518
+ var _event_violatedDirective;
519
+ const directive = (_event_violatedDirective = event.violatedDirective) != null ? _event_violatedDirective : '';
520
+ const remediation = `the embedding page's Content-Security-Policy must allow ${iframeOrigin} ` + 'in both the frame-src (or child-src) and connect-src directives';
521
+ if (directive.includes('frame-src') || directive.includes('child-src')) {
522
+ // Hard block: the browser refuses to load the iframe at all, so the
523
+ // pending load can only end in a timeout. Fail it now with a
524
+ // non-retryable error — retrying cannot succeed until the CSP changes.
525
+ const message = `Dynamic wallet iframe blocked by CSP (${directive}): ${remediation}`;
526
+ logger.error(message);
527
+ fireError(createNonRetryableIframeLoadError(message));
528
+ } else if (directive.includes('connect-src')) {
529
+ // The iframe itself can still load, but requests to the wallet backend
530
+ // are blocked so wallet operations will fail. Warn — do not abort.
531
+ logger.warn(`Dynamic wallet requests blocked by CSP (connect-src): ${remediation}`);
532
+ }
288
533
  };
289
534
  return {
290
535
  async setUrl (url) {
@@ -365,6 +610,195 @@ const createIframeWaasSDKContainer = ()=>{
365
610
  };
366
611
  };
367
612
 
613
+ /**
614
+ * Cookie-mode isolation guard: the key-share iframe must never share an origin
615
+ * with the embedding page — a same-origin parent can read the iframe's DOM and
616
+ * storage directly, collapsing the boundary that keeps client key shares out of
617
+ * reach of host-page XSS. This only happens when the app itself is served from
618
+ * the cookie hostname (e.g. a reverse proxy routing both the app and Dynamic's
619
+ * API through one hostname), so refuse to boot instead of running without the
620
+ * boundary. No-op off-web (React Native), where no location/DOM access exists.
621
+ */ const assertIframeOriginIsolated = (iframeDomain)=>{
622
+ var _globalThis_location;
623
+ const hostOrigin = (_globalThis_location = globalThis.location) == null ? void 0 : _globalThis_location.origin;
624
+ if (!hostOrigin) {
625
+ return;
626
+ }
627
+ let iframeOrigin;
628
+ try {
629
+ iframeOrigin = new URL(iframeDomain).origin;
630
+ } catch (e) {
631
+ // Malformed baseApiUrl surfaces as a clearer iframe load failure later.
632
+ return;
633
+ }
634
+ if (iframeOrigin === hostOrigin) {
635
+ throw new Error(`Cookie auth misconfiguration: the wallet iframe origin (${iframeOrigin}) is the same as the host page origin. ` + 'The cookie domain must be a dedicated hostname CNAMEd to Dynamic (e.g. auth.example.com) that never serves ' + 'your application — a same-origin setup would let the host page read the wallet key-share storage.');
636
+ }
637
+ };
638
+ /**
639
+ * Resolve the wallet iframe domain from the API base URL: the
640
+ * environment-mapped Dynamic domain, or `baseApiUrl` itself in cookie auth
641
+ * mode (customer custom domains). Single source of truth shared by the
642
+ * IframeManager constructor and the public preconnect helper.
643
+ */ const resolveIframeDomain = ({ baseApiUrl, authMode })=>{
644
+ if (authMode === AuthMode.COOKIE) {
645
+ return baseApiUrl;
646
+ }
647
+ var _IFRAME_DOMAIN_MAP_getEnvironmentFromUrl;
648
+ return (_IFRAME_DOMAIN_MAP_getEnvironmentFromUrl = IFRAME_DOMAIN_MAP[getEnvironmentFromUrl(baseApiUrl)]) != null ? _IFRAME_DOMAIN_MAP_getEnvironmentFromUrl : null;
649
+ };
650
+
651
+ /**
652
+ * Warm the browser's connection to the iframe origin (DNS + TCP + TLS) by
653
+ * injecting `<link rel="preconnect">` (plus a `<link rel="dns-prefetch">`
654
+ * fallback) into the host document head, so a later iframe document fetch
655
+ * starts on a hot connection instead of paying connection-setup RTT inside
656
+ * the iframe load timeout window.
657
+ *
658
+ * Re-warms on every call: browsers drop unused preconnected sockets after
659
+ * ~10s and never re-process a link already in the DOM, so the links are
660
+ * replaced rather than skipped. No-op outside the DOM (React Native / SSR).
661
+ * The preconnect deliberately omits `crossorigin`: the iframe navigation and
662
+ * its same-origin subresources are credentialed fetches, which reuse the
663
+ * non-CORS connection a plain preconnect opens.
664
+ */ const preconnectIframeOrigin = (iframeUrl)=>{
665
+ var _document_getElementById, _document_getElementById1;
666
+ if (typeof document === 'undefined' || !document.head) return;
667
+ let origin;
668
+ try {
669
+ origin = new URL(iframeUrl).origin;
670
+ } catch (e) {
671
+ return;
672
+ }
673
+ const preconnectId = `dynamic-waas-preconnect-${origin}`;
674
+ const dnsPrefetchId = `dynamic-waas-dns-prefetch-${origin}`;
675
+ (_document_getElementById = document.getElementById(preconnectId)) == null ? void 0 : _document_getElementById.remove();
676
+ (_document_getElementById1 = document.getElementById(dnsPrefetchId)) == null ? void 0 : _document_getElementById1.remove();
677
+ const preconnect = document.createElement('link');
678
+ preconnect.id = preconnectId;
679
+ preconnect.rel = 'preconnect';
680
+ preconnect.href = origin;
681
+ document.head.appendChild(preconnect);
682
+ const dnsPrefetch = document.createElement('link');
683
+ dnsPrefetch.id = dnsPrefetchId;
684
+ dnsPrefetch.rel = 'dns-prefetch';
685
+ dnsPrefetch.href = origin;
686
+ document.head.appendChild(dnsPrefetch);
687
+ };
688
+ /**
689
+ * Public warmup entry point for host SDKs. Resolves the wallet iframe domain
690
+ * from the same inputs the wallet client constructor uses and preconnects to
691
+ * it.
692
+ *
693
+ * Call this when an embedded-wallet auth flow STARTS (email submitted, OTP
694
+ * verification begins) — not at wallet client construction, which happens
695
+ * milliseconds before the iframe mounts and leaves the warmup no runway.
696
+ * Safe to call repeatedly; each call re-warms the connection, which matters
697
+ * because an unused preconnect goes cold after ~10s.
698
+ */ const preconnectWaasIframe = ({ baseApiUrl, authMode = AuthMode.HEADER })=>{
699
+ const iframeDomain = resolveIframeDomain({
700
+ baseApiUrl,
701
+ authMode
702
+ });
703
+ if (iframeDomain) {
704
+ preconnectIframeOrigin(iframeDomain);
705
+ }
706
+ };
707
+
708
+ /**
709
+ * One `setupIframeRequestHandlers` call's worth of registrations, grouped by
710
+ * lifetime.
711
+ */ /** Unregisters every handler in `disposers` and empties the list. */ const drainDisposers = (disposers)=>{
712
+ disposers.forEach((unsubscribe)=>unsubscribe());
713
+ disposers.length = 0;
714
+ };
715
+ /** Unregisters both halves of a registration. */ const disposeAllHandlers = ({ disposeSessionHandlers, disposeStorageHandlers })=>{
716
+ disposeSessionHandlers();
717
+ disposeStorageHandlers();
718
+ };
719
+ /**
720
+ * Lifetime bookkeeping for the iframe → host ("reverse channel") request
721
+ * handlers one IframeManager has attached to the shared container.
722
+ *
723
+ * A page has one WaaS iframe but every client built on it stays bridged to it,
724
+ * so the reverse channel is first-response-wins: a superseded manager with a
725
+ * revoked session callback rejects `getSignedSessionId` instantly and beats the
726
+ * live client's round-trip. This registry is what lets such a manager leave the
727
+ * race (see {@link detach}) without disturbing the key-share handlers, which
728
+ * the iframe still calls back during teardown.
729
+ */ class IframeRequestHandlerRegistry {
730
+ get sessionHandlerCount() {
731
+ return this.sessionDisposers.length;
732
+ }
733
+ get storageHandlerCount() {
734
+ return this.storageDisposers.length;
735
+ }
736
+ /** Capture the current generations before awaiting the iframe. */ snapshot() {
737
+ return {
738
+ cleanupGeneration: this.cleanupGeneration,
739
+ detachGeneration: this.detachGeneration
740
+ };
741
+ }
742
+ /**
743
+ * Takes ownership of a registration whose setup started at `epoch`, keeping
744
+ * whichever halves are still legitimate, and reports whether the registration
745
+ * is the manager's current one (the caller's channel is only worth keeping
746
+ * then). The host doesn't await `initialize()`, so a detach or a cleanup can
747
+ * land while the iframe is still loading — which one moved decides:
748
+ *
749
+ * - **Torn down** (cleanup): keep nothing. The lists this would land on are
750
+ * already drained, so anything tracked here would stay attached to a
751
+ * logged-out manager forever.
752
+ * - **Superseded** (detach): the session handlers would put this manager back
753
+ * into the race, but its key-share handlers still answer honestly — and on a
754
+ * first initialization they are the only ones the page has.
755
+ * - **Neither**: track both.
756
+ */ adopt(epoch, registration) {
757
+ if (this.cleanupGeneration !== epoch.cleanupGeneration) {
758
+ disposeAllHandlers(registration);
759
+ return false;
760
+ }
761
+ if (this.detachGeneration !== epoch.detachGeneration) {
762
+ registration.disposeSessionHandlers();
763
+ this.storageDisposers.push(registration.disposeStorageHandlers);
764
+ return false;
765
+ }
766
+ this.sessionDisposers.push(registration.disposeSessionHandlers);
767
+ this.storageDisposers.push(registration.disposeStorageHandlers);
768
+ return true;
769
+ }
770
+ /**
771
+ * Stops answering the session-scoped requests, and nothing else. Safe to call
772
+ * repeatedly, and mid-initialization: a registration still in flight is
773
+ * adopted as "superseded".
774
+ */ detach() {
775
+ this.detachGeneration += 1;
776
+ drainDisposers(this.sessionDisposers);
777
+ }
778
+ /**
779
+ * First phase of a teardown: leave the session race immediately, and mark
780
+ * anything still initializing as torn down rather than merely superseded. The
781
+ * storage handlers stay until {@link disposeStorageHandlers}, because the
782
+ * iframe's own cleanup clears each wallet's shares over this channel.
783
+ */ markTornDown() {
784
+ this.cleanupGeneration += 1;
785
+ this.detach();
786
+ }
787
+ /** Second phase of a teardown: drop the key-share handlers, once the iframe has finished calling back. */ disposeStorageHandlers() {
788
+ drainDisposers(this.storageDisposers);
789
+ }
790
+ constructor(){
791
+ /**
792
+ * Lists, not single entries: `initializeMessageTransport` checks its guard
793
+ * *then* awaits, so one manager can end up registered on two transports that
794
+ * both answer, and overwriting would orphan the first.
795
+ */ this.sessionDisposers = [];
796
+ this.storageDisposers = [];
797
+ /** Bumped by {@link detach}. */ this.detachGeneration = 0;
798
+ /** Bumped by {@link markTornDown}. */ this.cleanupGeneration = 0;
799
+ }
800
+ }
801
+
368
802
  const FRAME_ANCESTORS_QUERY_PARAM = 'frameAncestors';
369
803
  /**
370
804
  * Builds the iframe message transport with the recovery + block decorators.
@@ -392,9 +826,32 @@ const FRAME_ANCESTORS_QUERY_PARAM = 'frameAncestors';
392
826
  });
393
827
  }
394
828
  class IframeManager {
395
- // Simply load the iframe from localhost
829
+ /**
830
+ * Apply constructor-provided overrides for the iframe load timeout and
831
+ * retry budget to the static singleton state. Writing to the statics keeps
832
+ * the timeout doubling logic in {@link resetSharedWaasSDKContainer}
833
+ * coherent across instances that share the same `iframeLoadPromise`.
834
+ *
835
+ * Invalid values (non-finite, out of range) are clamped or ignored rather
836
+ * than thrown — the iframe must still load even if a misconfigured host
837
+ * passes nonsense.
838
+ */ static applyLoadTuning({ iframeLoadTimeout, maxRetryAttempts }) {
839
+ if (typeof iframeLoadTimeout === 'number' && Number.isFinite(iframeLoadTimeout)) {
840
+ IframeManager.iframeLoadTimeout = Math.min(Math.max(iframeLoadTimeout, IframeManager.minIframeLoadTimeout), IframeManager.maxIframeLoadTimeout);
841
+ }
842
+ if (typeof maxRetryAttempts === 'number' && Number.isFinite(maxRetryAttempts)) {
843
+ IframeManager.maxRetryAttempts = Math.min(Math.max(Math.floor(maxRetryAttempts), 0), IframeManager.maxAllowedRetryAttempts);
844
+ }
845
+ }
846
+ // Boot the iframe. Eager hosts also authenticate the transport now (so the
847
+ // iframe self-recovers without a first op); lazy hosts defer that to first op.
396
848
  async initialize() {
397
- await this.doInitializeIframeCommunication();
849
+ if (this.eagerlyRecoverKeyShares) {
850
+ // Loads the iframe internally, then sends the auth token.
851
+ await this.initializeMessageTransport();
852
+ } else {
853
+ await this.doInitializeIframeCommunication();
854
+ }
398
855
  }
399
856
  /**
400
857
  * this is called on class construction time
@@ -416,54 +873,118 @@ class IframeManager {
416
873
  throw error;
417
874
  }
418
875
  }
876
+ /**
877
+ * Resolves the `hostOrigin` embedded in the iframe URL, validating it so a
878
+ * caller-supplied value can never become an injection sink.
879
+ *
880
+ * Prefers the explicitly-configured `hostOrigin` (required on React Native,
881
+ * where `globalThis.location.origin` is `localhost`/meaningless), otherwise
882
+ * falls back to the browser's own origin. Either source is parsed as a URL
883
+ * and accepted only when it is a well-formed `http(s)` or `chrome-extension:`
884
+ * origin — anything else (`javascript:`, an opaque/malformed string, a non-`http(s)`
885
+ * or non-`chrome-extension:` scheme) is rejected and yields an empty string
886
+ * rather than being forwarded.
887
+ */ resolveHostOrigin() {
888
+ var _globalThis_location;
889
+ var _this_hostOrigin;
890
+ const candidate = (_this_hostOrigin = this.hostOrigin) != null ? _this_hostOrigin : (_globalThis_location = globalThis.location) == null ? void 0 : _globalThis_location.origin;
891
+ if (!candidate) {
892
+ return '';
893
+ }
894
+ try {
895
+ const url = new URL(candidate);
896
+ const isHttp = url.protocol === 'http:' || url.protocol === 'https:';
897
+ const isChromeExtension = url.protocol === 'chrome-extension:';
898
+ if (!isHttp && !isChromeExtension) {
899
+ return '';
900
+ }
901
+ if (!url.host) {
902
+ return '';
903
+ }
904
+ if (isChromeExtension) {
905
+ return `chrome-extension://${url.host}`;
906
+ }
907
+ return url.origin;
908
+ } catch (e) {
909
+ return '';
910
+ }
911
+ }
419
912
  buildIframeUrlSearchParams() {
420
913
  var _this_instanceId, _this_sdkVersion, _this_baseClientKeysharesRelayApiUrl;
421
- const params = new URLSearchParams({
422
- instanceId: (_this_instanceId = this.instanceId) != null ? _this_instanceId : '',
423
- hostOrigin: window.location.origin,
914
+ // Omit empty/undefined params so readers get null and `?? default` works.
915
+ // An empty '' would flow through to an empty axios baseURL downstream.
916
+ const candidates = {
917
+ instanceId: (_this_instanceId = this.instanceId) != null ? _this_instanceId : undefined,
918
+ // Validated/normalized origin (explicit hostOrigin on React Native, else
919
+ // the browser's own origin). See resolveHostOrigin for the safety checks.
920
+ hostOrigin: this.resolveHostOrigin(),
424
921
  environmentId: this.environmentId,
425
922
  baseApiUrl: this.baseApiUrl,
426
923
  baseMPCRelayApiUrl: this.baseMPCRelayApiUrl,
427
- sdkVersion: (_this_sdkVersion = this.sdkVersion) != null ? _this_sdkVersion : '',
924
+ sdkVersion: (_this_sdkVersion = this.sdkVersion) != null ? _this_sdkVersion : undefined,
428
925
  debug: String(this.debug),
429
- baseClientKeysharesRelayApiUrl: (_this_baseClientKeysharesRelayApiUrl = this.baseClientKeysharesRelayApiUrl) != null ? _this_baseClientKeysharesRelayApiUrl : '',
430
- secureStorage: this.secureStorage ? 'true' : ''
431
- });
432
- const seenAdditional = new Set();
433
- for (const raw of this.additionalTrustedOrigins){
434
- const trimmed = raw.trim();
435
- if (!trimmed) {
436
- continue;
437
- }
438
- if (trimmed.length > IframeManager.maxTrustedOriginStringLength) {
439
- this.logger.warn('Skipping additionalTrustedOrigin (exceeds max length)');
440
- continue;
926
+ baseClientKeysharesRelayApiUrl: (_this_baseClientKeysharesRelayApiUrl = this.baseClientKeysharesRelayApiUrl) != null ? _this_baseClientKeysharesRelayApiUrl : undefined,
927
+ secureStorage: this.secureStorage ? 'true' : undefined,
928
+ iCloudBackup: this.iCloudBackup ? 'true' : undefined,
929
+ eagerlyRecoverKeyShares: this.eagerlyRecoverKeyShares ? 'true' : undefined
930
+ };
931
+ const params = new URLSearchParams(Object.entries(candidates).filter((entry)=>entry[1] != null && entry[1] !== ''));
932
+ this.appendTrustedOriginParams(params);
933
+ return params;
934
+ }
935
+ /**
936
+ * Validates and normalizes a single `additionalTrustedOrigins` entry.
937
+ * Returns the origin to append, or `null` if the entry should be skipped.
938
+ */ getTrustedOrigin(raw) {
939
+ const trimmed = raw.trim();
940
+ if (!trimmed) {
941
+ return null;
942
+ }
943
+ if (trimmed.length > IframeManager.maxTrustedOriginStringLength) {
944
+ this.logger.warn('Skipping additionalTrustedOrigin (exceeds max length)');
945
+ return null;
946
+ }
947
+ try {
948
+ const u = new URL(trimmed);
949
+ const isHttpOrHttps = u.protocol === 'http:' || u.protocol === 'https:';
950
+ const isChromeExtension = u.protocol === 'chrome-extension:';
951
+ if (!isHttpOrHttps && !isChromeExtension) {
952
+ this.logger.warn('Skipping additionalTrustedOrigin (unsupported scheme)', {
953
+ trimmed
954
+ });
955
+ return null;
441
956
  }
442
- try {
443
- const u = new URL(trimmed);
444
- if (u.protocol !== 'http:' && u.protocol !== 'https:') {
445
- this.logger.warn('Skipping additionalTrustedOrigin (unsupported scheme)', {
957
+ if (isChromeExtension) {
958
+ if (!u.host) {
959
+ this.logger.warn('Skipping invalid additionalTrustedOrigin', {
446
960
  trimmed
447
961
  });
448
- continue;
449
- }
450
- const origin = u.origin;
451
- if (seenAdditional.has(origin)) {
452
- continue;
962
+ return null;
453
963
  }
454
- if (seenAdditional.size >= IframeManager.maxAdditionalTrustedOrigins) {
455
- this.logger.warn('additionalTrustedOrigin limit reached, extra entries ignored');
456
- break;
457
- }
458
- seenAdditional.add(origin);
459
- params.append(FRAME_ANCESTORS_QUERY_PARAM, origin);
460
- } catch (e) {
461
- this.logger.warn('Skipping invalid additionalTrustedOrigin', {
462
- trimmed
463
- });
964
+ return `chrome-extension://${u.host}`;
464
965
  }
966
+ return u.origin;
967
+ } catch (e) {
968
+ this.logger.warn('Skipping invalid additionalTrustedOrigin', {
969
+ trimmed
970
+ });
971
+ return null;
972
+ }
973
+ }
974
+ /** Appends validated, deduped `additionalTrustedOrigins` as `frameAncestors` params. */ appendTrustedOriginParams(params) {
975
+ const seenAdditional = new Set();
976
+ for (const raw of this.additionalTrustedOrigins){
977
+ const origin = this.getTrustedOrigin(raw);
978
+ if (origin == null || seenAdditional.has(origin)) {
979
+ continue;
980
+ }
981
+ if (seenAdditional.size >= IframeManager.maxAdditionalTrustedOrigins) {
982
+ this.logger.warn('additionalTrustedOrigin limit reached, extra entries ignored');
983
+ break;
984
+ }
985
+ seenAdditional.add(origin);
986
+ params.append(FRAME_ANCESTORS_QUERY_PARAM, origin);
465
987
  }
466
- return params;
467
988
  }
468
989
  /**
469
990
  * Build the URL that the transport provider should load.
@@ -480,11 +1001,18 @@ class IframeManager {
480
1001
  * sandbox host is rebuilt (needed by the recovery flow — the transport
481
1002
  * survives the rebuild and would otherwise accumulate stale listeners).
482
1003
  */ setupWaasSDKContainerBridge(transport, waasSDKContainer) {
483
- // Forward outgoing host messages to the sandbox host
1004
+ // Forward outgoing host messages to the sandbox host.
484
1005
  const transportListener = (message)=>{
485
- if (message.origin === 'host') {
486
- waasSDKContainer.sendMessage(message);
1006
+ if (message.origin !== 'host') return;
1007
+ // Skip (don't throw) a send to a torn-down captured container: a stale
1008
+ // bridge from a logged-out instance would otherwise throw "iframe not
1009
+ // loaded" uncaught. Don't reroute to the current shared container — that
1010
+ // would leak a stale session's message into another session's iframe.
1011
+ if (!waasSDKContainer.isAlive()) {
1012
+ this.logger.warn('(setupWaasSDKContainerBridge) captured container not alive — skipping host→iframe send');
1013
+ return;
487
1014
  }
1015
+ waasSDKContainer.sendMessage(message);
488
1016
  };
489
1017
  transport.on(transportListener);
490
1018
  // Forward incoming messages from the sandbox host to the transport
@@ -513,6 +1041,8 @@ class IframeManager {
513
1041
  this.logger.debug('Skipping initializeMessageTransport: transport and message handler already initialized');
514
1042
  return;
515
1043
  }
1044
+ // Captured before the await: detach() or cleanup() can run while the iframe loads.
1045
+ const epoch = this.requestHandlers.snapshot();
516
1046
  await this.initializeIframeCommunication();
517
1047
  const transport = createIframeMessageTransport();
518
1048
  this.messageTransport = transport;
@@ -526,16 +1056,22 @@ class IframeManager {
526
1056
  } else {
527
1057
  throw new Error('No sandbox host or iframe available');
528
1058
  }
529
- this.iframeMessageHandler = new iframeMessageHandler(this.messageTransport);
530
- // Set up request channel to handle messages from iframe (for secureStorage and getSignedSessionId)
531
- if (this.secureStorage || this.getSignedSessionIdCallback) {
532
- this.iframeRequestChannel = this.setupIframeRequestHandlers(this.messageTransport);
1059
+ this.iframeMessageHandler = new IframeMessageHandler(this.messageTransport);
1060
+ // Set up request channel to handle messages from iframe (for secureStorage,
1061
+ // getSignedSessionId, and the unauthorized notification)
1062
+ if (this.secureStorage || this.iCloudBackup || this.getSignedSessionIdCallback || this.onUnauthorized) {
1063
+ const _this_setupIframeRequestHandlers = this.setupIframeRequestHandlers(this.messageTransport), { requestChannel } = _this_setupIframeRequestHandlers, registration = _object_without_properties_loose(_this_setupIframeRequestHandlers, [
1064
+ "requestChannel"
1065
+ ]);
1066
+ if (this.requestHandlers.adopt(epoch, registration)) {
1067
+ this.iframeRequestChannel = requestChannel;
1068
+ }
533
1069
  }
534
1070
  // The recovery callback runs synchronously when the request channel's
535
1071
  // timeout calls triggerRecovery. block() must run before we await anything
536
1072
  // so the request channel's recursive sendMessage() lands on the queue
537
1073
  // instead of the dead bridge.
538
- transport.recoveryManager.onRecoveryRequested(()=>{
1074
+ this.cleanupRecoverySubscription = transport.recoveryManager.onRecoveryRequested(()=>{
539
1075
  this.logger.info('(recoverIframe) Iframe transport recovery requested — rebuilding iframe');
540
1076
  transport.block();
541
1077
  void this.recoverIframe(transport).catch((error)=>{
@@ -570,7 +1106,17 @@ class IframeManager {
570
1106
  // real dead-container case below falls through to the rebuild.
571
1107
  if ((_IframeManager_sharedWaasSDKContainer = IframeManager.sharedWaasSDKContainer) == null ? void 0 : _IframeManager_sharedWaasSDKContainer.isAlive()) {
572
1108
  this.logger.info('(recoverIframe) Container still alive — request-channel timeout, skipping rebuild');
573
- this.waasSDKContainer = IframeManager.sharedWaasSDKContainer;
1109
+ // Ensure we're tracked before re-pointing the bridge (idempotent).
1110
+ IframeManager.sharedContainerUsers.add(this);
1111
+ if (this.waasSDKContainer !== IframeManager.sharedWaasSDKContainer) {
1112
+ // A concurrent recovery already swapped in a fresh shared container. Our
1113
+ // bridge still forwards to the old (now-dead) one, so re-point it before
1114
+ // unblock flushes the queued retry — otherwise the flush calls sendMessage
1115
+ // on a torn-down iframe ("iframe not loaded").
1116
+ this.cleanupBridge == null ? void 0 : this.cleanupBridge.call(this);
1117
+ this.waasSDKContainer = IframeManager.sharedWaasSDKContainer;
1118
+ this.cleanupBridge = this.setupWaasSDKContainerBridge(transport, this.waasSDKContainer);
1119
+ }
574
1120
  transport.unblock();
575
1121
  return;
576
1122
  }
@@ -580,10 +1126,7 @@ class IframeManager {
580
1126
  // retry that we want to flush after rebuild.
581
1127
  this.cleanupBridge == null ? void 0 : this.cleanupBridge.call(this);
582
1128
  this.cleanupBridge = null;
583
- if (IframeManager.sharedWaasSDKContainer) {
584
- IframeManager.sharedWaasSDKContainer.destroy();
585
- IframeManager.sharedWaasSDKContainer = null;
586
- }
1129
+ IframeManager.destroySharedContainer();
587
1130
  IframeManager.iframeLoadPromise = null;
588
1131
  this.waasSDKContainer = null;
589
1132
  // Defer the rebuild + concurrency control to loadIframe(): the first
@@ -613,22 +1156,60 @@ class IframeManager {
613
1156
  }
614
1157
  /**
615
1158
  * Sets up message handlers for iframe → host requests (secureStorage and getSignedSessionId)
1159
+ *
1160
+ * Returns the channel plus one disposer per lifetime group, covering exactly the
1161
+ * handlers this call attached. Scoped per call because three different transports
1162
+ * use it — pooling them would let a display flow take ownership of the shared
1163
+ * container's handlers.
616
1164
  */ setupIframeRequestHandlers(transport) {
617
1165
  // Create a request channel to handle requests FROM iframe
618
1166
  const requestChannel = createRequestChannel(transport);
619
- if (this.secureStorage) {
620
- // Handle getClientKeyShare requests from iframe
621
- requestChannel.handle('getClientKeyShare', this.handleGetClientKeyShare.bind(this));
622
- // Handle setClientKeyShare requests from iframe
623
- requestChannel.handle('setClientKeyShare', this.handleSetClientKeyShare.bind(this));
624
- // Handle removeClientKeyShare requests from iframe
625
- requestChannel.handle('removeClientKeyShare', this.handleRemoveClientKeyShare.bind(this));
1167
+ // handle() returns the unsubscribe; each entry here is one registration.
1168
+ // secureStorage: key-share reads/writes, answered identically by any manager
1169
+ // on the page, so they are not part of a detach.
1170
+ const storageDisposers = this.secureStorage ? [
1171
+ requestChannel.handle('getClientKeyShare', this.handleGetClientKeyShare.bind(this)),
1172
+ requestChannel.handle('setClientKeyShare', this.handleSetClientKeyShare.bind(this)),
1173
+ requestChannel.handle('removeClientKeyShare', this.handleRemoveClientKeyShare.bind(this))
1174
+ ] : [];
1175
+ // Session-scoped: these answer from this client's own session state, so a
1176
+ // superseded manager must stop answering them the moment it is detached.
1177
+ const sessionDisposers = [];
1178
+ // iCloud backup: answered from this manager's own host adapter. Unlike
1179
+ // secureStorage (which proxies host storage by address), two managers can hold
1180
+ // different adapters, so a superseded manager must stop answering on detach or
1181
+ // the first-response-wins channel could save a backup through the wrong adapter.
1182
+ if (this.iCloudBackup) {
1183
+ sessionDisposers.push(requestChannel.handle('isICloudBackupAuthenticated', this.handleIsICloudBackupAuthenticated.bind(this)), requestChannel.handle('saveICloudBackup', this.handleSaveICloudBackup.bind(this)));
626
1184
  }
627
1185
  if (this.getSignedSessionIdCallback) {
628
- // Handle getSignedSessionId requests from iframe
629
- requestChannel.handle('getSignedSessionId', this.handleGetSignedSessionId.bind(this));
1186
+ sessionDisposers.push(requestChannel.handle('getSignedSessionId', this.handleGetSignedSessionId.bind(this)));
1187
+ }
1188
+ // The iframe's 401 notification (iframe → host)
1189
+ if (this.onUnauthorized) {
1190
+ sessionDisposers.push(requestChannel.handle('notifyUnauthorized', this.handleNotifyUnauthorized.bind(this)));
1191
+ }
1192
+ return {
1193
+ disposeSessionHandlers: ()=>drainDisposers(sessionDisposers),
1194
+ disposeStorageHandlers: ()=>drainDisposers(storageDisposers),
1195
+ requestChannel
1196
+ };
1197
+ }
1198
+ /**
1199
+ * Handler for the iframe's `notifyUnauthorized` reverse-channel request.
1200
+ * Fires the host's logout callback once per session; further 401 bursts are
1201
+ * ignored until the next session re-initializes this manager.
1202
+ */ async handleNotifyUnauthorized(_request) {
1203
+ if (this.unauthorizedHandled) {
1204
+ return;
1205
+ }
1206
+ this.unauthorizedHandled = true;
1207
+ this.logger.info('(notifyUnauthorized) iframe reported a 401 — invoking host logout callback');
1208
+ try {
1209
+ await (this.onUnauthorized == null ? void 0 : this.onUnauthorized.call(this));
1210
+ } catch (error) {
1211
+ this.logger.error('(notifyUnauthorized) onUnauthorized handler threw:', error);
630
1212
  }
631
- return requestChannel;
632
1213
  }
633
1214
  /**
634
1215
  * Handler for getClientKeyShare requests from iframe
@@ -658,14 +1239,36 @@ class IframeManager {
658
1239
  await this.secureStorage.removeClientKeyShare(request.accountAddress);
659
1240
  }
660
1241
  /**
1242
+ * Handler for isICloudBackupAuthenticated requests from iframe
1243
+ */ async handleIsICloudBackupAuthenticated() {
1244
+ if (!this.iCloudBackup) {
1245
+ throw new Error('iCloud backup not available');
1246
+ }
1247
+ return {
1248
+ isAuthenticated: await this.iCloudBackup.isAuthenticated()
1249
+ };
1250
+ }
1251
+ /**
1252
+ * Handler for saveICloudBackup requests from iframe
1253
+ */ async handleSaveICloudBackup(request) {
1254
+ if (!this.iCloudBackup) {
1255
+ throw new Error('iCloud backup not available');
1256
+ }
1257
+ await this.iCloudBackup.saveBackup(request.backupData);
1258
+ }
1259
+ /**
661
1260
  * Handler for getSignedSessionId requests from iframe
662
1261
  */ async handleGetSignedSessionId(_request) {
663
1262
  if (!this.getSignedSessionIdCallback) {
664
1263
  throw new Error('Signed session ID callback not available');
665
1264
  }
666
1265
  const signedSessionId = await this.getSignedSessionIdCallback();
1266
+ // Nonce-free read; captured with the signature so the iframe-initiated path
1267
+ // (eager loading) forwards the key on backup. Absent on older hosts.
1268
+ const publicKey = await (this.getSessionPublicKeyCallback == null ? void 0 : this.getSessionPublicKeyCallback.call(this));
667
1269
  return {
668
- signedSessionId
1270
+ signedSessionId,
1271
+ publicKey
669
1272
  };
670
1273
  }
671
1274
  /**
@@ -682,21 +1285,41 @@ class IframeManager {
682
1285
  }
683
1286
  }
684
1287
  /**
685
- * Reset the shared provider and iframe load promise, and iframe instance count
1288
+ * Reset the shared provider and iframe load promise, and drop this instance
1289
+ * from the shared-container user set
686
1290
  */ resetSharedWaasSDKContainer() {
687
1291
  this.cleanupBridge == null ? void 0 : this.cleanupBridge.call(this);
688
1292
  this.cleanupBridge = null;
689
- if (IframeManager.sharedWaasSDKContainer) {
690
- IframeManager.sharedWaasSDKContainer.destroy();
691
- IframeManager.sharedWaasSDKContainer = null;
692
- }
693
- IframeManager.iframeInstanceCount = 0;
1293
+ this.cleanupRecoverySubscription == null ? void 0 : this.cleanupRecoverySubscription.call(this);
1294
+ this.cleanupRecoverySubscription = null;
1295
+ IframeManager.destroySharedContainer();
1296
+ // Drop only this failed instance; siblings stay (they re-adopt on recovery).
1297
+ IframeManager.sharedContainerUsers.delete(this);
694
1298
  IframeManager.iframeLoadPromise = null;
695
1299
  this.waasSDKContainer = null;
696
1300
  this.iframeMessageHandler = null;
697
1301
  this.messageTransport = null;
698
- // Double the timeout and cap at 60 seconds to give more time for slow networks
699
- IframeManager.iframeLoadTimeout = Math.min(IframeManager.iframeLoadTimeout * 2, 60000);
1302
+ // Double the timeout to give more time for slow networks, capped at the configured maximum.
1303
+ IframeManager.iframeLoadTimeout = Math.min(IframeManager.iframeLoadTimeout * 2, IframeManager.maxIframeLoadTimeout);
1304
+ }
1305
+ /** Bind to the shared container and join the user set together, so the
1306
+ * destroy-when-empty invariant can't drift (see {@link sharedContainerUsers}). */ adoptSharedContainer() {
1307
+ this.waasSDKContainer = IframeManager.sharedWaasSDKContainer;
1308
+ IframeManager.sharedContainerUsers.add(this);
1309
+ }
1310
+ /** Destroy the (already dead/replaced) shared container. Deliberately leaves the
1311
+ * user set intact — live users re-point to the rebuilt container on recovery. */ static destroySharedContainer() {
1312
+ var _IframeManager_sharedWaasSDKContainer;
1313
+ (_IframeManager_sharedWaasSDKContainer = IframeManager.sharedWaasSDKContainer) == null ? void 0 : _IframeManager_sharedWaasSDKContainer.destroy();
1314
+ IframeManager.sharedWaasSDKContainer = null;
1315
+ }
1316
+ /** Release this instance; destroy the container only once no user remains, so a
1317
+ * logout can't tear it out from under a concurrent login's eager recovery. */ releaseSharedContainer() {
1318
+ IframeManager.sharedContainerUsers.delete(this);
1319
+ if (IframeManager.sharedWaasSDKContainer && IframeManager.sharedContainerUsers.size === 0) {
1320
+ IframeManager.destroySharedContainer();
1321
+ IframeManager.iframeLoadPromise = null;
1322
+ }
700
1323
  }
701
1324
  async loadIframe() {
702
1325
  var _IframeManager_sharedWaasSDKContainer;
@@ -705,24 +1328,19 @@ class IframeManager {
705
1328
  // loadIframe again on a dead container: we fall through to the remount
706
1329
  // branch below instead of adopting the corpse.
707
1330
  if ((_IframeManager_sharedWaasSDKContainer = IframeManager.sharedWaasSDKContainer) == null ? void 0 : _IframeManager_sharedWaasSDKContainer.isAlive()) {
708
- this.waasSDKContainer = IframeManager.sharedWaasSDKContainer;
709
- IframeManager.iframeInstanceCount++;
710
- return Promise.resolve();
1331
+ this.adoptSharedContainer();
1332
+ return;
711
1333
  }
712
1334
  // If a load is in progress, wait for it, then assign
713
1335
  if (IframeManager.iframeLoadPromise) {
714
1336
  return IframeManager.iframeLoadPromise.then(()=>{
715
- this.waasSDKContainer = IframeManager.sharedWaasSDKContainer;
716
- IframeManager.iframeInstanceCount++;
1337
+ this.adoptSharedContainer();
717
1338
  });
718
1339
  }
719
1340
  // sharedWaasSDKContainer is dead (or never existed) and no load is in
720
1341
  // flight. Destroy the stale corpse so createWaasSDKContainerLoadPromise
721
1342
  // mounts a fresh one.
722
- if (IframeManager.sharedWaasSDKContainer) {
723
- IframeManager.sharedWaasSDKContainer.destroy();
724
- IframeManager.sharedWaasSDKContainer = null;
725
- }
1343
+ IframeManager.destroySharedContainer();
726
1344
  const loadPromise = IframeManager.iframeLoadPromise = this.createWaasSDKContainerLoadPromise();
727
1345
  // Clear iframeLoadPromise once the load settles so the "in flight" branch
728
1346
  // above only fires while a load is actually pending. Otherwise it would
@@ -757,6 +1375,16 @@ class IframeManager {
757
1375
  unsubscribeHandshake();
758
1376
  unsubscribeError();
759
1377
  waasSDKContainer.destroy();
1378
+ // A non-retryable failure (e.g. the embedding page's CSP blocking
1379
+ // the iframe) can only repeat — reject now instead of retrying or
1380
+ // waiting out the remaining timeout.
1381
+ if (isNonRetryableIframeLoadError(error)) {
1382
+ this.logger.error('Iframe failed to load with a non-retryable error: ', error);
1383
+ this.resetSharedWaasSDKContainer();
1384
+ IframeManager.iframeLoadAttempts = 0;
1385
+ reject(error);
1386
+ return;
1387
+ }
760
1388
  // Check if we should retry
761
1389
  if (IframeManager.iframeLoadAttempts <= IframeManager.maxRetryAttempts) {
762
1390
  const errorMsg = error instanceof Error ? error.message : String(error);
@@ -785,8 +1413,7 @@ class IframeManager {
785
1413
  unsubscribeHandshake();
786
1414
  unsubscribeError();
787
1415
  IframeManager.sharedWaasSDKContainer = waasSDKContainer;
788
- this.waasSDKContainer = waasSDKContainer;
789
- IframeManager.iframeInstanceCount++;
1416
+ this.adoptSharedContainer();
790
1417
  IframeManager.iframeLoadAttempts = 0; // Reset retry counter on success
791
1418
  resolve();
792
1419
  this.logger.debug('Iframe loaded successfully...', this.getIframeContext());
@@ -816,7 +1443,13 @@ class IframeManager {
816
1443
  * @param {HTMLElement} container - The container to which the iframe will be attached
817
1444
  * @returns {Promise<HTMLIFrameElement>} that resolves when the iframe is loaded
818
1445
  */ loadIframeForContainer(container) {
819
- return new Promise((resolve, reject)=>{
1446
+ /* eslint-disable no-restricted-globals -- This is the sanctioned web-only
1447
+ DOM boundary for the embedded display iframe. `window`/`document` are
1448
+ banned across browser-wallet-client (they are undefined on React Native /
1449
+ Hermes and would crash the RN export path); this single method is the one
1450
+ place allowed to touch them, mirroring the `createIframeWaasSDKContainer`
1451
+ and `messageTransportBridge` web-only files. It is never reached on RN —
1452
+ the native WebView container path is used there instead. */ return new Promise((resolve, reject)=>{
820
1453
  var _this_sdkVersion;
821
1454
  const context = {
822
1455
  iframeDomain: this.iframeDomain,
@@ -867,7 +1500,7 @@ class IframeManager {
867
1500
  }
868
1501
  clearTimeout(iframeTimeoutId);
869
1502
  this.iframe = iframe;
870
- IframeManager.iframeInstanceCount++;
1503
+ // display iframe is per-instance — intentionally not a sharedContainerUsers member
871
1504
  resolve(iframe);
872
1505
  var _this_sdkVersion;
873
1506
  this.logger.debug('Iframe loaded successfully...', {
@@ -881,7 +1514,7 @@ class IframeManager {
881
1514
  };
882
1515
  window.addEventListener('message', messageListener);
883
1516
  });
884
- }
1517
+ /* eslint-enable no-restricted-globals */ }
885
1518
  /**
886
1519
  * Initializes the iframe display for a specific container.
887
1520
  *
@@ -898,12 +1531,10 @@ class IframeManager {
898
1531
  messageTransport: createMessageTransport()
899
1532
  });
900
1533
  const cleanupBridge = setupMessageTransportBridge(transport, iframe, this.iframeDomain);
901
- const iframeDisplay = new iframeMessageHandler(transport);
1534
+ const iframeDisplay = new IframeMessageHandler(transport);
902
1535
  // Set up iframe request handlers on this transport so the display iframe
903
1536
  // can access key shares (e.g. for exportPrivateKey) and signed session ID
904
- if (this.secureStorage || this.getSignedSessionIdCallback) {
905
- this.setupIframeRequestHandlers(transport);
906
- }
1537
+ const requestHandlers = this.secureStorage || this.getSignedSessionIdCallback ? this.setupIframeRequestHandlers(transport) : undefined;
907
1538
  var _this_authMode;
908
1539
  // if authMode is header: inform iframe the authMode with auth token
909
1540
  // if authMode is cookie: inform iframe the authMode with empty authToken
@@ -912,8 +1543,11 @@ class IframeManager {
912
1543
  iframe,
913
1544
  iframeDisplay,
914
1545
  cleanup: ()=>{
1546
+ if (requestHandlers) {
1547
+ disposeAllHandlers(requestHandlers);
1548
+ }
915
1549
  cleanupBridge();
916
- container.removeChild(iframe);
1550
+ iframe.remove();
917
1551
  }
918
1552
  };
919
1553
  } catch (error) {
@@ -921,47 +1555,163 @@ class IframeManager {
921
1555
  throw error;
922
1556
  }
923
1557
  }
924
- async cleanup() {
925
- await this.initializeMessageTransport();
926
- if (!this.iframeMessageHandler) {
927
- throw new Error('Iframe message handler not initialized');
928
- }
929
- // The iframe-side cleanup handler clears localStorage + secureStorage
930
- // (initWaasWalletHandler.ts), which is best-effort: if it doesn't ACK
931
- // within the request channel's 5s timeout, the channel rejects with a
932
- // (misleadingly named) NO_HANDLERS_REGISTERED error. Pre-#1063 that
933
- // rejection was masked because recoverIframe rebuilt the iframe and
934
- // the retry hit a fresh handler; post-#1063 we keep the (slow) alive
935
- // iframe, the rejection surfaces, and — uncaught here — becomes an
936
- // unhandled promise rejection / pageerror. RN-web's secureStorage is
937
- // slow enough to trigger this routinely, breaking the
938
- // `sign-message-new-wallet` re-login flow.
939
- //
940
- // Swallow the error: we're about to remove the iframe from the DOM
941
- // (or another instance is, when iframeInstanceCount drops to 0),
942
- // which obsoletes anything the cleanup handler would have cleared.
943
- // Stale storage from a missed cleanup is cleared by the next iframe
944
- // init's __resetInitializationState anyway.
1558
+ /**
1559
+ * Drives the handshake load for a caller-provided {@link WaasSDKContainer}
1560
+ * used as a *visible* private-key display surface (e.g. a React Native native
1561
+ * WebView). Resolves once the container reports the
1562
+ * `iframe-ready-${instanceId}` handshake; rejects on a container-level error
1563
+ * or load timeout.
1564
+ *
1565
+ * Unlike {@link loadIframe}, this deliberately does NOT touch the shared
1566
+ * signing container or its retry/static state: the display container is owned
1567
+ * by the caller, lives only for the duration of a single export ceremony, and
1568
+ * renders the key inside its own sandboxed document. The key is therefore
1569
+ * never sent back across the bridge to the host — keeping the
1570
+ * "host cannot read the key" invariant identical to the web iframe path.
1571
+ */ loadWaasSDKContainerForDisplay(waasSDKContainer) {
1572
+ return new Promise((resolve, reject)=>{
1573
+ // settle() captures timeoutId/unsubscribe* declared below; they are
1574
+ // assigned synchronously before any async callback (setUrl rejection,
1575
+ // onError, onMessage, timeout) can fire, so the references are always live.
1576
+ const settle = (error)=>{
1577
+ clearTimeout(timeoutId);
1578
+ unsubscribeHandshake();
1579
+ unsubscribeError();
1580
+ if (error) {
1581
+ // Avoid Object's default '[object Object]' stringification: keep Error
1582
+ // instances as-is, use a string reason directly, otherwise a stable
1583
+ // message (the raw non-Error value carries no reliable text).
1584
+ const reason = typeof error === 'string' ? error : 'Display container failed to load';
1585
+ reject(error instanceof Error ? error : new Error(reason));
1586
+ } else {
1587
+ resolve();
1588
+ }
1589
+ };
1590
+ const timeoutId = setTimeout(()=>{
1591
+ settle(new Error('Display container load timeout'));
1592
+ }, IframeManager.iframeLoadTimeout);
1593
+ // Surface container-level errors (load failure, navigation/CSP block) so
1594
+ // we don't wait out the full timeout.
1595
+ const unsubscribeError = waasSDKContainer.onError((error)=>{
1596
+ settle(error != null ? error : new Error('Display container failed to load'));
1597
+ });
1598
+ // The hosted page posts `iframe-ready-${instanceId}` once it is ready to
1599
+ // receive transport messages — the same handshake the signing container uses.
1600
+ const unsubscribeHandshake = waasSDKContainer.onMessage((data)=>{
1601
+ if (data === `iframe-ready-${this.instanceId}`) {
1602
+ settle();
1603
+ }
1604
+ });
1605
+ const url = this.buildIframeUrl();
1606
+ this.logger.debug('Loading display container with src:', url);
1607
+ waasSDKContainer.setUrl(url).catch((error)=>{
1608
+ settle(error);
1609
+ });
1610
+ });
1611
+ }
1612
+ /**
1613
+ * Initializes a private-key display surface backed by a caller-provided
1614
+ * {@link WaasSDKContainer} (e.g. a visible React Native WebView) instead of a
1615
+ * DOM {@link HTMLElement}. This is the container-based counterpart to
1616
+ * {@link initializeIframeDisplayForContainer}: it reuses the same
1617
+ * {@link setupWaasSDKContainerBridge} transport wiring the signing flow uses,
1618
+ * so the export ceremony runs — and the key is rendered — entirely inside the
1619
+ * container's own sandboxed document.
1620
+ *
1621
+ * The caller owns the container's mount/visibility. The returned `cleanup`
1622
+ * detaches the transport bridge and calls `container.destroy()`.
1623
+ */ async initializeDisplayForWaasSDKContainer({ waasSDKContainer }) {
945
1624
  try {
946
- await this.iframeMessageHandler.cleanup();
947
- } catch (error) {
948
- this.logger.warn('(cleanup) iframeMessageHandler.cleanup() failed; proceeding with DOM teardown', {
949
- error: error instanceof Error ? error.message : error
1625
+ await this.loadWaasSDKContainerForDisplay(waasSDKContainer);
1626
+ const transport = applyDefaultMessageOrigin({
1627
+ defaultOrigin: 'host',
1628
+ messageTransport: createMessageTransport()
950
1629
  });
1630
+ const cleanupBridge = this.setupWaasSDKContainerBridge(transport, waasSDKContainer);
1631
+ const iframeDisplay = new IframeMessageHandler(transport);
1632
+ // Set up iframe request handlers on this transport so the display
1633
+ // container can access key shares (e.g. for exportPrivateKey) and the
1634
+ // signed session ID — mirrors initializeIframeDisplayForContainer.
1635
+ const requestHandlers = this.secureStorage || this.getSignedSessionIdCallback ? this.setupIframeRequestHandlers(transport) : undefined;
1636
+ var _this_authMode;
1637
+ // if authMode is header: inform the container of the authMode with auth token
1638
+ // if authMode is cookie: inform the container of the authMode with empty authToken
1639
+ await iframeDisplay.sendAuthToken(this.authToken, (_this_authMode = this.authMode) != null ? _this_authMode : AuthMode.HEADER);
1640
+ return {
1641
+ iframeDisplay,
1642
+ cleanup: ()=>{
1643
+ if (requestHandlers) {
1644
+ disposeAllHandlers(requestHandlers);
1645
+ }
1646
+ cleanupBridge();
1647
+ waasSDKContainer.destroy();
1648
+ }
1649
+ };
1650
+ } catch (error) {
1651
+ this.logger.error('Error initializing display container:', error);
1652
+ throw error;
951
1653
  }
952
- if (this.waasSDKContainer) {
953
- IframeManager.iframeInstanceCount--;
954
- if (IframeManager.sharedWaasSDKContainer && IframeManager.iframeInstanceCount === 0) {
955
- this.cleanupBridge == null ? void 0 : this.cleanupBridge.call(this);
956
- this.cleanupBridge = null;
957
- IframeManager.sharedWaasSDKContainer.destroy();
958
- IframeManager.sharedWaasSDKContainer = null;
959
- IframeManager.iframeLoadPromise = null;
1654
+ }
1655
+ /**
1656
+ * Stops this manager answering the iframe's *session-scoped* reverse-channel
1657
+ * requests (iframe → host), and nothing else. Call it on a manager superseded
1658
+ * by a newer one for the same page.
1659
+ *
1660
+ * Every bridged manager answers every iframe → host request and the channel is
1661
+ * first-response-wins, so a superseded manager with revoked host callbacks
1662
+ * rejects `getSignedSessionId` instantly and beats the live one's round-trip —
1663
+ * killing wallet creation for the life of the iframe.
1664
+ *
1665
+ * Narrow on purpose. The key-share handlers stay: they proxy host storage by
1666
+ * address, so any manager answers them identically, and the iframe still needs
1667
+ * them to clear shares during {@link cleanup}. Transport, bridge, recovery
1668
+ * subscription and container membership stay too, so in-flight operations still
1669
+ * get their responses (tearing them down makes an in-flight wallet creation hang
1670
+ * forever). Use {@link cleanup} for a real teardown, and call this any time —
1671
+ * including mid-initialization.
1672
+ */ detach() {
1673
+ this.requestHandlers.detach();
1674
+ }
1675
+ async cleanup() {
1676
+ // Detach up front, so a logged-out manager stops answering signed-session
1677
+ // requests immediately instead of once the ACK below returns (or times out).
1678
+ this.requestHandlers.markTornDown();
1679
+ // Best-effort ACK (the iframe clears its storage), only if already
1680
+ // initialized. Do NOT initialize here: that mounts a fresh container just to
1681
+ // ACK and then tears it down, churning the shared container across
1682
+ // logout→relogin and starving the next login's eager recovery. May reject on
1683
+ // a 5s timeout — swallow it; stale storage is cleared by the next init anyway.
1684
+ if (this.waasSDKContainer && this.iframeMessageHandler) {
1685
+ try {
1686
+ await this.iframeMessageHandler.cleanup();
1687
+ } catch (error) {
1688
+ this.logger.warn('(cleanup) iframeMessageHandler.cleanup() failed; proceeding with DOM teardown', {
1689
+ error: error instanceof Error ? error.message : error
1690
+ });
960
1691
  }
1692
+ }
1693
+ // Always detach bridge + recovery subscription, even if the container is gone:
1694
+ // a dangling subscription's retry timer can fire recovery into a torn-down
1695
+ // container next session ("iframe not loaded").
1696
+ this.cleanupBridge == null ? void 0 : this.cleanupBridge.call(this);
1697
+ this.cleanupBridge = null;
1698
+ this.cleanupRecoverySubscription == null ? void 0 : this.cleanupRecoverySubscription.call(this);
1699
+ this.cleanupRecoverySubscription = null;
1700
+ if (this.waasSDKContainer) {
1701
+ this.releaseSharedContainer();
961
1702
  this.waasSDKContainer = null;
962
1703
  }
1704
+ // Drop transport/handler so the next op re-inits a fresh bridge (not a
1705
+ // detached one); re-arm the unauthorized guard for a future session.
1706
+ this.messageTransport = null;
1707
+ this.iframeMessageHandler = null;
1708
+ // Key-share handlers go last: the iframe's cleanup above clears each wallet's
1709
+ // shares over this channel and needs a host still answering.
1710
+ this.requestHandlers.disposeStorageHandlers();
1711
+ this.iframeRequestChannel = undefined;
1712
+ this.unauthorizedHandled = false;
963
1713
  }
964
- constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, chainName, sdkVersion, authMode = AuthMode.HEADER, authToken, debug, baseClientKeysharesRelayApiUrl, additionalTrustedOrigins }, internalOptions){
1714
+ constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, chainName, sdkVersion, authMode = AuthMode.HEADER, authToken, debug, baseClientKeysharesRelayApiUrl, additionalTrustedOrigins, hostOrigin, iframeLoadTimeout, maxRetryAttempts, eagerlyRecoverKeyShares }, internalOptions){
965
1715
  this.logger = logger;
966
1716
  this.instanceId = null;
967
1717
  this.iframeDomain = null;
@@ -970,8 +1720,17 @@ class IframeManager {
970
1720
  /** Teardown function returned by setupMessageTransportBridge — detaches all
971
1721
  * listeners. Tracked so we can rebuild the bridge on iframe recovery without
972
1722
  * leaking listeners against the dead iframe. */ this.cleanupBridge = null;
1723
+ /** Unsubscribe for the onRecoveryRequested listener. Tracked so logout detaches
1724
+ * it — otherwise the request channel's retry timer keeps firing recovery against
1725
+ * a torn-down transport on the next session. */ this.cleanupRecoverySubscription = null;
973
1726
  this.iframe = null;
1727
+ /**
1728
+ * Lifetimes of the shared container's reverse-channel handlers: which of them
1729
+ * a superseded manager stops answering ({@link detach}) and which outlive it
1730
+ * until teardown ({@link cleanup}).
1731
+ */ this.requestHandlers = new IframeRequestHandlerRegistry();
974
1732
  this.waasSDKContainer = null;
1733
+ /** One-shot guard so a burst of 401 notifications triggers a single logout. */ this.unauthorizedHandled = false;
975
1734
  this.environmentId = environmentId;
976
1735
  this.authToken = authToken;
977
1736
  this.authMode = authMode;
@@ -983,33 +1742,85 @@ class IframeManager {
983
1742
  this.additionalTrustedOrigins = additionalTrustedOrigins ? [
984
1743
  ...additionalTrustedOrigins
985
1744
  ] : [];
1745
+ this.hostOrigin = hostOrigin;
1746
+ this.eagerlyRecoverKeyShares = eagerlyRecoverKeyShares != null ? eagerlyRecoverKeyShares : false;
986
1747
  // Set secure storage adapter if provided (internal use only)
987
1748
  if (internalOptions == null ? void 0 : internalOptions.secureStorage) {
988
1749
  this.secureStorage = internalOptions.secureStorage;
989
1750
  }
1751
+ // Set iCloud backup adapter if provided (internal use only)
1752
+ if (internalOptions == null ? void 0 : internalOptions.iCloudBackup) {
1753
+ this.iCloudBackup = internalOptions.iCloudBackup;
1754
+ }
990
1755
  // Set signed session ID callback if provided (internal use only)
991
1756
  if (internalOptions == null ? void 0 : internalOptions.getSignedSessionId) {
992
1757
  this.getSignedSessionIdCallback = internalOptions.getSignedSessionId;
993
1758
  }
1759
+ // Set session public key callback if provided (internal use only)
1760
+ if (internalOptions == null ? void 0 : internalOptions.getSessionPublicKey) {
1761
+ this.getSessionPublicKeyCallback = internalOptions.getSessionPublicKey;
1762
+ }
994
1763
  var _internalOptions_createWaasSDKContainer;
995
1764
  this.createWaasSDKContainer = (_internalOptions_createWaasSDKContainer = internalOptions == null ? void 0 : internalOptions.createWaasSDKContainer) != null ? _internalOptions_createWaasSDKContainer : createIframeWaasSDKContainer;
996
- const environment = getEnvironmentFromUrl(baseApiUrl);
997
- this.iframeDomain = IFRAME_DOMAIN_MAP[environment];
998
- if (this.authMode === AuthMode.COOKIE) {
999
- this.iframeDomain = this.baseApiUrl;
1765
+ this.onUnauthorized = internalOptions == null ? void 0 : internalOptions.onUnauthorized;
1766
+ this.iframeDomain = resolveIframeDomain({
1767
+ baseApiUrl,
1768
+ authMode: this.authMode
1769
+ });
1770
+ // Cookie mode serves the iframe from the customer's cookie hostname; refuse
1771
+ // to boot if that origin is the embedding page's own origin (see the guard).
1772
+ if (this.authMode === AuthMode.COOKIE && this.iframeDomain) {
1773
+ assertIframeOriginIsolated(this.iframeDomain);
1774
+ }
1775
+ // Fallback warmup: only saves connection setup when the host constructs
1776
+ // the client ahead of use. Hosts should call `preconnectWaasIframe` at
1777
+ // auth-flow start for real runway. No-op on React Native.
1778
+ if (this.iframeDomain) {
1779
+ preconnectIframeOrigin(this.iframeDomain);
1000
1780
  }
1001
1781
  // Generate unique instanceId when client is created
1002
- this.instanceId = crypto.randomUUID();
1782
+ this.instanceId = generateUUID();
1003
1783
  this.debug = Boolean(debug);
1004
1784
  this.logger.setLogLevel(this.debug ? 'DEBUG' : 'INFO');
1785
+ IframeManager.applyLoadTuning({
1786
+ iframeLoadTimeout,
1787
+ maxRetryAttempts
1788
+ });
1005
1789
  }
1006
1790
  }
1007
1791
  IframeManager.iframeLoadPromise = null;
1008
- IframeManager.iframeLoadTimeout = 10000;
1792
+ /**
1793
+ * Initial timeout (ms) for the iframe to complete its boot handshake.
1794
+ * On each failed attempt the active timeout doubles (capped at 60_000ms — see
1795
+ * {@link resetSharedWaasSDKContainer}) before the next retry.
1796
+ *
1797
+ * Default chosen to comfortably cover the iframe's P95 cold-start at the
1798
+ * time of writing (~13s for global traffic on a 3 MB MPC WASM payload).
1799
+ * Override via the `iframeLoadTimeout` constructor option when the host
1800
+ * environment needs a different budget (e.g. constrained mobile webviews).
1801
+ *
1802
+ * Held as a static (not instance) field because the shared
1803
+ * `iframeLoadPromise` is itself static — all instances in a page must
1804
+ * agree on the active timeout for the retry doubling logic to remain
1805
+ * coherent.
1806
+ */ IframeManager.iframeLoadTimeout = 20000;
1009
1807
  IframeManager.iframeLoadAttempts = 0;
1010
- IframeManager.maxRetryAttempts = 1;
1808
+ /**
1809
+ * Number of retry attempts beyond the initial load attempt. The total
1810
+ * number of attempts is `maxRetryAttempts + 1`. Override via the
1811
+ * `maxRetryAttempts` constructor option.
1812
+ */ IframeManager.maxRetryAttempts = 1;
1813
+ IframeManager.minIframeLoadTimeout = 1000;
1814
+ IframeManager.maxIframeLoadTimeout = 60000;
1815
+ IframeManager.maxAllowedRetryAttempts = 10;
1011
1816
  IframeManager.sharedWaasSDKContainer = null;
1012
- IframeManager.iframeInstanceCount = 0;
1817
+ /**
1818
+ * Instances bound to the live shared container; it's destroyed only when this
1819
+ * empties. A set (vs the old counter) can't drift negative — a logged-out
1820
+ * instance's cleanup once decremented past zero and destroyed a container the
1821
+ * next login still needed. Live users are carried across a rebuild (not
1822
+ * cleared), so the fresh container isn't torn down before they re-point to it.
1823
+ */ IframeManager.sharedContainerUsers = new Set();
1013
1824
  IframeManager.maxAdditionalTrustedOrigins = 32;
1014
1825
  IframeManager.maxTrustedOriginStringLength = 200;
1015
1826
 
@@ -1060,7 +1871,20 @@ class DynamicWalletClient extends IframeManager {
1060
1871
  traceContext
1061
1872
  }));
1062
1873
  }
1063
- async createWalletAccount({ thresholdSignatureScheme, password = undefined, signedSessionId, authToken, traceContext, bitcoinConfig }) {
1874
+ /**
1875
+ * Re-locks every unlocked password-encrypted wallet: its
1876
+ * decrypted client key shares are cleared so the next wallet operation
1877
+ * prompts for the wallet password again. Pass `accountAddress` to re-lock a
1878
+ * single wallet.
1879
+ */ async lockWallets({ accountAddress, authToken, traceContext } = {}) {
1880
+ return this.withHandler((handler)=>handler.lockWallets({
1881
+ chainName: this.chainName,
1882
+ accountAddress,
1883
+ authToken,
1884
+ traceContext
1885
+ }));
1886
+ }
1887
+ async createWalletAccount({ thresholdSignatureScheme, password = undefined, signedSessionId, authToken, traceContext, bitcoinConfig, businessAccountId }) {
1064
1888
  return this.withHandler((handler)=>handler.createWalletAccount({
1065
1889
  chainName: this.chainName,
1066
1890
  thresholdSignatureScheme,
@@ -1068,9 +1892,44 @@ class DynamicWalletClient extends IframeManager {
1068
1892
  signedSessionId,
1069
1893
  authToken,
1070
1894
  traceContext,
1071
- bitcoinConfig
1895
+ bitcoinConfig,
1896
+ businessAccountId
1072
1897
  }));
1073
1898
  }
1899
+ /**
1900
+ * Business-account operations. Chain-agnostic; mirrors the base client's
1901
+ * `businessAccounts` surface but proxies each call across the iframe.
1902
+ */ get businessAccounts() {
1903
+ return {
1904
+ createBusinessAccount: (args = {})=>this.withHandler((handler)=>handler.createBusinessAccount(args)),
1905
+ listBusinessAccounts: (args = {})=>this.withHandler((handler)=>handler.listBusinessAccounts(args)),
1906
+ getBusinessAccount: (args)=>this.withHandler((handler)=>handler.getBusinessAccount(args)),
1907
+ addWalletToBusinessAccount: (args)=>this.withHandler((handler)=>handler.linkWalletToBusinessAccount(args)),
1908
+ addMember: (args)=>this.withHandler((handler)=>handler.addBusinessAccountMember(args)),
1909
+ addSigner: (args)=>this.withHandler((handler)=>handler.addBusinessAccountSigner(args))
1910
+ };
1911
+ }
1912
+ /**
1913
+ * addSigner via the SSE reshare ceremony — proxies to the chain client in the
1914
+ * iframe. `chainName` is this connector's chain; the rest is supplied by the
1915
+ * caller (the connector provides signedSessionId, like createWalletAccount).
1916
+ */ async reshareToNewSignerShareSet(request) {
1917
+ const { accountAddress, businessAccountId, signedSessionId, authToken, password, targetSignerPassword, elevatedAccessToken, intent, intentSignature, initialSignerRules } = request;
1918
+ return this.withHandler((handler)=>handler.reshareToNewSignerShareSet(_extends({
1919
+ chainName: this.chainName,
1920
+ accountAddress,
1921
+ businessAccountId
1922
+ }, pickSignerTarget(request), {
1923
+ signedSessionId,
1924
+ authToken,
1925
+ password,
1926
+ targetSignerPassword,
1927
+ elevatedAccessToken,
1928
+ intent,
1929
+ intentSignature,
1930
+ initialSignerRules
1931
+ })));
1932
+ }
1074
1933
  async requiresPasswordForOperation({ accountAddress, walletOperation = WalletOperation.REACH_THRESHOLD, authToken }) {
1075
1934
  return this.withHandler((handler)=>handler.requiresPasswordForOperation({
1076
1935
  chainName: this.chainName,
@@ -1086,8 +1945,8 @@ class DynamicWalletClient extends IframeManager {
1086
1945
  authToken
1087
1946
  }));
1088
1947
  }
1089
- async signMessage({ message, accountAddress, password = undefined, signedSessionId, authToken, mfaToken, elevatedAccessToken, context, traceContext, bitcoinConfig }) {
1090
- const contextString = JSON.stringify(context, (_key, value)=>typeof value === 'bigint' ? value.toString() : value);
1948
+ async signMessage({ message, accountAddress, password = undefined, signedSessionId, authToken, mfaToken, elevatedAccessToken, context, approvalQuorum, traceContext, bitcoinConfig }) {
1949
+ const contextString = JSON.stringify(context, (_key, value)=>typeof value === 'bigint' ? String(value) : value);
1091
1950
  return this.withHandler((handler)=>handler.signMessage({
1092
1951
  chainName: this.chainName,
1093
1952
  message,
@@ -1098,11 +1957,62 @@ class DynamicWalletClient extends IframeManager {
1098
1957
  mfaToken,
1099
1958
  elevatedAccessToken,
1100
1959
  context: contextString,
1960
+ approvalQuorum,
1101
1961
  traceContext,
1102
1962
  bitcoinConfig
1103
1963
  }));
1104
1964
  }
1105
- async signRawMessage({ message, accountAddress, password = undefined, signedSessionId, authToken, mfaToken, elevatedAccessToken, context, traceContext, bitcoinConfig }) {
1965
+ /**
1966
+ * Token-2022 confidential transfers (SVM only): generates the confidential
1967
+ * seed inside the enclave and stores the sealed result in CKS.
1968
+ */ async createConfidentialSeed(request) {
1969
+ return this.withHandler((handler)=>handler.createConfidentialSeed(_extends({}, request, {
1970
+ chainName: this.chainName
1971
+ })));
1972
+ }
1973
+ /**
1974
+ * Token-2022 confidential transfers (SVM only): signs the operation's
1975
+ * transactions in the enclave. `rpcUrl` is required when account state or
1976
+ * the blockhash must be fetched, or when `broadcast` is set.
1977
+ */ async signConfidentialTransfer(request) {
1978
+ return this.withHandler((handler)=>handler.signConfidentialTransfer(_extends({}, request, {
1979
+ chainName: this.chainName
1980
+ })));
1981
+ }
1982
+ /**
1983
+ * Token-2022 confidential transfers (SVM only): returns the available and
1984
+ * pending confidential balances for a token account. `rpcUrl` is required
1985
+ * when `accountState` is omitted.
1986
+ */ async getConfidentialBalance(request) {
1987
+ return this.withHandler((handler)=>handler.getConfidentialBalance(_extends({}, request, {
1988
+ chainName: this.chainName
1989
+ })));
1990
+ }
1991
+ async prepareSigningIntent(request) {
1992
+ return this.withHandler(async (handler)=>{
1993
+ const requestWithChain = _extends({}, request, {
1994
+ chainName: this.chainName
1995
+ });
1996
+ const intent = await handler.prepareSigningIntent(requestWithChain);
1997
+ // Refuse intents that drop or change the wallet the request named.
1998
+ let preparedPayload;
1999
+ if (intent.operation.kind !== 'transaction') {
2000
+ preparedPayload = intent.operation.payload;
2001
+ }
2002
+ assertPreparedSigningIntentMatchesRequest({
2003
+ intent,
2004
+ preparedPayload,
2005
+ request: requestWithChain
2006
+ });
2007
+ return intent;
2008
+ });
2009
+ }
2010
+ async resumeSigningIntent(request) {
2011
+ return this.withHandler((handler)=>handler.resumeSigningIntent(_extends({}, request, {
2012
+ chainName: this.chainName
2013
+ })));
2014
+ }
2015
+ async signRawMessage({ message, accountAddress, password = undefined, signedSessionId, authToken, mfaToken, elevatedAccessToken, context, traceContext, bitcoinConfig, approvalQuorum }) {
1106
2016
  return this.withHandler((handler)=>handler.signRawMessage({
1107
2017
  chainName: this.chainName,
1108
2018
  message,
@@ -1114,7 +2024,8 @@ class DynamicWalletClient extends IframeManager {
1114
2024
  elevatedAccessToken,
1115
2025
  context,
1116
2026
  traceContext,
1117
- bitcoinConfig
2027
+ bitcoinConfig,
2028
+ approvalQuorum
1118
2029
  }));
1119
2030
  }
1120
2031
  /**
@@ -1127,7 +2038,7 @@ class DynamicWalletClient extends IframeManager {
1127
2038
  * SUI:
1128
2039
  * const txBytes = await txb.build({ client });
1129
2040
  * const txString = Buffer.from(txBytes).toString("hex");
1130
- */ async signTransaction({ senderAddress, transaction, password = undefined, signedSessionId, authToken, mfaToken, elevatedAccessToken, chainId, traceContext, bitcoinConfig }) {
2041
+ */ async signTransaction({ senderAddress, transaction, password = undefined, signedSessionId, authToken, mfaToken, elevatedAccessToken, chainId, approvalQuorum, traceContext, bitcoinConfig, signingIndexes, allowedSighash, allowedWitnessScripts }) {
1131
2042
  return this.withHandler((handler)=>handler.signTransaction({
1132
2043
  chainName: this.chainName,
1133
2044
  senderAddress,
@@ -1138,42 +2049,55 @@ class DynamicWalletClient extends IframeManager {
1138
2049
  mfaToken,
1139
2050
  elevatedAccessToken,
1140
2051
  chainId,
2052
+ approvalQuorum,
1141
2053
  traceContext,
1142
- bitcoinConfig
2054
+ bitcoinConfig,
2055
+ signingIndexes,
2056
+ allowedSighash,
2057
+ allowedWitnessScripts
1143
2058
  }));
1144
2059
  }
1145
- async signTypedData({ accountAddress, typedData, password = undefined, signedSessionId, authToken, mfaToken, elevatedAccessToken, traceContext }) {
2060
+ async signTypedData({ accountAddress, typedData, password = undefined, signedSessionId, authToken, mfaToken, elevatedAccessToken, traceContext, approvalQuorum }) {
1146
2061
  return this.withHandler((handler)=>handler.signTypedData({
1147
2062
  chainName: this.chainName,
1148
2063
  accountAddress,
1149
- typedData: JSON.stringify(typedData),
2064
+ typedData: JSON.stringify(typedData, (_key, value)=>typeof value === 'bigint' ? String(value) : value),
1150
2065
  password,
1151
2066
  signedSessionId,
1152
2067
  authToken,
1153
2068
  mfaToken,
1154
2069
  elevatedAccessToken,
1155
- traceContext
2070
+ traceContext,
2071
+ approvalQuorum
1156
2072
  }));
1157
2073
  }
1158
- async backupKeySharesToGoogleDrive({ accountAddress, password = undefined, signedSessionId, authToken, googleDriveAccessToken, traceContext }) {
2074
+ async backupKeySharesToGoogleDrive({ accountAddress, password = undefined, signedSessionId, sessionPublicKey, authToken, googleDriveAccessToken, shouldBackupWithPassword, traceContext, approvalQuorum, proposalId }) {
1159
2075
  return this.withHandler((handler)=>handler.backupKeySharesToGoogleDrive({
1160
2076
  chainName: this.chainName,
1161
2077
  accountAddress,
1162
2078
  password,
1163
2079
  signedSessionId,
2080
+ sessionPublicKey,
1164
2081
  authToken,
1165
2082
  googleDriveAccessToken,
1166
- traceContext
2083
+ shouldBackupWithPassword,
2084
+ traceContext,
2085
+ approvalQuorum,
2086
+ proposalId
1167
2087
  }));
1168
2088
  }
1169
- async backupKeySharesToICloud({ accountAddress, password = undefined, signedSessionId, authToken, traceContext }) {
2089
+ async backupKeySharesToICloud({ accountAddress, password = undefined, signedSessionId, sessionPublicKey, authToken, shouldBackupWithPassword, traceContext, approvalQuorum, proposalId }) {
1170
2090
  return this.withHandler((handler)=>handler.backupKeySharesToICloud({
1171
2091
  chainName: this.chainName,
1172
2092
  accountAddress,
1173
2093
  password,
1174
2094
  signedSessionId,
2095
+ sessionPublicKey,
1175
2096
  authToken,
1176
- traceContext
2097
+ shouldBackupWithPassword,
2098
+ traceContext,
2099
+ approvalQuorum,
2100
+ proposalId
1177
2101
  }));
1178
2102
  }
1179
2103
  async displayICloudSignIn({ displayContainer }) {
@@ -1189,25 +2113,53 @@ class DynamicWalletClient extends IframeManager {
1189
2113
  return this.withHandler((handler)=>handler.hideICloudSignIn());
1190
2114
  }
1191
2115
  async isICloudAuthenticated() {
2116
+ // The host adapter is in this same runtime, so ask it directly instead of
2117
+ // round-tripping through the iframe's CloudKit JS.
2118
+ if (this.iCloudBackup) {
2119
+ return this.iCloudBackup.isAuthenticated();
2120
+ }
1192
2121
  return this.withHandler((handler)=>handler.isICloudAuthenticated(this.chainName));
1193
2122
  }
1194
- async delegateKeyShares({ accountAddress, password, signedSessionId, authToken, mfaToken, traceContext }) {
2123
+ async delegateKeyShares({ accountAddress, password, signedSessionId, sessionPublicKey, authToken, mfaToken, traceContext, initialSignerRules, approvalQuorum, proposalId }) {
1195
2124
  return this.withHandler((handler)=>handler.delegateKeyShares({
1196
2125
  chainName: this.chainName,
1197
2126
  accountAddress,
1198
2127
  password,
1199
2128
  signedSessionId,
2129
+ sessionPublicKey,
1200
2130
  authToken,
1201
2131
  mfaToken,
1202
- traceContext
2132
+ traceContext,
2133
+ initialSignerRules,
2134
+ approvalQuorum,
2135
+ proposalId
2136
+ }));
2137
+ }
2138
+ async offlineRecovery({ accountAddress, password, signedSessionId, sessionPublicKey, authToken, mfaToken, cloudProvider, cloudProviderAccessToken, recoveryEncryptionPublicKey, shouldBackupWithPassword, traceContext, approvalQuorum, proposalId }) {
2139
+ return this.withHandler((handler)=>handler.offlineRecovery({
2140
+ chainName: this.chainName,
2141
+ accountAddress,
2142
+ password,
2143
+ signedSessionId,
2144
+ sessionPublicKey,
2145
+ authToken,
2146
+ mfaToken,
2147
+ cloudProvider,
2148
+ cloudProviderAccessToken,
2149
+ recoveryEncryptionPublicKey,
2150
+ shouldBackupWithPassword,
2151
+ traceContext,
2152
+ approvalQuorum,
2153
+ proposalId
1203
2154
  }));
1204
2155
  }
1205
- async revokeDelegation({ accountAddress, password, signedSessionId, authToken, mfaToken, traceContext }) {
2156
+ async revokeDelegation({ accountAddress, password, signedSessionId, sessionPublicKey, authToken, mfaToken, traceContext }) {
1206
2157
  return this.withHandler((handler)=>handler.revokeDelegation({
1207
2158
  chainName: this.chainName,
1208
2159
  accountAddress,
1209
2160
  password,
1210
2161
  signedSessionId,
2162
+ sessionPublicKey,
1211
2163
  authToken,
1212
2164
  mfaToken,
1213
2165
  traceContext
@@ -1224,19 +2176,20 @@ class DynamicWalletClient extends IframeManager {
1224
2176
  traceContext
1225
2177
  }));
1226
2178
  }
1227
- async refreshWalletAccountShares({ accountAddress, password, signedSessionId, authToken, mfaToken, elevatedAccessToken, traceContext }) {
2179
+ async refreshWalletAccountShares({ accountAddress, password, signedSessionId, sessionPublicKey, authToken, mfaToken, elevatedAccessToken, traceContext }) {
1228
2180
  return this.withHandler((handler)=>handler.refreshWalletAccountShares({
1229
2181
  chainName: this.chainName,
1230
2182
  accountAddress,
1231
2183
  password,
1232
2184
  signedSessionId,
2185
+ sessionPublicKey,
1233
2186
  authToken,
1234
2187
  mfaToken,
1235
2188
  elevatedAccessToken,
1236
2189
  traceContext
1237
2190
  }));
1238
2191
  }
1239
- async reshare({ accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password, signedSessionId, authToken, mfaToken, elevatedAccessToken, traceContext }) {
2192
+ async reshare({ accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password, signedSessionId, sessionPublicKey, authToken, mfaToken, elevatedAccessToken, traceContext, approvalQuorum, proposalId }) {
1240
2193
  return this.withHandler((handler)=>handler.reshare({
1241
2194
  chainName: this.chainName,
1242
2195
  accountAddress,
@@ -1244,14 +2197,33 @@ class DynamicWalletClient extends IframeManager {
1244
2197
  newThresholdSignatureScheme,
1245
2198
  password,
1246
2199
  signedSessionId,
2200
+ sessionPublicKey,
1247
2201
  authToken,
1248
2202
  mfaToken,
1249
2203
  elevatedAccessToken,
1250
- traceContext
2204
+ traceContext,
2205
+ approvalQuorum,
2206
+ proposalId
1251
2207
  }));
1252
2208
  }
1253
- async exportPrivateKey({ accountAddress, elevatedAccessToken, displayContainer, password, signedSessionId, authToken, mfaToken, traceContext, bitcoinConfig }) {
1254
- const { iframeDisplay } = await this.initializeIframeDisplayForContainer({
2209
+ async exportPrivateKey({ accountAddress, elevatedAccessToken, displayContainer, container, password, signedSessionId, authToken, mfaToken, traceContext, bitcoinConfig, approvalQuorum, proposalId }) {
2210
+ // Exactly one display surface is required. `displayContainer` (a DOM element,
2211
+ // web) injects a visible iframe into the page; `container` (a
2212
+ // WaasSDKContainer, e.g. a React Native native WebView) drives the ceremony
2213
+ // over the message bridge. Both render the key inside their own sandboxed
2214
+ // document, so the raw key never crosses back to the host.
2215
+ if (displayContainer && container) {
2216
+ throw new Error('exportPrivateKey accepts either displayContainer (web) or container (native), not both');
2217
+ }
2218
+ if (!displayContainer && !container) {
2219
+ throw new Error('exportPrivateKey requires a displayContainer (web) or a container (native)');
2220
+ }
2221
+ // The guards above guarantee exactly one is set, so when `container` is
2222
+ // absent `displayContainer` is necessarily present (TS cannot narrow this
2223
+ // across the two runtime guards, hence the assertion).
2224
+ const { iframeDisplay } = container ? await this.initializeDisplayForWaasSDKContainer({
2225
+ waasSDKContainer: container
2226
+ }) : await this.initializeIframeDisplayForContainer({
1255
2227
  container: displayContainer
1256
2228
  });
1257
2229
  if (!iframeDisplay) {
@@ -1266,10 +2238,30 @@ class DynamicWalletClient extends IframeManager {
1266
2238
  mfaToken,
1267
2239
  elevatedAccessToken,
1268
2240
  traceContext,
1269
- bitcoinConfig
2241
+ bitcoinConfig,
2242
+ approvalQuorum,
2243
+ proposalId
1270
2244
  });
1271
2245
  }
1272
2246
  /**
2247
+ * Builds the export Intent for a business-account wallet, to be signed with
2248
+ * the session key and sent as `approvalQuorum` on the export call. Runs no
2249
+ * ceremony, makes no API call and needs no MFA token.
2250
+ */ async prepareExportIntent(request) {
2251
+ return this.withHandler((handler)=>handler.prepareExportIntent(_extends({}, request, {
2252
+ chainName: this.chainName
2253
+ })));
2254
+ }
2255
+ /**
2256
+ * Builds the reshare Intent for a governed backup, delegation or offline
2257
+ * recovery, to be signed with the session key and sent as `approvalQuorum`
2258
+ * on that call. Runs no ceremony and makes no API call.
2259
+ */ async prepareReshareIntent(request) {
2260
+ return this.withHandler((handler)=>handler.prepareReshareIntent(_extends({}, request, {
2261
+ chainName: this.chainName
2262
+ })));
2263
+ }
2264
+ /**
1273
2265
  * Aleo full transaction: view key → MPC sign → prove + broadcast via DPS.
1274
2266
  * Forwards to the iframe's DynamicAleoWalletClient.proveTransaction. View
1275
2267
  * key stays in the iframe throughout.
@@ -1337,30 +2329,33 @@ class DynamicWalletClient extends IframeManager {
1337
2329
  traceContext
1338
2330
  }));
1339
2331
  }
1340
- async updatePassword({ accountAddress, existingPassword, newPassword, signedSessionId, authToken, passwordUpdateBatchId, traceContext }) {
2332
+ async updatePassword({ accountAddress, existingPassword, passwordOverrides, newPassword, signedSessionId, sessionPublicKey, authToken, passwordUpdateBatchId, traceContext }) {
1341
2333
  return this.withHandler((handler)=>handler.updatePassword({
1342
2334
  chainName: this.chainName,
1343
2335
  accountAddress,
1344
2336
  existingPassword,
2337
+ passwordOverrides,
1345
2338
  newPassword,
1346
2339
  signedSessionId,
2340
+ sessionPublicKey,
1347
2341
  authToken,
1348
2342
  passwordUpdateBatchId,
1349
2343
  traceContext
1350
2344
  }));
1351
2345
  }
1352
- async setPassword({ accountAddress, newPassword, signedSessionId, authToken, passwordUpdateBatchId, traceContext }) {
2346
+ async setPassword({ accountAddress, newPassword, signedSessionId, sessionPublicKey, authToken, passwordUpdateBatchId, traceContext }) {
1353
2347
  return this.withHandler((handler)=>handler.setPassword({
1354
2348
  chainName: this.chainName,
1355
2349
  accountAddress,
1356
2350
  newPassword,
1357
2351
  signedSessionId,
2352
+ sessionPublicKey,
1358
2353
  authToken,
1359
2354
  passwordUpdateBatchId,
1360
2355
  traceContext
1361
2356
  }));
1362
2357
  }
1363
- async importPrivateKey({ privateKey, thresholdSignatureScheme, password, signedSessionId, authToken, publicAddressCheck, addressType, traceContext, legacyWalletId }) {
2358
+ async importPrivateKey({ privateKey, thresholdSignatureScheme, password, signedSessionId, authToken, publicAddressCheck, addressType, traceContext, legacyWalletId, isRawScalarImport }) {
1364
2359
  return this.withHandler((handler)=>handler.importPrivateKey({
1365
2360
  chainName: this.chainName,
1366
2361
  privateKey,
@@ -1371,9 +2366,13 @@ class DynamicWalletClient extends IframeManager {
1371
2366
  publicAddressCheck,
1372
2367
  addressType,
1373
2368
  traceContext,
1374
- legacyWalletId
2369
+ legacyWalletId,
2370
+ isRawScalarImport
1375
2371
  }));
1376
2372
  }
2373
+ async migrateFromFireblocks(params) {
2374
+ return this.withHandler((handler)=>handler.migrateFromFireblocks(params));
2375
+ }
1377
2376
  async exportClientKeyshares({ accountAddress, password, signedSessionId, authToken, traceContext }) {
1378
2377
  return this.withHandler((handler)=>handler.exportClientKeyshares({
1379
2378
  chainName: this.chainName,
@@ -1401,7 +2400,115 @@ class DynamicWalletClient extends IframeManager {
1401
2400
  traceContext
1402
2401
  }));
1403
2402
  }
1404
- constructor({ environmentId, authToken, baseApiUrl, baseMPCRelayApiUrl, baseClientKeysharesRelayApiUrl, chainName, sdkVersion, debug, authMode = AuthMode.HEADER, additionalTrustedOrigins }, internalOptions){
2403
+ async getPrivateBalance({ accountAddress, password, signedSessionId, authToken, mfaToken, elevatedAccessToken, networkId, traceContext }) {
2404
+ return this.withHandler((handler)=>handler.getPrivateBalance({
2405
+ chainName: this.chainName,
2406
+ accountAddress,
2407
+ password,
2408
+ signedSessionId,
2409
+ authToken,
2410
+ mfaToken,
2411
+ elevatedAccessToken,
2412
+ networkId,
2413
+ traceContext
2414
+ }));
2415
+ }
2416
+ async getWalletProvider({ accountAddress, password, signedSessionId, authToken, mfaToken, elevatedAccessToken, networkId, traceContext }) {
2417
+ return this.withHandler((handler)=>handler.getWalletProvider({
2418
+ chainName: this.chainName,
2419
+ accountAddress,
2420
+ password,
2421
+ signedSessionId,
2422
+ authToken,
2423
+ mfaToken,
2424
+ elevatedAccessToken,
2425
+ networkId,
2426
+ traceContext
2427
+ }));
2428
+ }
2429
+ async balanceWalletProviderTransaction({ accountAddress, transaction, ttl, password, signedSessionId, authToken, mfaToken, elevatedAccessToken, networkId, traceContext }) {
2430
+ if (!transaction) {
2431
+ throw new Error('balanceWalletProviderTransaction: transaction is required');
2432
+ }
2433
+ return this.withHandler((handler)=>handler.balanceWalletProviderTransaction({
2434
+ chainName: this.chainName,
2435
+ accountAddress,
2436
+ transaction,
2437
+ ttl,
2438
+ password,
2439
+ signedSessionId,
2440
+ authToken,
2441
+ mfaToken,
2442
+ elevatedAccessToken,
2443
+ networkId,
2444
+ traceContext
2445
+ }));
2446
+ }
2447
+ async registerDust({ accountAddress, password, signedSessionId, authToken, mfaToken, elevatedAccessToken, networkId, traceContext }) {
2448
+ return this.withHandler((handler)=>handler.registerDust({
2449
+ chainName: this.chainName,
2450
+ accountAddress,
2451
+ password,
2452
+ signedSessionId,
2453
+ authToken,
2454
+ mfaToken,
2455
+ elevatedAccessToken,
2456
+ networkId,
2457
+ traceContext
2458
+ }));
2459
+ }
2460
+ async createTransferTransaction({ accountAddress, transfers, ttlMinutes, password, signedSessionId, authToken, mfaToken, elevatedAccessToken, networkId, traceContext }) {
2461
+ return this.withHandler((handler)=>handler.createTransferTransaction({
2462
+ chainName: this.chainName,
2463
+ accountAddress,
2464
+ transfers,
2465
+ ttlMinutes,
2466
+ password,
2467
+ signedSessionId,
2468
+ authToken,
2469
+ mfaToken,
2470
+ elevatedAccessToken,
2471
+ networkId,
2472
+ traceContext
2473
+ }));
2474
+ }
2475
+ async submitTransaction({ accountAddress, transaction, waitForBalance, tokenType, balanceBefore, password, signedSessionId, authToken, mfaToken, elevatedAccessToken, networkId, traceContext }) {
2476
+ if (!transaction) {
2477
+ throw new Error('submitTransaction: transaction is required');
2478
+ }
2479
+ return this.withHandler((handler)=>handler.submitTransaction({
2480
+ chainName: this.chainName,
2481
+ accountAddress,
2482
+ transaction,
2483
+ waitForBalance,
2484
+ tokenType,
2485
+ balanceBefore,
2486
+ password,
2487
+ signedSessionId,
2488
+ authToken,
2489
+ mfaToken,
2490
+ elevatedAccessToken,
2491
+ networkId,
2492
+ traceContext
2493
+ }));
2494
+ }
2495
+ async revertTransaction({ accountAddress, transaction, all, resetCache, password, signedSessionId, authToken, mfaToken, elevatedAccessToken, networkId, traceContext }) {
2496
+ return this.withHandler((handler)=>handler.revertTransaction({
2497
+ chainName: this.chainName,
2498
+ accountAddress,
2499
+ transaction,
2500
+ all,
2501
+ resetCache,
2502
+ password,
2503
+ signedSessionId,
2504
+ authToken,
2505
+ mfaToken,
2506
+ elevatedAccessToken,
2507
+ networkId,
2508
+ traceContext
2509
+ }));
2510
+ }
2511
+ constructor({ environmentId, authToken, baseApiUrl, baseMPCRelayApiUrl, baseClientKeysharesRelayApiUrl, chainName, sdkVersion, debug, authMode = AuthMode.HEADER, additionalTrustedOrigins, hostOrigin, iframeLoadTimeout, maxRetryAttempts, eagerlyRecoverKeyShares }, internalOptions){
1405
2512
  super({
1406
2513
  environmentId,
1407
2514
  authToken,
@@ -1412,10 +2519,14 @@ class DynamicWalletClient extends IframeManager {
1412
2519
  sdkVersion,
1413
2520
  debug,
1414
2521
  authMode,
1415
- additionalTrustedOrigins
2522
+ additionalTrustedOrigins,
2523
+ hostOrigin,
2524
+ iframeLoadTimeout,
2525
+ maxRetryAttempts,
2526
+ eagerlyRecoverKeyShares
1416
2527
  }, internalOptions);
1417
2528
  // Note: secureStorage and getSignedSessionId are already set by IframeManager constructor
1418
2529
  }
1419
2530
  }
1420
2531
 
1421
- export { DynamicWalletClient, createIframeWaasSDKContainer };
2532
+ export { DynamicWalletClient, assertPreparedSigningIntentMatchesRequest, createIframeWaasSDKContainer, preconnectWaasIframe };