@aztec/wallet-sdk 0.0.1-commit.0c875d939 → 0.0.1-commit.0ec55a70b
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 +66 -41
- package/dest/base-wallet/base_wallet.d.ts.map +1 -1
- package/dest/base-wallet/base_wallet.js +197 -82
- package/dest/base-wallet/index.d.ts +2 -2
- package/dest/base-wallet/index.d.ts.map +1 -1
- package/dest/base-wallet/utils.d.ts +5 -3
- package/dest/base-wallet/utils.d.ts.map +1 -1
- package/dest/base-wallet/utils.js +9 -4
- 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 +4 -6
- package/dest/extension/provider/extension_wallet.d.ts.map +1 -1
- package/dest/extension/provider/extension_wallet.js +9 -2
- 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 +6 -5
- 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 +48 -18
- 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 +275 -135
- package/src/base-wallet/index.ts +6 -1
- package/src/base-wallet/utils.ts +14 -4
- package/src/crypto.ts +104 -0
- package/src/extension/provider/extension_wallet.ts +13 -10
- 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 +5 -4
- package/src/manager/wallet_manager.ts +55 -23
- package/src/types.ts +13 -0
package/src/base-wallet/utils.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import type { AztecNode } from '@aztec/aztec.js/node';
|
|
2
|
+
import { TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
|
|
2
3
|
import { MAX_ENQUEUED_CALLS_PER_CALL } from '@aztec/constants';
|
|
3
4
|
import type { ChainInfo } from '@aztec/entrypoints/interfaces';
|
|
4
5
|
import { makeTuple } from '@aztec/foundation/array';
|
|
5
6
|
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
6
7
|
import type { Tuple } from '@aztec/foundation/serialize';
|
|
8
|
+
import type { ContractNameResolver } from '@aztec/pxe/client/lazy';
|
|
9
|
+
import { displayDebugLogs } from '@aztec/pxe/client/lazy';
|
|
7
10
|
import { generateSimulatedProvingResult } from '@aztec/pxe/simulator';
|
|
8
11
|
import { type FunctionCall, FunctionSelector } from '@aztec/stdlib/abi';
|
|
9
12
|
import type { AztecAddress } from '@aztec/stdlib/aztec-address';
|
|
@@ -72,6 +75,7 @@ async function simulateBatchViaNode(
|
|
|
72
75
|
gasSettings: GasSettings,
|
|
73
76
|
blockHeader: BlockHeader,
|
|
74
77
|
skipFeeEnforcement: boolean,
|
|
78
|
+
getContractName: ContractNameResolver,
|
|
75
79
|
): Promise<TxSimulationResult> {
|
|
76
80
|
const txContext = new TxContext(chainInfo.chainId, chainInfo.version, gasSettings);
|
|
77
81
|
|
|
@@ -145,6 +149,9 @@ async function simulateBatchViaNode(
|
|
|
145
149
|
throw publicOutput.revertReason;
|
|
146
150
|
}
|
|
147
151
|
|
|
152
|
+
// Display debug logs from the public simulation.
|
|
153
|
+
await displayDebugLogs(publicOutput.debugLogs, getContractName);
|
|
154
|
+
|
|
148
155
|
return new TxSimulationResult(privateResult, provingResult.publicInputs, publicOutput, undefined);
|
|
149
156
|
}
|
|
150
157
|
|
|
@@ -169,6 +176,7 @@ export async function simulateViaNode(
|
|
|
169
176
|
gasSettings: GasSettings,
|
|
170
177
|
blockHeader: BlockHeader,
|
|
171
178
|
skipFeeEnforcement: boolean = true,
|
|
179
|
+
getContractName: ContractNameResolver,
|
|
172
180
|
): Promise<TxSimulationResult[]> {
|
|
173
181
|
const batches: FunctionCall[][] = [];
|
|
174
182
|
|
|
@@ -187,6 +195,7 @@ export async function simulateViaNode(
|
|
|
187
195
|
gasSettings,
|
|
188
196
|
blockHeader,
|
|
189
197
|
skipFeeEnforcement,
|
|
198
|
+
getContractName,
|
|
190
199
|
);
|
|
191
200
|
results.push(result);
|
|
192
201
|
}
|
|
@@ -206,13 +215,13 @@ export async function simulateViaNode(
|
|
|
206
215
|
*/
|
|
207
216
|
export function buildMergedSimulationResult(
|
|
208
217
|
optimizedResults: TxSimulationResult[],
|
|
209
|
-
normalResult:
|
|
210
|
-
):
|
|
218
|
+
normalResult: TxSimulationResultWithAppOffset | null,
|
|
219
|
+
): TxSimulationResultWithAppOffset {
|
|
211
220
|
const optimizedReturnValues = optimizedResults.flatMap(r => r.publicOutput?.publicReturnValues ?? []);
|
|
212
221
|
const normalReturnValues = normalResult?.publicOutput?.publicReturnValues ?? [];
|
|
213
222
|
const allReturnValues = [...optimizedReturnValues, ...normalReturnValues];
|
|
214
223
|
|
|
215
|
-
const baseResult = normalResult ?? optimizedResults[0];
|
|
224
|
+
const baseResult: TxSimulationResult = normalResult ?? optimizedResults[0];
|
|
216
225
|
|
|
217
226
|
const mergedPublicOutput: PublicSimulationOutput | undefined = baseResult.publicOutput
|
|
218
227
|
? {
|
|
@@ -221,10 +230,11 @@ export function buildMergedSimulationResult(
|
|
|
221
230
|
}
|
|
222
231
|
: undefined;
|
|
223
232
|
|
|
224
|
-
|
|
233
|
+
const merged = new TxSimulationResult(
|
|
225
234
|
baseResult.privateExecutionResult,
|
|
226
235
|
baseResult.publicInputs,
|
|
227
236
|
mergedPublicOutput,
|
|
228
237
|
normalResult?.stats,
|
|
229
238
|
);
|
|
239
|
+
return TxSimulationResultWithAppOffset.fromResultAndOffset(merged, normalResult?.appCallOffset ?? 0);
|
|
230
240
|
}
|
package/src/crypto.ts
CHANGED
|
@@ -497,3 +497,107 @@ export function hashToEmoji(hash: string, count: number = DEFAULT_EMOJI_GRID_SIZ
|
|
|
497
497
|
}
|
|
498
498
|
return emojis.join('');
|
|
499
499
|
}
|
|
500
|
+
|
|
501
|
+
// ─── Passphrase-based encryption (PBKDF2 + AES-256-GCM) ───────────────────
|
|
502
|
+
|
|
503
|
+
/** Default PBKDF2 iteration count. High to compensate for short PINs (~1-2s on modern hardware). */
|
|
504
|
+
const DEFAULT_PBKDF2_ITERATIONS = 2_000_000;
|
|
505
|
+
const PBKDF2_SALT_BYTES = 16;
|
|
506
|
+
const PBKDF2_IV_BYTES = 12;
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Derives an AES-256-GCM key from a passphrase using PBKDF2-SHA256.
|
|
510
|
+
*
|
|
511
|
+
* @param passphrase - The user-provided passphrase or PIN
|
|
512
|
+
* @param salt - Random salt bytes
|
|
513
|
+
* @param iterations - PBKDF2 iteration count (default: 2,000,000)
|
|
514
|
+
* @returns An AES-256-GCM CryptoKey
|
|
515
|
+
*/
|
|
516
|
+
export async function deriveKeyFromPassphrase(
|
|
517
|
+
passphrase: string,
|
|
518
|
+
salt: Uint8Array,
|
|
519
|
+
iterations: number = DEFAULT_PBKDF2_ITERATIONS,
|
|
520
|
+
): Promise<CryptoKey> {
|
|
521
|
+
const keyMaterial = await crypto.subtle.importKey('raw', new TextEncoder().encode(passphrase), 'PBKDF2', false, [
|
|
522
|
+
'deriveKey',
|
|
523
|
+
]);
|
|
524
|
+
return crypto.subtle.deriveKey(
|
|
525
|
+
{ name: 'PBKDF2', salt: salt as BufferSource, iterations, hash: 'SHA-256' },
|
|
526
|
+
keyMaterial,
|
|
527
|
+
{ name: 'AES-GCM', length: 256 },
|
|
528
|
+
false,
|
|
529
|
+
['encrypt', 'decrypt'],
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Encrypts arbitrary bytes with a passphrase using PBKDF2 + AES-256-GCM.
|
|
535
|
+
*
|
|
536
|
+
* Output layout: `[salt (16)] [iv (12)] [ciphertext (...)]`
|
|
537
|
+
*
|
|
538
|
+
* @param plaintext - Data to encrypt
|
|
539
|
+
* @param passphrase - User passphrase or PIN
|
|
540
|
+
* @param iterations - PBKDF2 iteration count (default: 2,000,000)
|
|
541
|
+
* @returns A Uint8Array containing salt + iv + ciphertext
|
|
542
|
+
*/
|
|
543
|
+
export async function encryptWithPassphrase(
|
|
544
|
+
plaintext: Uint8Array,
|
|
545
|
+
passphrase: string,
|
|
546
|
+
iterations: number = DEFAULT_PBKDF2_ITERATIONS,
|
|
547
|
+
): Promise<Uint8Array> {
|
|
548
|
+
const salt = crypto.getRandomValues(new Uint8Array(PBKDF2_SALT_BYTES));
|
|
549
|
+
const iv = crypto.getRandomValues(new Uint8Array(PBKDF2_IV_BYTES));
|
|
550
|
+
const key = await deriveKeyFromPassphrase(passphrase, salt, iterations);
|
|
551
|
+
const ciphertext = new Uint8Array(
|
|
552
|
+
await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext as BufferSource),
|
|
553
|
+
);
|
|
554
|
+
const result = new Uint8Array(PBKDF2_SALT_BYTES + PBKDF2_IV_BYTES + ciphertext.length);
|
|
555
|
+
result.set(salt, 0);
|
|
556
|
+
result.set(iv, PBKDF2_SALT_BYTES);
|
|
557
|
+
result.set(ciphertext, PBKDF2_SALT_BYTES + PBKDF2_IV_BYTES);
|
|
558
|
+
return result;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Decrypts data produced by {@link encryptWithPassphrase}.
|
|
563
|
+
*
|
|
564
|
+
* @param data - The encrypted blob (salt + iv + ciphertext)
|
|
565
|
+
* @param passphrase - The passphrase used during encryption
|
|
566
|
+
* @param iterations - PBKDF2 iteration count (must match encryption)
|
|
567
|
+
* @returns The decrypted plaintext bytes
|
|
568
|
+
* @throws On wrong passphrase (AES-GCM auth tag mismatch)
|
|
569
|
+
*/
|
|
570
|
+
export async function decryptWithPassphrase(
|
|
571
|
+
data: Uint8Array,
|
|
572
|
+
passphrase: string,
|
|
573
|
+
iterations: number = DEFAULT_PBKDF2_ITERATIONS,
|
|
574
|
+
): Promise<Uint8Array> {
|
|
575
|
+
const salt = data.slice(0, PBKDF2_SALT_BYTES);
|
|
576
|
+
const iv = data.slice(PBKDF2_SALT_BYTES, PBKDF2_SALT_BYTES + PBKDF2_IV_BYTES);
|
|
577
|
+
const ciphertext = data.slice(PBKDF2_SALT_BYTES + PBKDF2_IV_BYTES);
|
|
578
|
+
const key = await deriveKeyFromPassphrase(passphrase, salt, iterations);
|
|
579
|
+
return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext as BufferSource));
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Converts a Uint8Array to a base64 string.
|
|
584
|
+
*/
|
|
585
|
+
export function uint8ToBase64(bytes: Uint8Array): string {
|
|
586
|
+
let binary = '';
|
|
587
|
+
for (const b of bytes) {
|
|
588
|
+
binary += String.fromCharCode(b);
|
|
589
|
+
}
|
|
590
|
+
return btoa(binary);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* Converts a base64 string to a Uint8Array.
|
|
595
|
+
*/
|
|
596
|
+
export function base64ToUint8(b64: string): Uint8Array {
|
|
597
|
+
const binary = atob(b64);
|
|
598
|
+
const bytes = new Uint8Array(binary.length);
|
|
599
|
+
for (let i = 0; i < binary.length; i++) {
|
|
600
|
+
bytes[i] = binary.charCodeAt(i);
|
|
601
|
+
}
|
|
602
|
+
return bytes;
|
|
603
|
+
}
|
|
@@ -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.
|
|
@@ -109,7 +104,7 @@ export class ExtensionWallet {
|
|
|
109
104
|
sharedKey: CryptoKey,
|
|
110
105
|
chainInfo: ChainInfo,
|
|
111
106
|
appId: string,
|
|
112
|
-
):
|
|
107
|
+
): ExtensionWallet {
|
|
113
108
|
const wallet = new ExtensionWallet(chainInfo, appId, extensionId, port, sharedKey);
|
|
114
109
|
|
|
115
110
|
// Set up message handler for encrypted responses and unencrypted control messages
|
|
@@ -127,8 +122,10 @@ export class ExtensionWallet {
|
|
|
127
122
|
wallet.port.start();
|
|
128
123
|
|
|
129
124
|
return new Proxy(wallet, {
|
|
130
|
-
get: (target, prop) => {
|
|
131
|
-
if (
|
|
125
|
+
get: (target, prop, receiver) => {
|
|
126
|
+
if (prop === 'asWallet') {
|
|
127
|
+
return () => receiver as unknown as Wallet;
|
|
128
|
+
} else if (schemaHasMethod(WalletSchema, prop.toString())) {
|
|
132
129
|
return async (...args: unknown[]) => {
|
|
133
130
|
const result = await target.postMessage({
|
|
134
131
|
type: prop.toString() as keyof FunctionsOf<Wallet>,
|
|
@@ -140,7 +137,13 @@ export class ExtensionWallet {
|
|
|
140
137
|
return target[prop as keyof ExtensionWallet];
|
|
141
138
|
}
|
|
142
139
|
},
|
|
143
|
-
})
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
asWallet(): Wallet {
|
|
144
|
+
// Overridden by the proxy in create() to return the proxy itself.
|
|
145
|
+
// This body is never reached when accessed through create().
|
|
146
|
+
return this as unknown as Wallet;
|
|
144
147
|
}
|
|
145
148
|
|
|
146
149
|
/**
|
|
@@ -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
|
+
}
|