@aztec/wallet-sdk 4.1.2 → 4.2.0-aztecnr-rc.2
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/dest/base-wallet/base_wallet.d.ts +23 -17
- package/dest/base-wallet/base_wallet.d.ts.map +1 -1
- package/dest/base-wallet/base_wallet.js +70 -45
- package/dest/base-wallet/index.d.ts +2 -2
- package/dest/base-wallet/index.d.ts.map +1 -1
- package/dest/crypto.d.ts +39 -1
- package/dest/crypto.d.ts.map +1 -1
- package/dest/crypto.js +88 -0
- package/dest/extension/provider/extension_wallet.d.ts +2 -5
- package/dest/extension/provider/extension_wallet.d.ts.map +1 -1
- package/dest/extension/provider/index.d.ts +2 -2
- package/dest/extension/provider/index.d.ts.map +1 -1
- package/dest/iframe/handlers/iframe_connection_handler.d.ts +118 -0
- package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
- package/dest/iframe/handlers/iframe_connection_handler.js +228 -0
- package/dest/iframe/handlers/index.d.ts +2 -0
- package/dest/iframe/handlers/index.d.ts.map +1 -0
- package/dest/iframe/handlers/index.js +1 -0
- package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
- package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
- package/dest/iframe/provider/iframe_discovery.js +167 -0
- package/dest/iframe/provider/iframe_provider.d.ts +65 -0
- package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
- package/dest/iframe/provider/iframe_provider.js +257 -0
- package/dest/iframe/provider/iframe_wallet.d.ts +68 -0
- package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
- package/dest/iframe/provider/iframe_wallet.js +200 -0
- package/dest/iframe/provider/index.d.ts +4 -0
- package/dest/iframe/provider/index.d.ts.map +1 -0
- package/dest/iframe/provider/index.js +3 -0
- package/dest/manager/types.d.ts +3 -2
- package/dest/manager/types.d.ts.map +1 -1
- package/dest/manager/wallet_manager.d.ts +1 -1
- package/dest/manager/wallet_manager.d.ts.map +1 -1
- package/dest/manager/wallet_manager.js +46 -16
- package/dest/types.d.ts +14 -2
- package/dest/types.d.ts.map +1 -1
- package/dest/types.js +4 -0
- package/package.json +12 -8
- package/src/base-wallet/base_wallet.ts +122 -78
- package/src/base-wallet/index.ts +1 -1
- package/src/crypto.ts +104 -0
- package/src/extension/provider/extension_wallet.ts +1 -6
- package/src/extension/provider/index.ts +1 -1
- package/src/iframe/handlers/iframe_connection_handler.ts +328 -0
- package/src/iframe/handlers/index.ts +7 -0
- package/src/iframe/provider/iframe_discovery.ts +185 -0
- package/src/iframe/provider/iframe_provider.ts +331 -0
- package/src/iframe/provider/iframe_wallet.ts +229 -0
- package/src/iframe/provider/index.ts +3 -0
- package/src/manager/types.ts +2 -1
- package/src/manager/wallet_manager.ts +48 -14
- package/src/types.ts +13 -0
|
@@ -6,7 +6,7 @@ import { schemaHasMethod } from '@aztec/foundation/schemas';
|
|
|
6
6
|
import type { FunctionsOf } from '@aztec/foundation/types';
|
|
7
7
|
|
|
8
8
|
import { type EncryptedPayload, decrypt, encrypt } from '../../crypto.js';
|
|
9
|
-
import { type WalletMessage, WalletMessageType, type WalletResponse } from '../../types.js';
|
|
9
|
+
import { type DisconnectCallback, type WalletMessage, WalletMessageType, type WalletResponse } from '../../types.js';
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Internal type representing a wallet method call before encryption.
|
|
@@ -19,11 +19,6 @@ type WalletMethodCall = {
|
|
|
19
19
|
args: unknown[];
|
|
20
20
|
};
|
|
21
21
|
|
|
22
|
-
/**
|
|
23
|
-
* Callback type for wallet disconnect events.
|
|
24
|
-
*/
|
|
25
|
-
export type DisconnectCallback = () => void;
|
|
26
|
-
|
|
27
22
|
/**
|
|
28
23
|
* A wallet implementation that communicates with browser extension wallets
|
|
29
24
|
* using an encrypted MessageChannel.
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IframeConnectionHandler — wallet-side of the cross-origin iframe protocol.
|
|
3
|
+
*
|
|
4
|
+
* This mirrors {@link BackgroundConnectionHandler} from `@aztec/wallet-sdk/extension/handlers`
|
|
5
|
+
* but uses `window.postMessage` instead of browser.runtime messaging.
|
|
6
|
+
*
|
|
7
|
+
* Message flow (wallet receives):
|
|
8
|
+
* parent → DISCOVERY → show approval UI → send DISCOVERY_RESPONSE
|
|
9
|
+
* parent → KEY_EXCHANGE_REQUEST → ECDH → send KEY_EXCHANGE_RESPONSE
|
|
10
|
+
* parent → SECURE_MESSAGE → decrypt → Wallet → encrypt → SECURE_RESPONSE
|
|
11
|
+
* parent → DISCONNECT → terminate session
|
|
12
|
+
*
|
|
13
|
+
* The wallet announces itself by posting WALLET_READY as soon as the handler starts,
|
|
14
|
+
* so the dApp knows it can send a discovery request.
|
|
15
|
+
*/
|
|
16
|
+
import type { ChainInfo } from '@aztec/aztec.js/account';
|
|
17
|
+
import { createLogger } from '@aztec/aztec.js/log';
|
|
18
|
+
import type { Wallet } from '@aztec/aztec.js/wallet';
|
|
19
|
+
import { WalletSchema } from '@aztec/aztec.js/wallet';
|
|
20
|
+
import { jsonStringify } from '@aztec/foundation/json-rpc';
|
|
21
|
+
import { parseWithOptionals, schemaHasMethod } from '@aztec/foundation/schemas';
|
|
22
|
+
|
|
23
|
+
import {
|
|
24
|
+
type EncryptedPayload,
|
|
25
|
+
decrypt,
|
|
26
|
+
deriveSessionKeys,
|
|
27
|
+
encrypt,
|
|
28
|
+
exportPublicKey,
|
|
29
|
+
generateKeyPair,
|
|
30
|
+
importPublicKey,
|
|
31
|
+
} from '../../crypto.js';
|
|
32
|
+
import { type WalletMessage, WalletMessageType, type WalletResponse } from '../../types.js';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A pending discovery request from a dApp (before user approval).
|
|
36
|
+
*/
|
|
37
|
+
export interface PendingSession {
|
|
38
|
+
/** Unique request identifier */
|
|
39
|
+
requestId: string;
|
|
40
|
+
/** Application identifier */
|
|
41
|
+
appId: string;
|
|
42
|
+
/** Origin URL of the requesting page */
|
|
43
|
+
origin: string;
|
|
44
|
+
/** Approval status */
|
|
45
|
+
status: 'pending' | 'approved';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* An active session (after key exchange).
|
|
50
|
+
*/
|
|
51
|
+
export interface ActiveSession {
|
|
52
|
+
/** Session identifier (same as the discovery requestId) */
|
|
53
|
+
sessionId: string;
|
|
54
|
+
/** AES-256-GCM shared key for this session */
|
|
55
|
+
sharedKey: CryptoKey;
|
|
56
|
+
/** Verification hash for emoji display */
|
|
57
|
+
verificationHash: string;
|
|
58
|
+
/** Origin URL of the connected dApp */
|
|
59
|
+
origin: string;
|
|
60
|
+
/** Application identifier */
|
|
61
|
+
appId: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Configuration for the iframe connection handler.
|
|
66
|
+
*/
|
|
67
|
+
export interface IframeConnectionConfig {
|
|
68
|
+
/** Unique wallet identifier */
|
|
69
|
+
walletId: string;
|
|
70
|
+
/** Display name for the wallet */
|
|
71
|
+
walletName: string;
|
|
72
|
+
/** Wallet version string */
|
|
73
|
+
walletVersion: string;
|
|
74
|
+
/** Optional wallet icon URL */
|
|
75
|
+
walletIcon?: string;
|
|
76
|
+
/** Origins allowed to connect. If empty or undefined, all origins are allowed (dev mode). */
|
|
77
|
+
allowedOrigins?: string[];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Event callbacks for the iframe connection handler.
|
|
82
|
+
*/
|
|
83
|
+
export interface IframeConnectionCallbacks {
|
|
84
|
+
/** Called when a new discovery request arrives — wallet can show approval UI */
|
|
85
|
+
onPendingDiscovery?: (session: PendingSession) => void;
|
|
86
|
+
/** Called when a session is established (key exchange complete) */
|
|
87
|
+
onSessionEstablished?: (session: ActiveSession) => void;
|
|
88
|
+
/** Called when a session is terminated */
|
|
89
|
+
onSessionTerminated?: (sessionId: string) => void;
|
|
90
|
+
/** Called when a key exchange completes — show verificationHash as emojis to the user */
|
|
91
|
+
onVerificationHash?: (verificationHash: string) => void;
|
|
92
|
+
/**
|
|
93
|
+
* Resolves the Wallet instance to use for a given dApp and chain.
|
|
94
|
+
* Called when an encrypted message arrives and needs to be dispatched.
|
|
95
|
+
*/
|
|
96
|
+
getWallet: (appId: string, chainInfo: ChainInfo) => Promise<Wallet>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Handles the wallet side of the cross-origin iframe protocol.
|
|
101
|
+
*
|
|
102
|
+
* Manages the full lifecycle: discovery, ECDH key exchange, encrypted message
|
|
103
|
+
* dispatch to a {@link Wallet} instance, and session termination.
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* ```typescript
|
|
107
|
+
* const handler = new IframeConnectionHandler(
|
|
108
|
+
* { walletId: 'my-wallet', walletName: 'My Wallet', walletVersion: '1.0.0' },
|
|
109
|
+
* {
|
|
110
|
+
* onPendingDiscovery: (session) => showApprovalUI(session),
|
|
111
|
+
* getWallet: (appId, chainInfo) => createWalletForApp(appId, chainInfo),
|
|
112
|
+
* },
|
|
113
|
+
* );
|
|
114
|
+
* handler.start();
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
export class IframeConnectionHandler {
|
|
118
|
+
private pendingSessions = new Map<string, PendingSession>();
|
|
119
|
+
private activeSessions = new Map<string, ActiveSession>();
|
|
120
|
+
private log = createLogger('wallet:iframe-handler');
|
|
121
|
+
|
|
122
|
+
constructor(
|
|
123
|
+
private config: IframeConnectionConfig,
|
|
124
|
+
private callbacks: IframeConnectionCallbacks,
|
|
125
|
+
) {}
|
|
126
|
+
|
|
127
|
+
start(): void {
|
|
128
|
+
window.addEventListener('message', this.handleMessage);
|
|
129
|
+
this.postToParent({ type: WalletMessageType.WALLET_READY });
|
|
130
|
+
this.log.info('IframeConnectionHandler started, posted WALLET_READY');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
stop(): void {
|
|
134
|
+
window.removeEventListener('message', this.handleMessage);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
approveDiscovery(requestId: string): void {
|
|
138
|
+
const pending = this.pendingSessions.get(requestId);
|
|
139
|
+
if (!pending || pending.status !== 'pending') {
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
pending.status = 'approved';
|
|
144
|
+
this.postToOrigin(pending.origin, {
|
|
145
|
+
type: WalletMessageType.DISCOVERY_RESPONSE,
|
|
146
|
+
requestId,
|
|
147
|
+
walletInfo: {
|
|
148
|
+
id: this.config.walletId,
|
|
149
|
+
name: this.config.walletName,
|
|
150
|
+
version: this.config.walletVersion,
|
|
151
|
+
icon: this.config.walletIcon,
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
this.log.info(`Discovery approved for requestId=${requestId}`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
rejectDiscovery(requestId: string): void {
|
|
158
|
+
this.pendingSessions.delete(requestId);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
terminateSession(sessionId: string): void {
|
|
162
|
+
const session = this.activeSessions.get(sessionId);
|
|
163
|
+
if (session) {
|
|
164
|
+
this.postToOrigin(session.origin, {
|
|
165
|
+
type: WalletMessageType.SESSION_DISCONNECTED,
|
|
166
|
+
sessionId,
|
|
167
|
+
});
|
|
168
|
+
this.activeSessions.delete(sessionId);
|
|
169
|
+
this.callbacks.onSessionTerminated?.(sessionId);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
getPendingSessions(): PendingSession[] {
|
|
174
|
+
return Array.from(this.pendingSessions.values()).filter(s => s.status === 'pending');
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private handleMessage = (event: MessageEvent): void => {
|
|
178
|
+
void this.handleMessageAsync(event);
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
private async handleMessageAsync(event: MessageEvent): Promise<void> {
|
|
182
|
+
if (this.config.allowedOrigins && this.config.allowedOrigins.length > 0) {
|
|
183
|
+
if (!this.config.allowedOrigins.includes(event.origin)) {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const msg = event.data;
|
|
189
|
+
if (!msg || typeof msg !== 'object' || !msg.type) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
switch (msg.type) {
|
|
194
|
+
case WalletMessageType.DISCOVERY:
|
|
195
|
+
this.handleDiscoveryRequest(msg, event.origin);
|
|
196
|
+
break;
|
|
197
|
+
case WalletMessageType.KEY_EXCHANGE_REQUEST:
|
|
198
|
+
await this.handleKeyExchangeRequest(msg, event.origin);
|
|
199
|
+
break;
|
|
200
|
+
case WalletMessageType.SECURE_MESSAGE:
|
|
201
|
+
await this.handleSecureMessage(msg);
|
|
202
|
+
break;
|
|
203
|
+
case WalletMessageType.DISCONNECT:
|
|
204
|
+
this.terminateSession(msg.sessionId);
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private handleDiscoveryRequest(msg: Record<string, unknown>, origin: string): void {
|
|
210
|
+
// eslint-disable-next-line jsdoc/require-jsdoc
|
|
211
|
+
const { requestId, appId } = msg as { requestId: string; appId: string };
|
|
212
|
+
const pending: PendingSession = { requestId, appId, origin, status: 'pending' };
|
|
213
|
+
this.pendingSessions.set(requestId, pending);
|
|
214
|
+
this.log.info(`Discovery request from appId=${appId} origin=${origin}`);
|
|
215
|
+
this.callbacks.onPendingDiscovery?.(pending);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private async handleKeyExchangeRequest(msg: Record<string, unknown>, origin: string): Promise<void> {
|
|
219
|
+
const { requestId, publicKey: appPublicKeyRaw } = msg as {
|
|
220
|
+
// eslint-disable-next-line jsdoc/require-jsdoc
|
|
221
|
+
requestId: string;
|
|
222
|
+
// eslint-disable-next-line jsdoc/require-jsdoc
|
|
223
|
+
publicKey: { kty: string; crv: string; x: string; y: string };
|
|
224
|
+
};
|
|
225
|
+
const pending = this.pendingSessions.get(requestId);
|
|
226
|
+
if (!pending || pending.status !== 'approved') {
|
|
227
|
+
this.log.warn(`Key exchange for unknown/unapproved requestId=${requestId}`);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
try {
|
|
232
|
+
const keyPair = await generateKeyPair();
|
|
233
|
+
const walletPublicKey = await exportPublicKey(keyPair.publicKey);
|
|
234
|
+
const appPublicKey = await importPublicKey(appPublicKeyRaw);
|
|
235
|
+
const sessionKeys = await deriveSessionKeys(keyPair, appPublicKey, false);
|
|
236
|
+
|
|
237
|
+
const session: ActiveSession = {
|
|
238
|
+
sessionId: requestId,
|
|
239
|
+
sharedKey: sessionKeys.encryptionKey,
|
|
240
|
+
verificationHash: sessionKeys.verificationHash,
|
|
241
|
+
origin: pending.origin,
|
|
242
|
+
appId: pending.appId,
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
this.activeSessions.set(requestId, session);
|
|
246
|
+
this.pendingSessions.delete(requestId);
|
|
247
|
+
|
|
248
|
+
this.postToOrigin(origin, {
|
|
249
|
+
type: WalletMessageType.KEY_EXCHANGE_RESPONSE,
|
|
250
|
+
requestId,
|
|
251
|
+
publicKey: walletPublicKey,
|
|
252
|
+
verificationHash: sessionKeys.verificationHash,
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
this.callbacks.onVerificationHash?.(sessionKeys.verificationHash);
|
|
256
|
+
this.callbacks.onSessionEstablished?.(session);
|
|
257
|
+
this.log.info(`Key exchange complete, sessionId=${requestId}`);
|
|
258
|
+
} catch (err) {
|
|
259
|
+
this.log.error(`Key exchange failed: ${err}`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
private async handleSecureMessage(msg: Record<string, unknown>): Promise<void> {
|
|
264
|
+
// eslint-disable-next-line jsdoc/require-jsdoc
|
|
265
|
+
const { sessionId, encrypted } = msg as { sessionId: string; encrypted: EncryptedPayload };
|
|
266
|
+
const session = this.activeSessions.get(sessionId);
|
|
267
|
+
if (!session) {
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
let walletMessage: WalletMessage;
|
|
272
|
+
try {
|
|
273
|
+
walletMessage = await decrypt<WalletMessage>(session.sharedKey, encrypted);
|
|
274
|
+
} catch {
|
|
275
|
+
this.log.warn(`Decryption failed for sessionId=${sessionId}`);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const { messageId, type, args, chainInfo, appId } = walletMessage;
|
|
280
|
+
|
|
281
|
+
let result: unknown;
|
|
282
|
+
let error: string | undefined;
|
|
283
|
+
|
|
284
|
+
try {
|
|
285
|
+
const wallet = await this.callbacks.getWallet(appId, chainInfo);
|
|
286
|
+
|
|
287
|
+
if (!schemaHasMethod(WalletSchema, type)) {
|
|
288
|
+
throw new Error(`Unknown wallet method: ${type}`);
|
|
289
|
+
}
|
|
290
|
+
// Zod's AnyZodTuple rejects optional tuple items typed as `T | undefined`
|
|
291
|
+
const sanitizedArgs = await parseWithOptionals(args, WalletSchema[type].parameters() as any);
|
|
292
|
+
result = await (wallet as Record<string, (...a: unknown[]) => Promise<unknown>>)[type](...sanitizedArgs);
|
|
293
|
+
} catch (err: unknown) {
|
|
294
|
+
error = err instanceof Error ? err.message : String(err);
|
|
295
|
+
this.log.error(`Error handling ${type}: ${error}`);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const response: WalletResponse = {
|
|
299
|
+
messageId,
|
|
300
|
+
walletId: this.config.walletId,
|
|
301
|
+
result,
|
|
302
|
+
error,
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
try {
|
|
306
|
+
const encryptedResponse = await encrypt(session.sharedKey, jsonStringify(response));
|
|
307
|
+
this.postToOrigin(session.origin, {
|
|
308
|
+
type: WalletMessageType.SECURE_RESPONSE,
|
|
309
|
+
sessionId,
|
|
310
|
+
encrypted: encryptedResponse,
|
|
311
|
+
});
|
|
312
|
+
} catch (err) {
|
|
313
|
+
this.log.error(`Encryption of response failed: ${err}`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private postToParent(msg: object): void {
|
|
318
|
+
if (window.parent !== window) {
|
|
319
|
+
window.parent.postMessage(msg, '*');
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
private postToOrigin(origin: string, msg: object): void {
|
|
324
|
+
if (window.parent !== window) {
|
|
325
|
+
window.parent.postMessage(msg, origin);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Web wallet discovery — creates {@link IframeWalletProvider} instances from a list of URLs.
|
|
3
|
+
*
|
|
4
|
+
* For each configured URL we probe the wallet by loading a tiny invisible iframe,
|
|
5
|
+
* waiting for WALLET_READY, then sending a DISCOVERY request. On a successful
|
|
6
|
+
* DISCOVERY_RESPONSE we emit an IframeWalletProvider to the caller.
|
|
7
|
+
*
|
|
8
|
+
* This is intentionally lightweight (no key exchange yet) — key exchange happens
|
|
9
|
+
* later when the user selects the wallet and calls `provider.establishSecureChannel()`.
|
|
10
|
+
*/
|
|
11
|
+
import type { ChainInfo } from '@aztec/aztec.js/account';
|
|
12
|
+
import { promiseWithResolvers } from '@aztec/foundation/promise';
|
|
13
|
+
|
|
14
|
+
import type { DiscoverySession, WalletProvider } from '../../manager/types.js';
|
|
15
|
+
import { type WalletInfo, WalletMessageType } from '../../types.js';
|
|
16
|
+
import { IframeWalletProvider } from './iframe_provider.js';
|
|
17
|
+
|
|
18
|
+
const PROBE_TIMEOUT_MS = 10_000;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Probes a list of web wallet URLs and returns a {@link DiscoverySession} compatible
|
|
22
|
+
* with WalletManager's `getAvailableWallets()` interface.
|
|
23
|
+
*
|
|
24
|
+
* Discovered {@link IframeWalletProvider} instances are yielded asynchronously as each
|
|
25
|
+
* wallet responds to the probe.
|
|
26
|
+
*
|
|
27
|
+
* @param walletUrls - URLs of web wallets to probe
|
|
28
|
+
* @param chainInfo - Network information to pass during discovery
|
|
29
|
+
* @returns A cancellable discovery session
|
|
30
|
+
*/
|
|
31
|
+
export function discoverWebWallets(walletUrls: string[], chainInfo: ChainInfo): DiscoverySession {
|
|
32
|
+
const { promise: donePromise, resolve: resolveDone } = promiseWithResolvers<void>();
|
|
33
|
+
|
|
34
|
+
/* eslint-disable jsdoc/require-jsdoc */
|
|
35
|
+
type IteratorState =
|
|
36
|
+
| { status: 'discovering'; resolve: ((result: IteratorResult<WalletProvider>) => void) | null }
|
|
37
|
+
| { status: 'done' };
|
|
38
|
+
/* eslint-enable jsdoc/require-jsdoc */
|
|
39
|
+
|
|
40
|
+
let state: IteratorState = { status: 'discovering', resolve: null };
|
|
41
|
+
const pendingProviders: WalletProvider[] = [];
|
|
42
|
+
|
|
43
|
+
// eslint-disable-next-line jsdoc/require-jsdoc
|
|
44
|
+
function emit(provider: WalletProvider) {
|
|
45
|
+
if (state.status !== 'discovering') {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (state.resolve) {
|
|
49
|
+
const resolve = state.resolve;
|
|
50
|
+
state.resolve = null;
|
|
51
|
+
resolve({ value: provider, done: false });
|
|
52
|
+
} else {
|
|
53
|
+
pendingProviders.push(provider);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// eslint-disable-next-line jsdoc/require-jsdoc
|
|
58
|
+
function markComplete() {
|
|
59
|
+
if (state.status !== 'discovering') {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const pendingResolve = state.resolve;
|
|
63
|
+
state = { status: 'done' };
|
|
64
|
+
resolveDone();
|
|
65
|
+
if (pendingResolve) {
|
|
66
|
+
pendingResolve({ value: undefined as unknown as WalletProvider, done: true });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Probe all URLs in parallel
|
|
71
|
+
const probes = walletUrls.map(url =>
|
|
72
|
+
probeWallet(url, chainInfo, PROBE_TIMEOUT_MS).then(
|
|
73
|
+
provider => {
|
|
74
|
+
if (provider) {
|
|
75
|
+
emit(provider);
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
() => {
|
|
79
|
+
// ignore probe errors
|
|
80
|
+
},
|
|
81
|
+
),
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
void Promise.all(probes).then(markComplete);
|
|
85
|
+
|
|
86
|
+
const wallets: AsyncIterable<WalletProvider> = {
|
|
87
|
+
// eslint-disable-next-line jsdoc/require-jsdoc
|
|
88
|
+
[Symbol.asyncIterator](): AsyncIterator<WalletProvider> {
|
|
89
|
+
return {
|
|
90
|
+
// eslint-disable-next-line jsdoc/require-jsdoc
|
|
91
|
+
next(): Promise<IteratorResult<WalletProvider>> {
|
|
92
|
+
if (pendingProviders.length > 0) {
|
|
93
|
+
return Promise.resolve({ value: pendingProviders.shift()!, done: false });
|
|
94
|
+
}
|
|
95
|
+
if (state.status === 'done') {
|
|
96
|
+
return Promise.resolve({ value: undefined as unknown as WalletProvider, done: true });
|
|
97
|
+
}
|
|
98
|
+
return new Promise(resolve => {
|
|
99
|
+
if (state.status === 'discovering') {
|
|
100
|
+
state.resolve = resolve;
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
},
|
|
104
|
+
// eslint-disable-next-line jsdoc/require-jsdoc
|
|
105
|
+
return(): Promise<IteratorResult<WalletProvider>> {
|
|
106
|
+
markComplete();
|
|
107
|
+
return Promise.resolve({ value: undefined as unknown as WalletProvider, done: true });
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
wallets,
|
|
115
|
+
done: donePromise,
|
|
116
|
+
cancel: markComplete,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Probes a single web wallet URL.
|
|
122
|
+
* Creates a temporary hidden iframe, waits for WALLET_READY, sends DISCOVERY_REQUEST.
|
|
123
|
+
* Returns an IframeWalletProvider on success, null on timeout/failure.
|
|
124
|
+
* @internal
|
|
125
|
+
*/
|
|
126
|
+
function probeWallet(walletUrl: string, chainInfo: ChainInfo, timeoutMs: number): Promise<IframeWalletProvider | null> {
|
|
127
|
+
const walletOrigin = new URL(walletUrl).origin;
|
|
128
|
+
const iframe = document.createElement('iframe');
|
|
129
|
+
iframe.src = walletUrl;
|
|
130
|
+
iframe.style.cssText = 'display:none;width:0;height:0;border:none;position:absolute;top:-9999px;';
|
|
131
|
+
iframe.allow = 'storage-access; cross-origin-isolated';
|
|
132
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
133
|
+
|
|
134
|
+
// Register listener BEFORE appending to DOM to avoid race with WALLET_READY
|
|
135
|
+
const result = new Promise<IframeWalletProvider | null>(resolve => {
|
|
136
|
+
const cleanup = () => {
|
|
137
|
+
if (iframe.parentNode) {
|
|
138
|
+
iframe.parentNode.removeChild(iframe);
|
|
139
|
+
}
|
|
140
|
+
window.removeEventListener('message', handler);
|
|
141
|
+
clearTimeout(timer);
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
timer = setTimeout(() => {
|
|
145
|
+
cleanup();
|
|
146
|
+
resolve(null);
|
|
147
|
+
}, timeoutMs);
|
|
148
|
+
|
|
149
|
+
let step: 'waiting-ready' | 'waiting-discovery' = 'waiting-ready';
|
|
150
|
+
const requestId = globalThis.crypto.randomUUID();
|
|
151
|
+
|
|
152
|
+
// eslint-disable-next-line jsdoc/require-jsdoc
|
|
153
|
+
function handler(event: MessageEvent) {
|
|
154
|
+
if (event.origin !== walletOrigin) {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const msg = event.data;
|
|
158
|
+
if (!msg || typeof msg !== 'object') {
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (step === 'waiting-ready' && msg.type === WalletMessageType.WALLET_READY) {
|
|
163
|
+
step = 'waiting-discovery';
|
|
164
|
+
iframe.contentWindow?.postMessage(
|
|
165
|
+
{ type: WalletMessageType.DISCOVERY, requestId, appId: 'discovery-probe' },
|
|
166
|
+
walletOrigin,
|
|
167
|
+
);
|
|
168
|
+
} else if (
|
|
169
|
+
step === 'waiting-discovery' &&
|
|
170
|
+
msg.type === WalletMessageType.DISCOVERY_RESPONSE &&
|
|
171
|
+
msg.requestId === requestId
|
|
172
|
+
) {
|
|
173
|
+
const info = msg.walletInfo as WalletInfo;
|
|
174
|
+
cleanup();
|
|
175
|
+
resolve(new IframeWalletProvider(info.id, info.name, info.icon, walletUrl, chainInfo));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
window.addEventListener('message', handler);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
document.body.appendChild(iframe);
|
|
183
|
+
|
|
184
|
+
return result;
|
|
185
|
+
}
|