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