@aztec/wallet-sdk 0.0.1-commit.0208eb9
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/README.md +321 -0
- package/dest/base-wallet/base_wallet.d.ts +117 -0
- package/dest/base-wallet/base_wallet.d.ts.map +1 -0
- package/dest/base-wallet/base_wallet.js +271 -0
- package/dest/base-wallet/index.d.ts +2 -0
- package/dest/base-wallet/index.d.ts.map +1 -0
- package/dest/base-wallet/index.js +1 -0
- package/dest/crypto.d.ts +192 -0
- package/dest/crypto.d.ts.map +1 -0
- package/dest/crypto.js +394 -0
- package/dest/emoji_alphabet.d.ts +35 -0
- package/dest/emoji_alphabet.d.ts.map +1 -0
- package/dest/emoji_alphabet.js +299 -0
- package/dest/extension/handlers/background_connection_handler.d.ts +158 -0
- package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
- package/dest/extension/handlers/background_connection_handler.js +258 -0
- package/dest/extension/handlers/content_script_connection_handler.d.ts +56 -0
- package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
- package/dest/extension/handlers/content_script_connection_handler.js +174 -0
- package/dest/extension/handlers/index.d.ts +12 -0
- package/dest/extension/handlers/index.d.ts.map +1 -0
- package/dest/extension/handlers/index.js +10 -0
- package/dest/extension/handlers/internal_message_types.d.ts +63 -0
- package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
- package/dest/extension/handlers/internal_message_types.js +22 -0
- package/dest/extension/provider/extension_provider.d.ts +107 -0
- package/dest/extension/provider/extension_provider.d.ts.map +1 -0
- package/dest/extension/provider/extension_provider.js +160 -0
- package/dest/extension/provider/extension_wallet.d.ts +131 -0
- package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
- package/dest/extension/provider/extension_wallet.js +271 -0
- package/dest/extension/provider/index.d.ts +3 -0
- package/dest/extension/provider/index.d.ts.map +1 -0
- package/dest/extension/provider/index.js +2 -0
- package/dest/manager/index.d.ts +3 -0
- package/dest/manager/index.d.ts.map +1 -0
- package/dest/manager/index.js +1 -0
- package/dest/manager/types.d.ts +167 -0
- package/dest/manager/types.d.ts.map +1 -0
- package/dest/manager/types.js +19 -0
- package/dest/manager/wallet_manager.d.ts +70 -0
- package/dest/manager/wallet_manager.d.ts.map +1 -0
- package/dest/manager/wallet_manager.js +226 -0
- package/dest/types.d.ts +123 -0
- package/dest/types.d.ts.map +1 -0
- package/dest/types.js +11 -0
- package/package.json +99 -0
- package/src/base-wallet/base_wallet.ts +394 -0
- package/src/base-wallet/index.ts +1 -0
- package/src/crypto.ts +499 -0
- package/src/emoji_alphabet.ts +317 -0
- package/src/extension/handlers/background_connection_handler.ts +423 -0
- package/src/extension/handlers/content_script_connection_handler.ts +246 -0
- package/src/extension/handlers/index.ts +25 -0
- package/src/extension/handlers/internal_message_types.ts +69 -0
- package/src/extension/provider/extension_provider.ts +233 -0
- package/src/extension/provider/extension_wallet.ts +321 -0
- package/src/extension/provider/index.ts +7 -0
- package/src/manager/index.ts +12 -0
- package/src/manager/types.ts +177 -0
- package/src/manager/wallet_manager.ts +259 -0
- package/src/types.ts +132 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { ChainInfo } from '@aztec/aztec.js/account';
|
|
2
|
+
import { type ConnectedWalletInfo, type WalletInfo } from '../../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* A discovered wallet before key exchange.
|
|
5
|
+
* Has basic info and MessagePort, but no shared key yet.
|
|
6
|
+
*
|
|
7
|
+
* Call {@link establishSecureChannel} to perform key exchange and get a connected wallet.
|
|
8
|
+
*/
|
|
9
|
+
export declare class DiscoveredWallet {
|
|
10
|
+
/** Basic wallet information (id, name, icon, version) */
|
|
11
|
+
readonly info: WalletInfo;
|
|
12
|
+
/** The MessagePort for private communication with the wallet */
|
|
13
|
+
readonly port: MessagePort;
|
|
14
|
+
/** Request ID for correlation */
|
|
15
|
+
readonly requestId: string;
|
|
16
|
+
constructor(
|
|
17
|
+
/** Basic wallet information (id, name, icon, version) */
|
|
18
|
+
info: WalletInfo,
|
|
19
|
+
/** The MessagePort for private communication with the wallet */
|
|
20
|
+
port: MessagePort,
|
|
21
|
+
/** Request ID for correlation */
|
|
22
|
+
requestId: string);
|
|
23
|
+
/**
|
|
24
|
+
* Establishes a secure connection with this wallet.
|
|
25
|
+
*
|
|
26
|
+
* This method:
|
|
27
|
+
* 1. Generates an ECDH key pair
|
|
28
|
+
* 2. Sends public key to wallet over the MessagePort
|
|
29
|
+
* 3. Receives wallet's public key
|
|
30
|
+
* 4. Derives shared secret and computes verification hash locally
|
|
31
|
+
*
|
|
32
|
+
* **IMPORTANT**: Has a 2 second timeout for MITM defense.
|
|
33
|
+
* Both parties must exchange keys relatively quickly.
|
|
34
|
+
*
|
|
35
|
+
* The verification hash is computed independently by both parties
|
|
36
|
+
* and should be displayed to the user for visual comparison.
|
|
37
|
+
*
|
|
38
|
+
* @returns Connected wallet with shared key and verification hash
|
|
39
|
+
* @throws Error if key exchange fails or times out
|
|
40
|
+
*/
|
|
41
|
+
establishSecureChannel(): Promise<ConnectedWallet>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A fully connected wallet with secure channel established.
|
|
45
|
+
* Available after key exchange completes.
|
|
46
|
+
*/
|
|
47
|
+
export interface ConnectedWallet {
|
|
48
|
+
/** Full wallet info including public key and verification hash */
|
|
49
|
+
info: ConnectedWalletInfo;
|
|
50
|
+
/** The MessagePort for encrypted communication */
|
|
51
|
+
port: MessagePort;
|
|
52
|
+
/** The derived AES-256-GCM shared key for encryption */
|
|
53
|
+
sharedKey: CryptoKey;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Options for wallet discovery.
|
|
57
|
+
*/
|
|
58
|
+
export interface DiscoveryOptions {
|
|
59
|
+
/** Application ID making the request */
|
|
60
|
+
appId: string;
|
|
61
|
+
/** How long to wait for user approval (ms). Default: 60000 (60s) */
|
|
62
|
+
timeout?: number;
|
|
63
|
+
/**
|
|
64
|
+
* Callback invoked when a wallet is discovered.
|
|
65
|
+
* Wallets are streamed as users approve them.
|
|
66
|
+
*/
|
|
67
|
+
onWalletDiscovered?: (wallet: DiscoveredWallet) => void;
|
|
68
|
+
/**
|
|
69
|
+
* AbortSignal for cancelling discovery early.
|
|
70
|
+
* When aborted, cleanup happens immediately instead of waiting for timeout.
|
|
71
|
+
*/
|
|
72
|
+
signal?: AbortSignal;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Provider for discovering Aztec wallet extensions.
|
|
76
|
+
*
|
|
77
|
+
* NOTE: Most users should use WalletManager instead of this class directly.
|
|
78
|
+
* WalletManager provides a higher-level API with streaming support.
|
|
79
|
+
*
|
|
80
|
+
* The connection flow is split into two phases for security:
|
|
81
|
+
*
|
|
82
|
+
* 1. **Discovery Phase** ({@link discoverWallets}):
|
|
83
|
+
* - Broadcasts a discovery request (NO public keys)
|
|
84
|
+
* - Wallet shows pending request to user
|
|
85
|
+
* - User must approve before wallet reveals itself
|
|
86
|
+
* - Wallets are streamed via callback as they're approved
|
|
87
|
+
*
|
|
88
|
+
* 2. **Secure Channel Phase** ({@link DiscoveredWallet.establishSecureChannel}):
|
|
89
|
+
* - Performs ECDH key exchange over private MessageChannel
|
|
90
|
+
* - Both parties compute verification hash locally
|
|
91
|
+
* - Has a 2s timeout for MITM defense
|
|
92
|
+
* - Returns connected wallet with shared key and verification hash
|
|
93
|
+
*/
|
|
94
|
+
export declare class ExtensionProvider {
|
|
95
|
+
/**
|
|
96
|
+
* Discovers wallet extensions that user has approved.
|
|
97
|
+
*
|
|
98
|
+
* Wallets are streamed via the `onWalletDiscovered` callback as users approve them.
|
|
99
|
+
* The promise resolves when the timeout expires or signal is aborted.
|
|
100
|
+
*
|
|
101
|
+
* @param chainInfo - Chain information to check if extensions support this network
|
|
102
|
+
* @param options - Discovery options including appId, appName, timeout, and callback
|
|
103
|
+
* @returns Promise that resolves when discovery completes
|
|
104
|
+
*/
|
|
105
|
+
static discoverWallets(chainInfo: ChainInfo, options: Di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;;;;;;;OAiBG;IACG,sBAAsB,IAAI,OAAO,CAAC,eAAe,CAAC,CA+CvD;CACF;AAED;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,kEAAkE;IAClE,IAAI,EAAE,mBAAmB,CAAC;IAC1B,kDAAkD;IAClD,IAAI,EAAE,WAAW,CAAC;IAClB,wDAAwD;IACxD,SAAS,EAAE,SAAS,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,wCAAwC;IACxC,KAAK,EAAE,MAAM,CAAC;IACd,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,CAAC,MAAM,EAAE,gBAAgB,KAAK,IAAI,CAAC;IACxD;;;OAGG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,iBAAiB;IAC5B;;;;;;;;;OASG;IACH,MAAM,CAAC,eAAe,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CA8DrF;CACF"}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { jsonStringify } from '@aztec/foundation/json-rpc';
|
|
2
|
+
import { promiseWithResolvers } from '@aztec/foundation/promise';
|
|
3
|
+
import { deriveSessionKeys, exportPublicKey, generateKeyPair, importPublicKey } from '../../crypto.js';
|
|
4
|
+
import { WalletMessageType } from '../../types.js';
|
|
5
|
+
/** Default discovery timeout - long to give users time to approve */ const DEFAULT_DISCOVERY_TIMEOUT_MS = 60000; // 60 seconds
|
|
6
|
+
/** Key exchange timeout - short, wallet should respond quickly after discovery approval */ const KEY_EXCHANGE_TIMEOUT_MS = 2000; // 2 seconds
|
|
7
|
+
/**
|
|
8
|
+
* A discovered wallet before key exchange.
|
|
9
|
+
* Has basic info and MessagePort, but no shared key yet.
|
|
10
|
+
*
|
|
11
|
+
* Call {@link establishSecureChannel} to perform key exchange and get a connected wallet.
|
|
12
|
+
*/ export class DiscoveredWallet {
|
|
13
|
+
info;
|
|
14
|
+
port;
|
|
15
|
+
requestId;
|
|
16
|
+
constructor(/** Basic wallet information (id, name, icon, version) */ info, /** The MessagePort for private communication with the wallet */ port, /** Request ID for correlation */ requestId){
|
|
17
|
+
this.info = info;
|
|
18
|
+
this.port = port;
|
|
19
|
+
this.requestId = requestId;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Establishes a secure connection with this wallet.
|
|
23
|
+
*
|
|
24
|
+
* This method:
|
|
25
|
+
* 1. Generates an ECDH key pair
|
|
26
|
+
* 2. Sends public key to wallet over the MessagePort
|
|
27
|
+
* 3. Receives wallet's public key
|
|
28
|
+
* 4. Derives shared secret and computes verification hash locally
|
|
29
|
+
*
|
|
30
|
+
* **IMPORTANT**: Has a 2 second timeout for MITM defense.
|
|
31
|
+
* Both parties must exchange keys relatively quickly.
|
|
32
|
+
*
|
|
33
|
+
* The verification hash is computed independently by both parties
|
|
34
|
+
* and should be displayed to the user for visual comparison.
|
|
35
|
+
*
|
|
36
|
+
* @returns Connected wallet with shared key and verification hash
|
|
37
|
+
* @throws Error if key exchange fails or times out
|
|
38
|
+
*/ async establishSecureChannel() {
|
|
39
|
+
const keyPair = await generateKeyPair();
|
|
40
|
+
const exportedPublicKey = await exportPublicKey(keyPair.publicKey);
|
|
41
|
+
const { promise, resolve, reject } = promiseWithResolvers();
|
|
42
|
+
const timeoutId = setTimeout(()=>{
|
|
43
|
+
reject(new Error('Key exchange timeout'));
|
|
44
|
+
}, KEY_EXCHANGE_TIMEOUT_MS);
|
|
45
|
+
this.port.onmessage = async (event)=>{
|
|
46
|
+
const data = event.data;
|
|
47
|
+
if (data.type === WalletMessageType.KEY_EXCHANGE_RESPONSE && data.requestId === this.requestId) {
|
|
48
|
+
clearTimeout(timeoutId);
|
|
49
|
+
try {
|
|
50
|
+
const walletPublicKey = await importPublicKey(data.publicKey);
|
|
51
|
+
const session = await deriveSessionKeys(keyPair, walletPublicKey, true);
|
|
52
|
+
const connectedInfo = {
|
|
53
|
+
...this.info,
|
|
54
|
+
publicKey: data.publicKey,
|
|
55
|
+
verificationHash: session.verificationHash
|
|
56
|
+
};
|
|
57
|
+
resolve({
|
|
58
|
+
info: connectedInfo,
|
|
59
|
+
port: this.port,
|
|
60
|
+
sharedKey: session.encryptionKey
|
|
61
|
+
});
|
|
62
|
+
} catch (err) {
|
|
63
|
+
reject(new Error(`Key exchange failed: ${err}`));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
this.port.start();
|
|
68
|
+
const keyExchangeRequest = {
|
|
69
|
+
type: WalletMessageType.KEY_EXCHANGE_REQUEST,
|
|
70
|
+
requestId: this.requestId,
|
|
71
|
+
publicKey: exportedPublicKey
|
|
72
|
+
};
|
|
73
|
+
this.port.postMessage(keyExchangeRequest);
|
|
74
|
+
return promise;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Provider for discovering Aztec wallet extensions.
|
|
79
|
+
*
|
|
80
|
+
* NOTE: Most users should use WalletManager instead of this class directly.
|
|
81
|
+
* WalletManager provides a higher-level API with streaming support.
|
|
82
|
+
*
|
|
83
|
+
* The connection flow is split into two phases for security:
|
|
84
|
+
*
|
|
85
|
+
* 1. **Discovery Phase** ({@link discoverWallets}):
|
|
86
|
+
* - Broadcasts a discovery request (NO public keys)
|
|
87
|
+
* - Wallet shows pending request to user
|
|
88
|
+
* - User must approve before wallet reveals itself
|
|
89
|
+
* - Wallets are streamed via callback as they're approved
|
|
90
|
+
*
|
|
91
|
+
* 2. **Secure Channel Phase** ({@link DiscoveredWallet.establishSecureChannel}):
|
|
92
|
+
* - Performs ECDH key exchange over private MessageChannel
|
|
93
|
+
* - Both parties compute verification hash locally
|
|
94
|
+
* - Has a 2s timeout for MITM defense
|
|
95
|
+
* - Returns connected wallet with shared key and verification hash
|
|
96
|
+
*/ export class ExtensionProvider {
|
|
97
|
+
/**
|
|
98
|
+
* Discovers wallet extensions that user has approved.
|
|
99
|
+
*
|
|
100
|
+
* Wallets are streamed via the `onWalletDiscovered` callback as users approve them.
|
|
101
|
+
* The promise resolves when the timeout expires or signal is aborted.
|
|
102
|
+
*
|
|
103
|
+
* @param chainInfo - Chain information to check if extensions support this network
|
|
104
|
+
* @param options - Discovery options including appId, appName, timeout, and callback
|
|
105
|
+
* @returns Promise that resolves when discovery completes
|
|
106
|
+
*/ static discoverWallets(chainInfo, options) {
|
|
107
|
+
if (options.signal?.aborted) {
|
|
108
|
+
return Promise.resolve();
|
|
109
|
+
}
|
|
110
|
+
const timeout = options.timeout ?? DEFAULT_DISCOVERY_TIMEOUT_MS;
|
|
111
|
+
return new Promise((resolve)=>{
|
|
112
|
+
const requestId = globalThis.crypto.randomUUID();
|
|
113
|
+
let timeoutId = null;
|
|
114
|
+
let completed = false;
|
|
115
|
+
const finish = ()=>{
|
|
116
|
+
if (completed) {
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
completed = true;
|
|
120
|
+
if (timeoutId !== null) {
|
|
121
|
+
clearTimeout(timeoutId);
|
|
122
|
+
}
|
|
123
|
+
window.removeEventListener('message', onMessage);
|
|
124
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
125
|
+
resolve();
|
|
126
|
+
};
|
|
127
|
+
const onAbort = ()=>finish();
|
|
128
|
+
const onMessage = (event)=>{
|
|
129
|
+
if (completed || event.source !== window) {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
let data;
|
|
133
|
+
try {
|
|
134
|
+
data = JSON.parse(event.data);
|
|
135
|
+
} catch {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (data.type !== WalletMessageType.DISCOVERY_RESPONSE || data.requestId !== requestId) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const port = event.ports?.[0];
|
|
142
|
+
if (port) {
|
|
143
|
+
options.onWalletDiscovered?.(new DiscoveredWallet(data.walletInfo, port, requestId));
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
options.signal?.addEventListener('abort', onAbort, {
|
|
147
|
+
once: true
|
|
148
|
+
});
|
|
149
|
+
window.addEventListener('message', onMessage);
|
|
150
|
+
const discoveryMessage = {
|
|
151
|
+
type: WalletMessageType.DISCOVERY,
|
|
152
|
+
requestId,
|
|
153
|
+
appId: options.appId,
|
|
154
|
+
chainInfo
|
|
155
|
+
};
|
|
156
|
+
window.postMessage(jsonStringify(discoveryMessage), '*');
|
|
157
|
+
timeoutId = setTimeout(finish, timeout);
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { ChainInfo } from '@aztec/aztec.js/account';
|
|
2
|
+
import { type Wallet } from '@aztec/aztec.js/wallet';
|
|
3
|
+
/**
|
|
4
|
+
* Callback type for wallet disconnect events.
|
|
5
|
+
*/
|
|
6
|
+
export type DisconnectCallback = () => void;
|
|
7
|
+
/**
|
|
8
|
+
* A wallet implementation that communicates with browser extension wallets
|
|
9
|
+
* using an encrypted MessageChannel.
|
|
10
|
+
*
|
|
11
|
+
* This class uses a secure channel established after discovery:
|
|
12
|
+
*
|
|
13
|
+
* 1. **MessageChannel**: Created during discovery and transferred via window.postMessage.
|
|
14
|
+
* Note: The port transfer is visible to page scripts, but security comes from encryption.
|
|
15
|
+
*
|
|
16
|
+
* 2. **ECDH Key Exchange**: The shared secret was derived after discovery using
|
|
17
|
+
* Elliptic Curve Diffie-Hellman key exchange over the MessagePort.
|
|
18
|
+
*
|
|
19
|
+
* 3. **AES-GCM Encryption**: All messages are encrypted using AES-256-GCM,
|
|
20
|
+
* providing both confidentiality and authenticity. This is what secures the channel.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* // Discover and establish secure channel to a wallet
|
|
25
|
+
* const discoveredWallets = await ExtensionProvider.discoverWallets(chainInfo, { appId: 'my-dapp' });
|
|
26
|
+
* const connection = await discoveredWallets[0].establishSecureChannel();
|
|
27
|
+
*
|
|
28
|
+
* // User can verify emoji if desired
|
|
29
|
+
* console.log('Verify:', hashToEmoji(connection.info.verificationHash!));
|
|
30
|
+
*
|
|
31
|
+
* // Create wallet using the connection
|
|
32
|
+
* const wallet = ExtensionWallet.create(connection.info.id, connection.port, connection.sharedKey, chainInfo, 'my-dapp');
|
|
33
|
+
*
|
|
34
|
+
* // All subsequent calls are encrypted
|
|
35
|
+
* const accounts = await wallet.getAccounts();
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export declare class ExtensionWallet {
|
|
39
|
+
private chainInfo;
|
|
40
|
+
private appId;
|
|
41
|
+
private extensionId;
|
|
42
|
+
private port;
|
|
43
|
+
private sharedKey;
|
|
44
|
+
/** Map of pending requests awaiting responses, keyed by message ID */
|
|
45
|
+
private inFlight;
|
|
46
|
+
private disconnected;
|
|
47
|
+
private disconnectCallbacks;
|
|
48
|
+
/**
|
|
49
|
+
* Private constructor - use {@link ExtensionWallet.create} to instantiate.
|
|
50
|
+
* @param chainInfo - The chain information (chainId and version)
|
|
51
|
+
* @param appId - Application identifier for the requesting dApp
|
|
52
|
+
* @param extensionId - The unique identifier of the target wallet extension
|
|
53
|
+
* @param port - The MessagePort for private communication with the wallet
|
|
54
|
+
* @param sharedKey - The derived AES-256-GCM shared key for encryption
|
|
55
|
+
*/
|
|
56
|
+
private constructor();
|
|
57
|
+
/**
|
|
58
|
+
* Creates a Wallet that communicates with a browser extension
|
|
59
|
+
* over a secure encrypted MessageChannel.
|
|
60
|
+
*
|
|
61
|
+
* @param extensionId - The unique identifier of the wallet extension
|
|
62
|
+
* @param port - The MessagePort for encrypted communication with the wallet
|
|
63
|
+
* @param sharedKey - The derived AES-256-GCM shared key for encryption
|
|
64
|
+
* @param chainInfo - The chain information (chainId and version) for request context
|
|
65
|
+
* @param appId - Application identifier used to identify the requesting dApp to the wallet
|
|
66
|
+
* @returns A Wallet interface where all method calls are encrypted
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```typescript
|
|
70
|
+
* const discoveredWallets = await ExtensionProvider.discoverWallets(chainInfo, { appId: 'my-defi-app' });
|
|
71
|
+
* const connection = await discoveredWallets[0].establishSecureChannel();
|
|
72
|
+
* const wallet = ExtensionWallet.create(
|
|
73
|
+
* connection.info.id,
|
|
74
|
+
* connection.port,
|
|
75
|
+
* connection.sharedKey,
|
|
76
|
+
* chainInfo,
|
|
77
|
+
* 'my-defi-app'
|
|
78
|
+
* );
|
|
79
|
+
*
|
|
80
|
+
* const accounts = await wallet.getAccounts();
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
static create(extensionId: string, port: MessagePort, sharedKey: CryptoKey, chainInfo: ChainInfo, appId: string): Wallet;
|
|
84
|
+
private handleEncryptedResponse;
|
|
85
|
+
private postMessage;
|
|
86
|
+
/**
|
|
87
|
+
* Handles wallet disconnection.
|
|
88
|
+
* Rejects all pending requests and notifies registered callbacks.
|
|
89
|
+
* @internal
|
|
90
|
+
*/
|
|
91
|
+
private handleDisconnect;
|
|
92
|
+
/**
|
|
93
|
+
* Registers a callback to be invoked when the wallet disconnects.
|
|
94
|
+
*
|
|
95
|
+
* @param callback - Function to call when wallet disconnects
|
|
96
|
+
* @returns A function to unregister the callback
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* ```typescript
|
|
100
|
+
* const wallet = await ExtensionWallet.create(...);
|
|
101
|
+
* const unsubscribe = wallet.onDisconnect(() => {
|
|
102
|
+
* console.log('Wallet disconnected! Please reconnect.');
|
|
103
|
+
* // Clean up UI, prompt user to reconnect, etc.
|
|
104
|
+
* });
|
|
105
|
+
* // Later: unsubscribe(); to stop receiving notifications
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
onDisconnect(callback: DisconnectCallback): () => void;
|
|
109
|
+
/**
|
|
110
|
+
* Returns whether the wallet has been disconnected.
|
|
111
|
+
*
|
|
112
|
+
* @returns true if the wallet is no longer connected
|
|
113
|
+
*/
|
|
114
|
+
isDisconnected(): boolean;
|
|
115
|
+
/**
|
|
116
|
+
* Disconnects from the wallet and cleans up resources.
|
|
117
|
+
*
|
|
118
|
+
* This method notifies the wallet extension that the session is ending,
|
|
119
|
+
* allowing it to clean up its state. After calling this method, the wallet
|
|
120
|
+
* instance can no longer be used and any pending requests will be rejected.
|
|
121
|
+
*
|
|
122
|
+
* @example
|
|
123
|
+
* ```typescript
|
|
124
|
+
* const extensionWallet = ExtensionWallet.create(extensionId, port, sharedKey, chainInfo, 'my-app');
|
|
125
|
+
* // ... use wallet ...
|
|
126
|
+
* await extensionWallet.disconnect(); // Clean disconnect when done
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
disconnect(): Promise<void>;
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5zaW9uX3dhbGxldC5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2V4dGVuc2lvbi9wcm92aWRlci9leHRlbnNpb25fd2FsbGV0LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sS0FBSyxFQUFFLFNBQVMsRUFBRSxNQUFNLHlCQUF5QixDQUFDO0FBQ3pELE9BQU8sRUFBRSxLQUFLLE1BQU0sRUFBZ0IsTUFBTSx3QkFBd0IsQ0FBQztBQW9CbkU7O0dBRUc7QUFDSCxNQUFNLE1BQU0sa0JBQWtCLEdBQUcsTUFBTSxJQUFJLENBQUM7QUFFNUM7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztHQThCRztBQUNILHFCQUFhLGVBQWU7SUFleEIsT0FBTyxDQUFDLFNBQVM7SUFDakIsT0FBTyxDQUFDLEtBQUs7SUFDYixPQUFPLENBQUMsV0FBVztJQUNuQixPQUFPL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AAI,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBAAa,eAAe;IAexB,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,KAAK;IACb,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,IAAI;IACZ,OAAO,CAAC,SAAS;IAlBnB,sEAAsE;IACtE,OAAO,CAAC,QAAQ,CAAoD;IACpE,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,mBAAmB,CAA4B;IAEvD;;;;;;;OAOG;IACH,OAAO,eAMH;IAEJ;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACH,MAAM,CAAC,MAAM,CACX,WAAW,EAAE,MAAM,EACnB,IAAI,EAAE,WAAW,EACjB,SAAS,EAAE,SAAS,EACpB,SAAS,EAAE,SAAS,EACpB,KAAK,EAAE,MAAM,GACZ,MAAM,CAgCR;YAUa,uBAAuB;YA8CvB,WAAW;IA0BzB;;;;OAIG;IACH,OAAO,CAAC,gBAAgB;IA0BxB;;;;;;;;;;;;;;;OAeG;IACH,YAAY,CAAC,QAAQ,EAAE,kBAAkB,GAAG,MAAM,IAAI,CAQrD;IAED;;;;OAIG;IACH,cAAc,IAAI,OAAO,CAExB;IAED;;;;;;;;;;;;;OAaG;IAEG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAahC;CACF"}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { WalletSchema } from '@aztec/aztec.js/wallet';
|
|
2
|
+
import { jsonStringify } from '@aztec/foundation/json-rpc';
|
|
3
|
+
import { promiseWithResolvers } from '@aztec/foundation/promise';
|
|
4
|
+
import { schemaHasMethod } from '@aztec/foundation/schemas';
|
|
5
|
+
import { decrypt, encrypt } from '../../crypto.js';
|
|
6
|
+
import { WalletMessageType } from '../../types.js';
|
|
7
|
+
/**
|
|
8
|
+
* A wallet implementation that communicates with browser extension wallets
|
|
9
|
+
* using an encrypted MessageChannel.
|
|
10
|
+
*
|
|
11
|
+
* This class uses a secure channel established after discovery:
|
|
12
|
+
*
|
|
13
|
+
* 1. **MessageChannel**: Created during discovery and transferred via window.postMessage.
|
|
14
|
+
* Note: The port transfer is visible to page scripts, but security comes from encryption.
|
|
15
|
+
*
|
|
16
|
+
* 2. **ECDH Key Exchange**: The shared secret was derived after discovery using
|
|
17
|
+
* Elliptic Curve Diffie-Hellman key exchange over the MessagePort.
|
|
18
|
+
*
|
|
19
|
+
* 3. **AES-GCM Encryption**: All messages are encrypted using AES-256-GCM,
|
|
20
|
+
* providing both confidentiality and authenticity. This is what secures the channel.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* // Discover and establish secure channel to a wallet
|
|
25
|
+
* const discoveredWallets = await ExtensionProvider.discoverWallets(chainInfo, { appId: 'my-dapp' });
|
|
26
|
+
* const connection = await discoveredWallets[0].establishSecureChannel();
|
|
27
|
+
*
|
|
28
|
+
* // User can verify emoji if desired
|
|
29
|
+
* console.log('Verify:', hashToEmoji(connection.info.verificationHash!));
|
|
30
|
+
*
|
|
31
|
+
* // Create wallet using the connection
|
|
32
|
+
* const wallet = ExtensionWallet.create(connection.info.id, connection.port, connection.sharedKey, chainInfo, 'my-dapp');
|
|
33
|
+
*
|
|
34
|
+
* // All subsequent calls are encrypted
|
|
35
|
+
* const accounts = await wallet.getAccounts();
|
|
36
|
+
* ```
|
|
37
|
+
*/ export class ExtensionWallet {
|
|
38
|
+
chainInfo;
|
|
39
|
+
appId;
|
|
40
|
+
extensionId;
|
|
41
|
+
port;
|
|
42
|
+
sharedKey;
|
|
43
|
+
/** Map of pending requests awaiting responses, keyed by message ID */ inFlight;
|
|
44
|
+
disconnected;
|
|
45
|
+
disconnectCallbacks;
|
|
46
|
+
/**
|
|
47
|
+
* Private constructor - use {@link ExtensionWallet.create} to instantiate.
|
|
48
|
+
* @param chainInfo - The chain information (chainId and version)
|
|
49
|
+
* @param appId - Application identifier for the requesting dApp
|
|
50
|
+
* @param extensionId - The unique identifier of the target wallet extension
|
|
51
|
+
* @param port - The MessagePort for private communication with the wallet
|
|
52
|
+
* @param sharedKey - The derived AES-256-GCM shared key for encryption
|
|
53
|
+
*/ constructor(chainInfo, appId, extensionId, port, sharedKey){
|
|
54
|
+
this.chainInfo = chainInfo;
|
|
55
|
+
this.appId = appId;
|
|
56
|
+
this.extensionId = extensionId;
|
|
57
|
+
this.port = port;
|
|
58
|
+
this.sharedKey = sharedKey;
|
|
59
|
+
this.inFlight = new Map();
|
|
60
|
+
this.disconnected = false;
|
|
61
|
+
this.disconnectCallbacks = [];
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Creates a Wallet that communicates with a browser extension
|
|
65
|
+
* over a secure encrypted MessageChannel.
|
|
66
|
+
*
|
|
67
|
+
* @param extensionId - The unique identifier of the wallet extension
|
|
68
|
+
* @param port - The MessagePort for encrypted communication with the wallet
|
|
69
|
+
* @param sharedKey - The derived AES-256-GCM shared key for encryption
|
|
70
|
+
* @param chainInfo - The chain information (chainId and version) for request context
|
|
71
|
+
* @param appId - Application identifier used to identify the requesting dApp to the wallet
|
|
72
|
+
* @returns A Wallet interface where all method calls are encrypted
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* ```typescript
|
|
76
|
+
* const discoveredWallets = await ExtensionProvider.discoverWallets(chainInfo, { appId: 'my-defi-app' });
|
|
77
|
+
* const connection = await discoveredWallets[0].establishSecureChannel();
|
|
78
|
+
* const wallet = ExtensionWallet.create(
|
|
79
|
+
* connection.info.id,
|
|
80
|
+
* connection.port,
|
|
81
|
+
* connection.sharedKey,
|
|
82
|
+
* chainInfo,
|
|
83
|
+
* 'my-defi-app'
|
|
84
|
+
* );
|
|
85
|
+
*
|
|
86
|
+
* const accounts = await wallet.getAccounts();
|
|
87
|
+
* ```
|
|
88
|
+
*/ static create(extensionId, port, sharedKey, chainInfo, appId) {
|
|
89
|
+
const wallet = new ExtensionWallet(chainInfo, appId, extensionId, port, sharedKey);
|
|
90
|
+
// Set up message handler for encrypted responses and unencrypted control messages
|
|
91
|
+
wallet.port.onmessage = (event)=>{
|
|
92
|
+
const data = event.data;
|
|
93
|
+
// Check for unencrypted disconnect notification
|
|
94
|
+
if (data && typeof data === 'object' && 'type' in data && data.type === WalletMessageType.DISCONNECT) {
|
|
95
|
+
wallet.handleDisconnect();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
// Otherwise treat as encrypted payload
|
|
99
|
+
void wallet.handleEncryptedResponse(data);
|
|
100
|
+
};
|
|
101
|
+
wallet.port.start();
|
|
102
|
+
return new Proxy(wallet, {
|
|
103
|
+
get: (target, prop)=>{
|
|
104
|
+
if (schemaHasMethod(WalletSchema, prop.toString())) {
|
|
105
|
+
return async (...args)=>{
|
|
106
|
+
const result = await target.postMessage({
|
|
107
|
+
type: prop.toString(),
|
|
108
|
+
args
|
|
109
|
+
});
|
|
110
|
+
return WalletSchema[prop.toString()].returnType().parseAsync(result);
|
|
111
|
+
};
|
|
112
|
+
} else {
|
|
113
|
+
return target[prop];
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Handles an encrypted response received from the wallet extension.
|
|
120
|
+
*
|
|
121
|
+
* Decrypts the response using the shared AES key and resolves or rejects
|
|
122
|
+
* the corresponding pending promise based on the response content.
|
|
123
|
+
*
|
|
124
|
+
* @param encrypted - The encrypted response from the wallet
|
|
125
|
+
*/ async handleEncryptedResponse(encrypted) {
|
|
126
|
+
if (!this.sharedKey) {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
const response = await decrypt(this.sharedKey, encrypted);
|
|
131
|
+
const { messageId, result, error, walletId: responseWalletId } = response;
|
|
132
|
+
if (!messageId || !responseWalletId) {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (this.extensionId !== responseWalletId) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (!this.inFlight.has(messageId)) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const { resolve, reject } = this.inFlight.get(messageId);
|
|
142
|
+
if (error) {
|
|
143
|
+
reject(new Error(jsonStringify(error)));
|
|
144
|
+
} else {
|
|
145
|
+
resolve(result);
|
|
146
|
+
}
|
|
147
|
+
this.inFlight.delete(messageId);
|
|
148
|
+
// eslint-disable-next-line no-empty
|
|
149
|
+
} catch {}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Sends an encrypted wallet method call over the secure MessageChannel.
|
|
153
|
+
*
|
|
154
|
+
* The message is encrypted using AES-256-GCM with the shared key derived
|
|
155
|
+
* during discovery. A unique message ID is generated to correlate
|
|
156
|
+
* the response.
|
|
157
|
+
*
|
|
158
|
+
* @param call - The wallet method call containing method name and arguments
|
|
159
|
+
* @returns A Promise that resolves with the decrypted result from the wallet
|
|
160
|
+
*
|
|
161
|
+
* @throws Error if the secure channel has not been established or wallet is disconnected
|
|
162
|
+
*/ async postMessage(call) {
|
|
163
|
+
if (this.disconnected) {
|
|
164
|
+
throw new Error('Wallet has been disconnected');
|
|
165
|
+
}
|
|
166
|
+
if (!this.port || !this.sharedKey) {
|
|
167
|
+
throw new Error('Secure channel not established');
|
|
168
|
+
}
|
|
169
|
+
const messageId = globalThis.crypto.randomUUID();
|
|
170
|
+
const message = {
|
|
171
|
+
type: call.type,
|
|
172
|
+
args: call.args,
|
|
173
|
+
messageId,
|
|
174
|
+
chainInfo: this.chainInfo,
|
|
175
|
+
appId: this.appId,
|
|
176
|
+
walletId: this.extensionId
|
|
177
|
+
};
|
|
178
|
+
const encrypted = await encrypt(this.sharedKey, jsonStringify(message));
|
|
179
|
+
this.port.postMessage(encrypted);
|
|
180
|
+
const { promise, resolve, reject } = promiseWithResolvers();
|
|
181
|
+
this.inFlight.set(messageId, {
|
|
182
|
+
promise,
|
|
183
|
+
resolve,
|
|
184
|
+
reject
|
|
185
|
+
});
|
|
186
|
+
return promise;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Handles wallet disconnection.
|
|
190
|
+
* Rejects all pending requests and notifies registered callbacks.
|
|
191
|
+
* @internal
|
|
192
|
+
*/ handleDisconnect() {
|
|
193
|
+
if (this.disconnected) {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
this.disconnected = true;
|
|
197
|
+
if (this.port) {
|
|
198
|
+
this.port.onmessage = null;
|
|
199
|
+
this.port.close();
|
|
200
|
+
}
|
|
201
|
+
const error = new Error('Wallet disconnected');
|
|
202
|
+
for (const { reject } of this.inFlight.values()){
|
|
203
|
+
reject(error);
|
|
204
|
+
}
|
|
205
|
+
this.inFlight.clear();
|
|
206
|
+
for (const callback of this.disconnectCallbacks){
|
|
207
|
+
try {
|
|
208
|
+
callback();
|
|
209
|
+
} catch {
|
|
210
|
+
// Ignore errors on disconnect callbacks
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Registers a callback to be invoked when the wallet disconnects.
|
|
216
|
+
*
|
|
217
|
+
* @param callback - Function to call when wallet disconnects
|
|
218
|
+
* @returns A function to unregister the callback
|
|
219
|
+
*
|
|
220
|
+
* @example
|
|
221
|
+
* ```typescript
|
|
222
|
+
* const wallet = await ExtensionWallet.create(...);
|
|
223
|
+
* const unsubscribe = wallet.onDisconnect(() => {
|
|
224
|
+
* console.log('Wallet disconnected! Please reconnect.');
|
|
225
|
+
* // Clean up UI, prompt user to reconnect, etc.
|
|
226
|
+
* });
|
|
227
|
+
* // Later: unsubscribe(); to stop receiving notifications
|
|
228
|
+
* ```
|
|
229
|
+
*/ onDisconnect(callback) {
|
|
230
|
+
this.disconnectCallbacks.push(callback);
|
|
231
|
+
return ()=>{
|
|
232
|
+
const index = this.disconnectCallbacks.indexOf(callback);
|
|
233
|
+
if (index !== -1) {
|
|
234
|
+
this.disconnectCallbacks.splice(index, 1);
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Returns whether the wallet has been disconnected.
|
|
240
|
+
*
|
|
241
|
+
* @returns true if the wallet is no longer connected
|
|
242
|
+
*/ isDisconnected() {
|
|
243
|
+
return this.disconnected;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Disconnects from the wallet and cleans up resources.
|
|
247
|
+
*
|
|
248
|
+
* This method notifies the wallet extension that the session is ending,
|
|
249
|
+
* allowing it to clean up its state. After calling this method, the wallet
|
|
250
|
+
* instance can no longer be used and any pending requests will be rejected.
|
|
251
|
+
*
|
|
252
|
+
* @example
|
|
253
|
+
* ```typescript
|
|
254
|
+
* const extensionWallet = ExtensionWallet.create(extensionId, port, sharedKey, chainInfo, 'my-app');
|
|
255
|
+
* // ... use wallet ...
|
|
256
|
+
* await extensionWallet.disconnect(); // Clean disconnect when done
|
|
257
|
+
* ```
|
|
258
|
+
*/ // eslint-disable-next-line require-await -- async for interface compatibility
|
|
259
|
+
async disconnect() {
|
|
260
|
+
if (this.disconnected) {
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (this.port) {
|
|
264
|
+
// Send unencrypted disconnect - control messages don't need encryption
|
|
265
|
+
this.port.postMessage({
|
|
266
|
+
type: WalletMessageType.DISCONNECT
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
this.handleDisconnect();
|
|
270
|
+
}
|
|
271
|
+
}
|