@aztec/wallet-sdk 0.0.1-commit.f295ac2 → 0.0.1-commit.fc805bf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +217 -294
  2. package/dest/base-wallet/base_wallet.d.ts +20 -7
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +29 -11
  5. package/dest/crypto.d.ts +59 -50
  6. package/dest/crypto.d.ts.map +1 -1
  7. package/dest/crypto.js +202 -108
  8. package/dest/emoji_alphabet.d.ts +35 -0
  9. package/dest/emoji_alphabet.d.ts.map +1 -0
  10. package/dest/emoji_alphabet.js +299 -0
  11. package/dest/extension/handlers/background_connection_handler.d.ts +158 -0
  12. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
  13. package/dest/extension/handlers/background_connection_handler.js +258 -0
  14. package/dest/extension/handlers/content_script_connection_handler.d.ts +56 -0
  15. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
  16. package/dest/extension/handlers/content_script_connection_handler.js +174 -0
  17. package/dest/extension/handlers/index.d.ts +12 -0
  18. package/dest/extension/handlers/index.d.ts.map +1 -0
  19. package/dest/extension/handlers/index.js +10 -0
  20. package/dest/extension/handlers/internal_message_types.d.ts +63 -0
  21. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
  22. package/dest/extension/handlers/internal_message_types.js +22 -0
  23. package/dest/extension/provider/extension_provider.d.ts +107 -0
  24. package/dest/extension/provider/extension_provider.d.ts.map +1 -0
  25. package/dest/extension/provider/extension_provider.js +160 -0
  26. package/dest/extension/provider/extension_wallet.d.ts +131 -0
  27. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  28. package/dest/{providers/extension → extension/provider}/extension_wallet.js +48 -95
  29. package/dest/extension/provider/index.d.ts +3 -0
  30. package/dest/extension/provider/index.d.ts.map +1 -0
  31. package/dest/{providers/extension → extension/provider}/index.js +0 -2
  32. package/dest/manager/index.d.ts +2 -8
  33. package/dest/manager/index.d.ts.map +1 -1
  34. package/dest/manager/index.js +0 -6
  35. package/dest/manager/types.d.ts +88 -6
  36. package/dest/manager/types.d.ts.map +1 -1
  37. package/dest/manager/types.js +17 -1
  38. package/dest/manager/wallet_manager.d.ts +50 -7
  39. package/dest/manager/wallet_manager.d.ts.map +1 -1
  40. package/dest/manager/wallet_manager.js +174 -44
  41. package/dest/types.d.ts +43 -12
  42. package/dest/types.d.ts.map +1 -1
  43. package/dest/types.js +3 -2
  44. package/package.json +10 -9
  45. package/src/base-wallet/base_wallet.ts +45 -20
  46. package/src/crypto.ts +237 -113
  47. package/src/emoji_alphabet.ts +317 -0
  48. package/src/extension/handlers/background_connection_handler.ts +423 -0
  49. package/src/extension/handlers/content_script_connection_handler.ts +246 -0
  50. package/src/extension/handlers/index.ts +25 -0
  51. package/src/extension/handlers/internal_message_types.ts +69 -0
  52. package/src/extension/provider/extension_provider.ts +233 -0
  53. package/src/{providers/extension → extension/provider}/extension_wallet.ts +52 -110
  54. package/src/extension/provider/index.ts +7 -0
  55. package/src/manager/index.ts +2 -10
  56. package/src/manager/types.ts +91 -5
  57. package/src/manager/wallet_manager.ts +192 -46
  58. package/src/types.ts +44 -10
  59. package/dest/providers/extension/extension_provider.d.ts +0 -63
  60. package/dest/providers/extension/extension_provider.d.ts.map +0 -1
  61. package/dest/providers/extension/extension_provider.js +0 -124
  62. package/dest/providers/extension/extension_wallet.d.ts +0 -155
  63. package/dest/providers/extension/extension_wallet.d.ts.map +0 -1
  64. package/dest/providers/extension/index.d.ts +0 -6
  65. package/dest/providers/extension/index.d.ts.map +0 -1
  66. package/src/providers/extension/extension_provider.ts +0 -167
  67. package/src/providers/extension/index.ts +0 -5
@@ -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: DiscoveryOptions): Promise<void>;
106
+ }
107
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5zaW9uX3Byb3ZpZGVyLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvZXh0ZW5zaW9uL3Byb3ZpZGVyL2V4dGVuc2lvbl9wcm92aWRlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxTQUFTLEVBQUUsTUFBTSx5QkFBeUIsQ0FBQztBQ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LENBQUM7Q0FDdEI7QUFFRDs7Ozs7Ozs7Ozs7Ozs7Ozs7OztHQW1CRztBQUNILHFCQUFhLGlCQUFpQjtJQUM1Qjs7Ozs7Ozs7O09BU0c7SUFDSCxNQUFNLENBQUMsZUFBZSxDQUFDLFNBQVMsRUFBRSxTQUFTLEVBQUUsT0FBTyxFQUFFLGdCQUFnQixHQUFHLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0E4RHJGO0NBQ0YifQ==
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension_provider.d.ts","sourceRoot":"","sources":["../../../src/extension/provider/extension_provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAKzD,OAAO,EACL,KAAK,mBAAmB,EAKxB,KAAK,UAAU,EAEhB,MAAM,gBAAgB,CAAC;AAQxB;;;;;GAKG;AACH,qBAAa,gBAAgB;IAEzB,yDAAyD;aACzC,IAAI,EAAE,UAAU;IAChC,gEAAgE;aAChD,IAAI,EAAE,WAAW;IACjC,iCAAiC;aACjB,SAAS,EAAE,MAAM;IANnC;IACE,yDAAyD;IACzC,IAAI,EAAE,UAAU;IAChC,gEAAgE;IAChD,IAAI,EAAE,WAAW;IACjC,iCAAiC;IACjB,SAAS,EAAE,MAAM,EAC/B;IAEJ;;;;;;;;;;;;;;;;;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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5zaW9uX3dhbGxldC5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2V4dGVuc2lvbi9wcm92aWRlci9leHRlbnNpb25fd2FsbGV0LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sS0FBSyxFQUFFLFNBQVMsRUFBRSxNQUFNLHlCQUF5QixDQUFDO0FBQ3pELE9BQU8sRUFBRSxLQUFLLE1BQU0sRUFBZ0IsTUFBTSx3QkFBd0IsQ0FBQztBQW9CbkU7O0dBRUc7QUFDSCxNQUFNLE1BQU0sa0JBQWtCLEdBQUcsTUFBTSxJQUFJLENBQUM7QUFFNUM7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztHQThCRztBQUNILHFCQUFhLGVBQWU7SUFleEIsT0FBTyxDQUFDLFNBQVM7SUFDakIsT0FBTyxDQUFDLEtBQUs7SUFDYixPQUFPLENBQUMsV0FBVztJQUNuQixPQUFPLENBQUMsSUFBSTtJQUNaLE9BQU8sQ0FBQyxTQUFTO0lBbEJuQixzRUFB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AexB,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"}
@@ -6,30 +6,30 @@ import { decrypt, encrypt } from '../../crypto.js';
6
6
  import { WalletMessageType } from '../../types.js';
7
7
  /**
8
8
  * A wallet implementation that communicates with browser extension wallets
9
- * using a secure encrypted MessageChannel.
9
+ * using an encrypted MessageChannel.
10
10
  *
11
- * This class uses a pre-established secure channel from the discovery phase:
11
+ * This class uses a secure channel established after discovery:
12
12
  *
13
- * 1. **MessageChannel**: A private communication channel created during discovery,
14
- * not visible to other scripts on the page (unlike window.postMessage).
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
15
  *
16
- * 2. **ECDH Key Exchange**: The shared secret was derived during discovery using
17
- * Elliptic Curve Diffie-Hellman key exchange.
16
+ * 2. **ECDH Key Exchange**: The shared secret was derived after discovery using
17
+ * Elliptic Curve Diffie-Hellman key exchange over the MessagePort.
18
18
  *
19
19
  * 3. **AES-GCM Encryption**: All messages are encrypted using AES-256-GCM,
20
- * providing both confidentiality and authenticity.
20
+ * providing both confidentiality and authenticity. This is what secures the channel.
21
21
  *
22
22
  * @example
23
23
  * ```typescript
24
- * // Discovery returns wallets with secure channel components
25
- * const wallets = await ExtensionProvider.discoverExtensions(chainInfo);
26
- * const { info, port, sharedKey } = wallets[0];
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
27
  *
28
28
  * // User can verify emoji if desired
29
- * console.log('Verify:', hashToEmoji(info.verificationHash!));
29
+ * console.log('Verify:', hashToEmoji(connection.info.verificationHash!));
30
30
  *
31
- * // Create wallet using the discovered components
32
- * const wallet = await ExtensionWallet.create(info, chainInfo, port, sharedKey, 'my-dapp');
31
+ * // Create wallet using the connection
32
+ * const wallet = ExtensionWallet.create(connection.info.id, connection.port, connection.sharedKey, chainInfo, 'my-dapp');
33
33
  *
34
34
  * // All subsequent calls are encrypted
35
35
  * const accounts = await wallet.getAccounts();
@@ -59,68 +59,47 @@ import { WalletMessageType } from '../../types.js';
59
59
  this.inFlight = new Map();
60
60
  this.disconnected = false;
61
61
  this.disconnectCallbacks = [];
62
- this.walletProxy = null;
63
62
  }
64
- /** Cached Wallet proxy instance */ walletProxy;
65
63
  /**
66
- * Creates an ExtensionWallet instance that communicates with a browser extension
64
+ * Creates a Wallet that communicates with a browser extension
67
65
  * over a secure encrypted MessageChannel.
68
66
  *
69
- * @param walletInfo - The wallet info from ExtensionProvider.discoverExtensions()
70
- * @param chainInfo - The chain information (chainId and version) for request context
71
- * @param port - The MessagePort for private communication with the wallet
67
+ * @param extensionId - The unique identifier of the wallet extension
68
+ * @param port - The MessagePort for encrypted communication with the wallet
72
69
  * @param sharedKey - The derived AES-256-GCM shared key for encryption
70
+ * @param chainInfo - The chain information (chainId and version) for request context
73
71
  * @param appId - Application identifier used to identify the requesting dApp to the wallet
74
- * @returns The ExtensionWallet instance. Use {@link getWallet} to get the Wallet interface.
72
+ * @returns A Wallet interface where all method calls are encrypted
75
73
  *
76
74
  * @example
77
75
  * ```typescript
78
- * const wallets = await ExtensionProvider.discoverExtensions(chainInfo);
79
- * const { info, port, sharedKey } = wallets[0];
80
- * const extensionWallet = ExtensionWallet.create(
81
- * info,
82
- * { chainId: Fr(31337), version: Fr(0) },
83
- * port,
84
- * sharedKey,
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,
85
83
  * 'my-defi-app'
86
84
  * );
87
85
  *
88
- * // Register disconnect handler
89
- * extensionWallet.onDisconnect(() => console.log('Disconnected!'));
90
- *
91
- * // Get the Wallet interface for dApp usage
92
- * const wallet = extensionWallet.getWallet();
93
86
  * const accounts = await wallet.getAccounts();
94
87
  * ```
95
- */ static create(walletInfo, chainInfo, port, sharedKey, appId) {
96
- const wallet = new ExtensionWallet(chainInfo, appId, walletInfo.id, port, sharedKey);
97
- // Set up message handler - all messages are now encrypted
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
98
91
  wallet.port.onmessage = (event)=>{
99
- void wallet.handleEncryptedResponse(event.data);
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
100
  };
101
101
  wallet.port.start();
102
- return wallet;
103
- }
104
- /**
105
- * Returns a Wallet interface that proxies all method calls through the secure channel.
106
- *
107
- * The returned Wallet can be used directly by dApps - all method calls are automatically
108
- * encrypted and sent to the wallet extension.
109
- *
110
- * @returns A Wallet implementation that encrypts all communication
111
- *
112
- * @example
113
- * ```typescript
114
- * const extensionWallet = ExtensionWallet.create(info, chainInfo, port, sharedKey, 'my-app');
115
- * const wallet = extensionWallet.getWallet();
116
- * const accounts = await wallet.getAccounts();
117
- * ```
118
- */ getWallet() {
119
- if (this.walletProxy) {
120
- return this.walletProxy;
121
- }
122
- // Create a Proxy that intercepts wallet method calls and forwards them to the extension
123
- this.walletProxy = new Proxy(this, {
102
+ return new Proxy(wallet, {
124
103
  get: (target, prop)=>{
125
104
  if (schemaHasMethod(WalletSchema, prop.toString())) {
126
105
  return async (...args)=>{
@@ -135,7 +114,6 @@ import { WalletMessageType } from '../../types.js';
135
114
  }
136
115
  }
137
116
  });
138
- return this.walletProxy;
139
117
  }
140
118
  /**
141
119
  * Handles an encrypted response received from the wallet extension.
@@ -151,12 +129,6 @@ import { WalletMessageType } from '../../types.js';
151
129
  try {
152
130
  const response = await decrypt(this.sharedKey, encrypted);
153
131
  const { messageId, result, error, walletId: responseWalletId } = response;
154
- // Check for disconnect notification from the wallet backend
155
- // This is sent as an encrypted error response with a special type
156
- if (error && typeof error === 'object' && 'type' in error && error.type === WalletMessageType.SESSION_DISCONNECTED) {
157
- this.handleDisconnect();
158
- return;
159
- }
160
132
  if (!messageId || !responseWalletId) {
161
133
  return;
162
134
  }
@@ -203,8 +175,7 @@ import { WalletMessageType } from '../../types.js';
203
175
  appId: this.appId,
204
176
  walletId: this.extensionId
205
177
  };
206
- // Encrypt the message and send over the private MessageChannel
207
- const encrypted = await encrypt(this.sharedKey, message);
178
+ const encrypted = await encrypt(this.sharedKey, jsonStringify(message));
208
179
  this.port.postMessage(encrypted);
209
180
  const { promise, resolve, reject } = promiseWithResolvers();
210
181
  this.inFlight.set(messageId, {
@@ -223,25 +194,20 @@ import { WalletMessageType } from '../../types.js';
223
194
  return;
224
195
  }
225
196
  this.disconnected = true;
226
- // Close the port to prevent any further messages
227
197
  if (this.port) {
228
198
  this.port.onmessage = null;
229
199
  this.port.close();
230
200
  }
231
- // Reject all pending requests
232
- // Note: These rejections should be caught by the callers, but we log them
233
- // here to help with debugging if they become unhandled
234
201
  const error = new Error('Wallet disconnected');
235
202
  for (const { reject } of this.inFlight.values()){
236
203
  reject(error);
237
204
  }
238
205
  this.inFlight.clear();
239
- // Notify registered callbacks
240
206
  for (const callback of this.disconnectCallbacks){
241
207
  try {
242
208
  callback();
243
209
  } catch {
244
- // Ignore errors in callbacks
210
+ // Ignore errors on disconnect callbacks
245
211
  }
246
212
  }
247
213
  }
@@ -285,34 +251,21 @@ import { WalletMessageType } from '../../types.js';
285
251
  *
286
252
  * @example
287
253
  * ```typescript
288
- * const wallet = await provider.connect('my-app');
254
+ * const extensionWallet = ExtensionWallet.create(extensionId, port, sharedKey, chainInfo, 'my-app');
289
255
  * // ... use wallet ...
290
- * await wallet.disconnect(); // Clean disconnect when done
256
+ * await extensionWallet.disconnect(); // Clean disconnect when done
291
257
  * ```
292
- */ async disconnect() {
258
+ */ // eslint-disable-next-line require-await -- async for interface compatibility
259
+ async disconnect() {
293
260
  if (this.disconnected) {
294
261
  return;
295
262
  }
296
- // Send disconnect message to extension before closing
297
- if (this.port && this.sharedKey) {
298
- try {
299
- const message = {
300
- type: WalletMessageType.DISCONNECT,
301
- messageId: globalThis.crypto.randomUUID(),
302
- chainInfo: this.chainInfo,
303
- appId: this.appId,
304
- walletId: this.extensionId,
305
- args: []
306
- };
307
- const encrypted = await encrypt(this.sharedKey, message);
308
- this.port.postMessage(encrypted);
309
- } catch {
310
- // Ignore errors sending disconnect message
311
- }
312
- }
313
- this.handleDisconnect();
314
263
  if (this.port) {
315
- this.port.close();
264
+ // Send unencrypted disconnect - control messages don't need encryption
265
+ this.port.postMessage({
266
+ type: WalletMessageType.DISCONNECT
267
+ });
316
268
  }
269
+ this.handleDisconnect();
317
270
  }
318
271
  }
@@ -0,0 +1,3 @@
1
+ export { ExtensionWallet, type DisconnectCallback } from './extension_wallet.js';
2
+ export { ExtensionProvider, type DiscoveredWallet, type ConnectedWallet, type DiscoveryOptions, } from './extension_provider.js';
3
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9leHRlbnNpb24vcHJvdmlkZXIvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUFFLGVBQWUsRUFBRSxLQUFLLGtCQUFrQixFQUFFLE1BQU0sdUJBQXVCLENBQUM7QUFDakYsT0FBTyxFQUNMLGlCQUFpQixFQUNqQixLQUFLLGdCQUFnQixFQUNyQixLQUFLLGVBQWUsRUFDcEIsS0FBSyxnQkFBZ0IsR0FDdEIsTUFBTSx5QkFBeUIsQ0FBQyJ9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extension/provider/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,KAAK,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACjF,OAAO,EACL,iBAAiB,EACjB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,gBAAgB,GACtB,MAAM,yBAAyB,CAAC"}
@@ -1,4 +1,2 @@
1
1
  export { ExtensionWallet } from './extension_wallet.js';
2
2
  export { ExtensionProvider } from './extension_provider.js';
3
- export * from '../../crypto.js';
4
- export { WalletMessageType } from '../../types.js';