@opendatalabs/vana-sdk 0.1.0-alpha.5f8458e → 0.1.0-alpha.606fa2d

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 (50) hide show
  1. package/README.md +55 -4
  2. package/dist/{browser-cRpdLQ3-.d.ts → browser-Bb8gLWHp.d.ts} +61 -10
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +745 -113
  5. package/dist/browser.js.map +1 -1
  6. package/dist/chains.browser.cjs +2 -2
  7. package/dist/chains.browser.cjs.map +1 -1
  8. package/dist/chains.browser.js +2 -2
  9. package/dist/chains.browser.js.map +1 -1
  10. package/dist/chains.cjs +2 -2
  11. package/dist/chains.cjs.map +1 -1
  12. package/dist/chains.js +2 -2
  13. package/dist/chains.js.map +1 -1
  14. package/dist/chains.node.cjs +2 -2
  15. package/dist/chains.node.cjs.map +1 -1
  16. package/dist/chains.node.js +2 -2
  17. package/dist/chains.node.js.map +1 -1
  18. package/dist/index.browser.d.ts +1348 -243
  19. package/dist/index.browser.js +35080 -32770
  20. package/dist/index.browser.js.map +1 -1
  21. package/dist/index.node.cjs +35587 -33174
  22. package/dist/index.node.cjs.map +1 -1
  23. package/dist/index.node.d.cts +1136 -250
  24. package/dist/index.node.d.ts +1136 -250
  25. package/dist/index.node.js +35459 -33037
  26. package/dist/index.node.js.map +1 -1
  27. package/dist/{node-CkdgwBiv.d.cts → node-D9-F9uEP.d.cts} +3 -2
  28. package/dist/{node-CkdgwBiv.d.ts → node-D9-F9uEP.d.ts} +3 -2
  29. package/dist/node.cjs +704 -67
  30. package/dist/node.cjs.map +1 -1
  31. package/dist/node.d.cts +1 -1
  32. package/dist/node.d.ts +1 -1
  33. package/dist/node.js +716 -66
  34. package/dist/node.js.map +1 -1
  35. package/dist/platform.browser.d.ts +2 -2
  36. package/dist/platform.browser.js +808 -121
  37. package/dist/platform.browser.js.map +1 -1
  38. package/dist/platform.cjs +973 -186
  39. package/dist/platform.cjs.map +1 -1
  40. package/dist/platform.d.cts +1 -1
  41. package/dist/platform.d.ts +1 -1
  42. package/dist/platform.js +985 -186
  43. package/dist/platform.js.map +1 -1
  44. package/dist/platform.node.cjs +973 -186
  45. package/dist/platform.node.cjs.map +1 -1
  46. package/dist/platform.node.d.cts +63 -12
  47. package/dist/platform.node.d.ts +63 -12
  48. package/dist/platform.node.js +985 -186
  49. package/dist/platform.node.js.map +1 -1
  50. package/package.json +40 -23
package/dist/platform.js CHANGED
@@ -1,5 +1,11 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
3
9
  var __esm = (fn, res) => function __init() {
4
10
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
11
  };
@@ -8,31 +14,6 @@ var __export = (target, all) => {
8
14
  __defProp(target, name, { get: all[name], enumerable: true });
9
15
  };
10
16
 
11
- // src/platform/shared/crypto-utils.ts
12
- function processWalletPublicKey(publicKey) {
13
- const publicKeyHex = publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey;
14
- const publicKeyBytes = Buffer.from(publicKeyHex, "hex");
15
- return publicKeyBytes.length === 64 ? Buffer.concat([Buffer.from([4]), publicKeyBytes]) : publicKeyBytes;
16
- }
17
- function processWalletPrivateKey(privateKey) {
18
- const privateKeyHex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
19
- return Buffer.from(privateKeyHex, "hex");
20
- }
21
- function parseEncryptedDataBuffer(encryptedBuffer) {
22
- return {
23
- iv: encryptedBuffer.slice(0, 16),
24
- ephemPublicKey: encryptedBuffer.slice(16, 81),
25
- // 65 bytes for uncompressed public key
26
- ciphertext: encryptedBuffer.slice(81, -32),
27
- mac: encryptedBuffer.slice(-32)
28
- };
29
- }
30
- var init_crypto_utils = __esm({
31
- "src/platform/shared/crypto-utils.ts"() {
32
- "use strict";
33
- }
34
- });
35
-
36
17
  // src/platform/shared/pgp-utils.ts
37
18
  function processPGPKeyOptions(options) {
38
19
  return {
@@ -75,144 +56,854 @@ var init_error_utils = __esm({
75
56
  }
76
57
  });
77
58
 
59
+ // src/utils/lazy-import.ts
60
+ function lazyImport(importFn) {
61
+ let cached = null;
62
+ return () => {
63
+ if (!cached) {
64
+ cached = importFn().catch((err) => {
65
+ cached = null;
66
+ throw new Error("Failed to load module", { cause: err });
67
+ });
68
+ }
69
+ return cached;
70
+ };
71
+ }
72
+ var init_lazy_import = __esm({
73
+ "src/utils/lazy-import.ts"() {
74
+ "use strict";
75
+ }
76
+ });
77
+
78
+ // src/utils/encoding.ts
79
+ function toHex(data) {
80
+ if (typeof Buffer !== "undefined" && Buffer.from) {
81
+ return Buffer.from(data).toString("hex");
82
+ }
83
+ return Array.from(data, (byte) => byte.toString(16).padStart(2, "0")).join(
84
+ ""
85
+ );
86
+ }
87
+ function fromHex(hex) {
88
+ const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
89
+ if (cleanHex.length % 2 !== 0) {
90
+ throw new Error("Invalid hex string: odd length");
91
+ }
92
+ if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {
93
+ throw new Error("Invalid hex string: contains non-hex characters");
94
+ }
95
+ if (typeof Buffer !== "undefined" && Buffer.from) {
96
+ return new Uint8Array(Buffer.from(cleanHex, "hex"));
97
+ }
98
+ const bytes = new Uint8Array(cleanHex.length / 2);
99
+ for (let i = 0; i < cleanHex.length; i += 2) {
100
+ bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);
101
+ }
102
+ return bytes;
103
+ }
104
+ function stringToBytes(str) {
105
+ if (typeof Buffer !== "undefined" && Buffer.from) {
106
+ return new Uint8Array(Buffer.from(str, "utf8"));
107
+ }
108
+ if (typeof TextEncoder !== "undefined") {
109
+ return new TextEncoder().encode(str);
110
+ }
111
+ const bytes = [];
112
+ for (let i = 0; i < str.length; i++) {
113
+ const char = str.charCodeAt(i);
114
+ if (char < 128) {
115
+ bytes.push(char);
116
+ } else if (char < 2048) {
117
+ bytes.push(192 | char >> 6, 128 | char & 63);
118
+ } else if (char < 55296 || char >= 57344) {
119
+ bytes.push(
120
+ 224 | char >> 12,
121
+ 128 | char >> 6 & 63,
122
+ 128 | char & 63
123
+ );
124
+ } else {
125
+ i++;
126
+ const char2 = str.charCodeAt(i);
127
+ const codePoint = 65536 + ((char & 1023) << 10 | char2 & 1023);
128
+ bytes.push(
129
+ 240 | codePoint >> 18,
130
+ 128 | codePoint >> 12 & 63,
131
+ 128 | codePoint >> 6 & 63,
132
+ 128 | codePoint & 63
133
+ );
134
+ }
135
+ }
136
+ return new Uint8Array(bytes);
137
+ }
138
+ function bytesToString(bytes) {
139
+ if (typeof Buffer !== "undefined" && Buffer.from) {
140
+ return Buffer.from(bytes).toString("utf8");
141
+ }
142
+ if (typeof TextDecoder !== "undefined") {
143
+ return new TextDecoder().decode(bytes);
144
+ }
145
+ let str = "";
146
+ let i = 0;
147
+ while (i < bytes.length) {
148
+ const byte = bytes[i];
149
+ if (byte < 128) {
150
+ str += String.fromCharCode(byte);
151
+ i++;
152
+ } else if ((byte & 224) === 192) {
153
+ str += String.fromCharCode((byte & 31) << 6 | bytes[i + 1] & 63);
154
+ i += 2;
155
+ } else if ((byte & 240) === 224) {
156
+ str += String.fromCharCode(
157
+ (byte & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63
158
+ );
159
+ i += 3;
160
+ } else {
161
+ const codePoint = ((byte & 7) << 18 | (bytes[i + 1] & 63) << 12 | (bytes[i + 2] & 63) << 6 | bytes[i + 3] & 63) - 65536;
162
+ str += String.fromCharCode(
163
+ 55296 + (codePoint >> 10),
164
+ 56320 + (codePoint & 1023)
165
+ );
166
+ i += 4;
167
+ }
168
+ }
169
+ return str;
170
+ }
171
+ var init_encoding = __esm({
172
+ "src/utils/encoding.ts"() {
173
+ "use strict";
174
+ }
175
+ });
176
+
177
+ // src/utils/crypto-utils.ts
178
+ function concatBytes(...arrays) {
179
+ const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
180
+ const result = new Uint8Array(totalLength);
181
+ let offset = 0;
182
+ for (const arr of arrays) {
183
+ result.set(arr, offset);
184
+ offset += arr.length;
185
+ }
186
+ return result;
187
+ }
188
+ function hexToBytes(hex) {
189
+ return fromHex(hex);
190
+ }
191
+ function bytesToHex(bytes) {
192
+ return toHex(bytes);
193
+ }
194
+ function processWalletPublicKey(publicKey) {
195
+ const publicKeyHex = typeof publicKey === "string" ? publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey : bytesToHex(publicKey);
196
+ const publicKeyBytes = hexToBytes(publicKeyHex);
197
+ return publicKeyBytes.length === 64 ? concatBytes(new Uint8Array([4]), publicKeyBytes) : publicKeyBytes;
198
+ }
199
+ function processWalletPrivateKey(privateKey) {
200
+ const privateKeyHex = typeof privateKey === "string" ? privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey : bytesToHex(privateKey);
201
+ return hexToBytes(privateKeyHex);
202
+ }
203
+ function parseEncryptedDataBuffer(encryptedBuffer) {
204
+ return {
205
+ iv: encryptedBuffer.slice(0, 16),
206
+ ephemPublicKey: encryptedBuffer.slice(16, 81),
207
+ // 65 bytes for uncompressed public key
208
+ ciphertext: encryptedBuffer.slice(81, -32),
209
+ mac: encryptedBuffer.slice(-32)
210
+ };
211
+ }
212
+ var init_crypto_utils = __esm({
213
+ "src/utils/crypto-utils.ts"() {
214
+ "use strict";
215
+ init_encoding();
216
+ }
217
+ });
218
+
219
+ // src/crypto/services/WalletKeyEncryptionService.ts
220
+ var WalletKeyEncryptionService;
221
+ var init_WalletKeyEncryptionService = __esm({
222
+ "src/crypto/services/WalletKeyEncryptionService.ts"() {
223
+ "use strict";
224
+ init_crypto_utils();
225
+ init_encoding();
226
+ WalletKeyEncryptionService = class {
227
+ eciesProvider;
228
+ constructor(config) {
229
+ this.eciesProvider = config.eciesProvider;
230
+ }
231
+ /**
232
+ * Encrypts data using a wallet's public key.
233
+ *
234
+ * @param data - The plaintext message to encrypt for the wallet owner.
235
+ * @param publicKey - The recipient wallet's public key for encryption.
236
+ * @returns A promise that resolves to the encrypted data as a hex string.
237
+ * @throws {Error} When encryption fails due to invalid key format.
238
+ *
239
+ * @example
240
+ * ```typescript
241
+ * const encrypted = await processor.encryptWithWalletPublicKey(
242
+ * "Secret message",
243
+ * "0x04..." // 65-byte uncompressed public key
244
+ * );
245
+ * console.log(`Encrypted: ${encrypted}`);
246
+ * ```
247
+ */
248
+ async encryptWithWalletPublicKey(data, publicKey) {
249
+ const publicKeyBytes = processWalletPublicKey(publicKey);
250
+ const dataBytes = stringToBytes(data);
251
+ const encrypted = await this.eciesProvider.encrypt(
252
+ publicKeyBytes,
253
+ dataBytes
254
+ );
255
+ const result = concatBytes(
256
+ encrypted.iv,
257
+ encrypted.ephemPublicKey,
258
+ encrypted.ciphertext,
259
+ encrypted.mac
260
+ );
261
+ return bytesToHex(result);
262
+ }
263
+ /**
264
+ * Decrypts data using a wallet's private key.
265
+ *
266
+ * @param encryptedData - The hex-encoded encrypted data to decrypt.
267
+ * @param privateKey - The wallet's private key for decryption.
268
+ * @returns A promise that resolves to the decrypted plaintext message.
269
+ * @throws {Error} When decryption fails due to invalid data or key format.
270
+ *
271
+ * @example
272
+ * ```typescript
273
+ * const decrypted = await processor.decryptWithWalletPrivateKey(
274
+ * encryptedHexString,
275
+ * "0x..." // 32-byte private key
276
+ * );
277
+ * console.log(`Decrypted: ${decrypted}`);
278
+ * ```
279
+ */
280
+ async decryptWithWalletPrivateKey(encryptedData, privateKey) {
281
+ const privateKeyBytes = processWalletPrivateKey(privateKey);
282
+ const encryptedBytes = hexToBytes(encryptedData);
283
+ const encrypted = parseEncryptedDataBuffer(encryptedBytes);
284
+ const decrypted = await this.eciesProvider.decrypt(
285
+ privateKeyBytes,
286
+ encrypted
287
+ );
288
+ return bytesToString(decrypted);
289
+ }
290
+ /**
291
+ * Encrypts a Uint8Array with a wallet public key
292
+ *
293
+ * @param data - Binary data to encrypt
294
+ * @param publicKey - Public key as hex string or Uint8Array
295
+ * @returns Encrypted data structure
296
+ */
297
+ async encryptBinary(data, publicKey) {
298
+ const publicKeyBytes = processWalletPublicKey(publicKey);
299
+ return this.eciesProvider.encrypt(publicKeyBytes, data);
300
+ }
301
+ /**
302
+ * Decrypts to a Uint8Array with a wallet private key
303
+ *
304
+ * @param encrypted - Encrypted data structure
305
+ * @param privateKey - Private key as hex string or Uint8Array
306
+ * @returns Decrypted binary data
307
+ */
308
+ async decryptBinary(encrypted, privateKey) {
309
+ const privateKeyBytes = processWalletPrivateKey(privateKey);
310
+ return this.eciesProvider.decrypt(privateKeyBytes, encrypted);
311
+ }
312
+ /**
313
+ * Gets the underlying ECIES provider
314
+ *
315
+ * @returns The ECIES provider instance
316
+ */
317
+ getECIESProvider() {
318
+ return this.eciesProvider;
319
+ }
320
+ };
321
+ }
322
+ });
323
+
324
+ // src/crypto/ecies/utils.ts
325
+ function hexToBytes2(hex) {
326
+ if (hex.length % 2 !== 0) {
327
+ throw new Error("Hex string must have even length");
328
+ }
329
+ const bytes = new Uint8Array(hex.length / 2);
330
+ for (let i = 0; i < hex.length; i += 2) {
331
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
332
+ }
333
+ return bytes;
334
+ }
335
+ function bytesToHex2(bytes) {
336
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
337
+ }
338
+ function stringToBytes2(str) {
339
+ return new TextEncoder().encode(str);
340
+ }
341
+ function bytesToString2(bytes) {
342
+ return new TextDecoder().decode(bytes);
343
+ }
344
+ function concatBytes2(...arrays) {
345
+ const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
346
+ const result = new Uint8Array(totalLength);
347
+ let offset = 0;
348
+ for (const arr of arrays) {
349
+ result.set(arr, offset);
350
+ offset += arr.length;
351
+ }
352
+ return result;
353
+ }
354
+ function constantTimeEqual(a, b) {
355
+ if (a.length !== b.length) return false;
356
+ let result = 0;
357
+ for (let i = 0; i < a.length; i++) {
358
+ result |= a[i] ^ b[i];
359
+ }
360
+ return result === 0;
361
+ }
362
+ var init_utils = __esm({
363
+ "src/crypto/ecies/utils.ts"() {
364
+ "use strict";
365
+ }
366
+ });
367
+
368
+ // src/crypto/ecies/constants.ts
369
+ var CURVE, CIPHER, KDF, MAC, FORMAT;
370
+ var init_constants = __esm({
371
+ "src/crypto/ecies/constants.ts"() {
372
+ "use strict";
373
+ CURVE = {
374
+ /** The elliptic curve used (secp256k1 - same as Bitcoin/Ethereum) */
375
+ name: "secp256k1",
376
+ /** Private key length in bytes */
377
+ PRIVATE_KEY_LENGTH: 32,
378
+ /** Compressed public key length in bytes (0x02 or 0x03 prefix + 32 bytes) */
379
+ COMPRESSED_PUBLIC_KEY_LENGTH: 33,
380
+ /** Uncompressed public key length in bytes (0x04 prefix + 64 bytes) */
381
+ UNCOMPRESSED_PUBLIC_KEY_LENGTH: 65,
382
+ /** ECDH shared secret X coordinate length */
383
+ SHARED_SECRET_LENGTH: 32,
384
+ /** Public key prefixes */
385
+ PREFIX: {
386
+ /** Uncompressed public key prefix */
387
+ UNCOMPRESSED: 4,
388
+ /** Compressed public key prefix for even Y */
389
+ COMPRESSED_EVEN: 2,
390
+ /** Compressed public key prefix for odd Y */
391
+ COMPRESSED_ODD: 3
392
+ },
393
+ /** X coordinate starts at byte 1 (after prefix) */
394
+ X_COORDINATE_OFFSET: 1,
395
+ /** X coordinate ends at byte 33 (1 + 32) */
396
+ X_COORDINATE_END: 33
397
+ };
398
+ CIPHER = {
399
+ /** Cipher algorithm - must match eccrypto */
400
+ algorithm: "aes-256-cbc",
401
+ /** AES key length in bytes */
402
+ KEY_LENGTH: 32,
403
+ /** Initialization vector length in bytes */
404
+ IV_LENGTH: 16,
405
+ /** Block size for AES */
406
+ BLOCK_SIZE: 16
407
+ };
408
+ KDF = {
409
+ /** Hash algorithm for key derivation - must match eccrypto */
410
+ algorithm: "sha512",
411
+ /** Output length of SHA-512 in bytes */
412
+ OUTPUT_LENGTH: 64,
413
+ /** Encryption key slice (first 32 bytes of KDF output) */
414
+ ENCRYPTION_KEY_OFFSET: 0,
415
+ ENCRYPTION_KEY_LENGTH: 32,
416
+ /** MAC key slice (last 32 bytes of KDF output) */
417
+ MAC_KEY_OFFSET: 32,
418
+ MAC_KEY_LENGTH: 32
419
+ };
420
+ MAC = {
421
+ /** MAC algorithm - must match eccrypto */
422
+ algorithm: "sha256",
423
+ /** HMAC-SHA256 output length in bytes */
424
+ LENGTH: 32
425
+ };
426
+ FORMAT = {
427
+ /** Offsets for each component in serialized format */
428
+ IV_OFFSET: 0,
429
+ IV_LENGTH: CIPHER.IV_LENGTH,
430
+ /** Ephemeral public key (always uncompressed in eccrypto format) */
431
+ EPHEMERAL_KEY_OFFSET: CIPHER.IV_LENGTH,
432
+ EPHEMERAL_KEY_LENGTH: CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
433
+ /** Ciphertext starts after IV and ephemeral key */
434
+ CIPHERTEXT_OFFSET: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,
435
+ /** MAC is always the last 32 bytes */
436
+ MAC_LENGTH: MAC.LENGTH,
437
+ /** Minimum size of encrypted data (IV + ephemKey + MAC, no ciphertext) */
438
+ MIN_ENCRYPTED_LENGTH: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + MAC.LENGTH,
439
+ /**
440
+ * Helper to calculate total length of encrypted data
441
+ *
442
+ * @param ciphertextLength - Length of the ciphertext portion
443
+ * @returns Total length including all components
444
+ */
445
+ getTotalLength: (ciphertextLength) => CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + ciphertextLength + MAC.LENGTH
446
+ };
447
+ }
448
+ });
449
+
450
+ // src/crypto/ecies/interface.ts
451
+ function isECIESEncrypted(obj) {
452
+ if (!obj || typeof obj !== "object") return false;
453
+ const enc = obj;
454
+ const isUint8Array = (value) => {
455
+ return value instanceof Uint8Array || typeof Buffer !== "undefined" && Buffer.isBuffer(value);
456
+ };
457
+ return isUint8Array(enc.iv) && enc.iv.length === CIPHER.IV_LENGTH && isUint8Array(enc.ephemPublicKey) && (enc.ephemPublicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH || enc.ephemPublicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) && isUint8Array(enc.ciphertext) && enc.ciphertext.length > 0 && isUint8Array(enc.mac) && enc.mac.length === MAC.LENGTH;
458
+ }
459
+ var ECIESError;
460
+ var init_interface = __esm({
461
+ "src/crypto/ecies/interface.ts"() {
462
+ "use strict";
463
+ init_constants();
464
+ ECIESError = class extends Error {
465
+ constructor(message, code, cause) {
466
+ super(message);
467
+ this.code = code;
468
+ this.cause = cause;
469
+ this.name = "ECIESError";
470
+ }
471
+ };
472
+ }
473
+ });
474
+
475
+ // src/crypto/ecies/base.ts
476
+ var BaseECIESUint8;
477
+ var init_base = __esm({
478
+ "src/crypto/ecies/base.ts"() {
479
+ "use strict";
480
+ init_interface();
481
+ init_constants();
482
+ init_utils();
483
+ BaseECIESUint8 = class _BaseECIESUint8 {
484
+ // Cache for validated public keys to avoid repeated validation
485
+ static validatedKeys = /* @__PURE__ */ new WeakMap();
486
+ /**
487
+ * Normalizes a public key to uncompressed format.
488
+ *
489
+ * @param publicKey - Public key in any format.
490
+ * @returns Uncompressed public key (65 bytes).
491
+ * @throws {ECIESError} If key format is invalid.
492
+ */
493
+ normalizePublicKey(publicKey) {
494
+ if (_BaseECIESUint8.validatedKeys.has(publicKey)) {
495
+ return publicKey;
496
+ }
497
+ if (publicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH) {
498
+ if (publicKey[0] !== CURVE.PREFIX.UNCOMPRESSED) {
499
+ throw new ECIESError(
500
+ "Invalid uncompressed public key prefix",
501
+ "INVALID_KEY"
502
+ );
503
+ }
504
+ if (!this.validatePublicKey(publicKey)) {
505
+ throw new ECIESError("Invalid public key", "INVALID_KEY");
506
+ }
507
+ _BaseECIESUint8.validatedKeys.set(publicKey, true);
508
+ return publicKey;
509
+ }
510
+ if (publicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) {
511
+ const decompressed = this.decompressPublicKey(publicKey);
512
+ if (!decompressed) {
513
+ throw new ECIESError("Failed to decompress public key", "INVALID_KEY");
514
+ }
515
+ _BaseECIESUint8.validatedKeys.set(decompressed, true);
516
+ return decompressed;
517
+ }
518
+ throw new ECIESError(
519
+ `Invalid public key length: ${publicKey.length}`,
520
+ "INVALID_KEY"
521
+ );
522
+ }
523
+ /**
524
+ * Encrypts data using ECIES.
525
+ *
526
+ * @param publicKey - The recipient's public key (compressed or uncompressed)
527
+ * @param message - The data to encrypt
528
+ * @returns Promise resolving to encrypted data structure
529
+ */
530
+ async encrypt(publicKey, message) {
531
+ try {
532
+ if (!(publicKey instanceof Uint8Array)) {
533
+ throw new ECIESError("Public key must be a Uint8Array", "INVALID_KEY");
534
+ }
535
+ if (!(message instanceof Uint8Array)) {
536
+ throw new ECIESError(
537
+ "Message must be a Uint8Array",
538
+ "ENCRYPTION_FAILED"
539
+ );
540
+ }
541
+ if (publicKey.length === 0) {
542
+ throw new ECIESError("Public key cannot be empty", "INVALID_KEY");
543
+ }
544
+ const pubKey = this.normalizePublicKey(publicKey);
545
+ let ephemeralPrivateKey;
546
+ do {
547
+ ephemeralPrivateKey = this.generateRandomBytes(
548
+ CURVE.PRIVATE_KEY_LENGTH
549
+ );
550
+ } while (!this.verifyPrivateKey(ephemeralPrivateKey));
551
+ const ephemeralPublicKey = this.createPublicKey(
552
+ ephemeralPrivateKey,
553
+ false
554
+ );
555
+ if (!ephemeralPublicKey) {
556
+ throw new ECIESError(
557
+ "Failed to generate ephemeral public key",
558
+ "ENCRYPTION_FAILED"
559
+ );
560
+ }
561
+ const sharedSecret = this.performECDH(pubKey, ephemeralPrivateKey);
562
+ const kdf = this.sha512(sharedSecret);
563
+ const encryptionKey = kdf.slice(
564
+ KDF.ENCRYPTION_KEY_OFFSET,
565
+ KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
566
+ );
567
+ const macKey = kdf.slice(
568
+ KDF.MAC_KEY_OFFSET,
569
+ KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
570
+ );
571
+ const iv = this.generateRandomBytes(CIPHER.IV_LENGTH);
572
+ const ciphertext = await this.aesEncrypt(encryptionKey, iv, message);
573
+ const macData = concatBytes2(iv, ephemeralPublicKey, ciphertext);
574
+ const mac = this.hmacSha256(macKey, macData);
575
+ this.clearBuffer(ephemeralPrivateKey);
576
+ this.clearBuffer(sharedSecret);
577
+ this.clearBuffer(kdf);
578
+ return {
579
+ iv,
580
+ ephemPublicKey: ephemeralPublicKey,
581
+ ciphertext,
582
+ mac
583
+ };
584
+ } catch (error) {
585
+ if (error instanceof ECIESError) throw error;
586
+ throw new ECIESError(
587
+ `Encryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
588
+ "ENCRYPTION_FAILED",
589
+ error instanceof Error ? error : void 0
590
+ );
591
+ }
592
+ }
593
+ /**
594
+ * Decrypts ECIES encrypted data.
595
+ *
596
+ * @param privateKey - The recipient's private key (32 bytes)
597
+ * @param encrypted - The encrypted data structure from encrypt()
598
+ * @returns Promise resolving to the original plaintext
599
+ */
600
+ async decrypt(privateKey, encrypted) {
601
+ try {
602
+ if (!(privateKey instanceof Uint8Array)) {
603
+ throw new ECIESError("Private key must be a Uint8Array", "INVALID_KEY");
604
+ }
605
+ if (!isECIESEncrypted(encrypted)) {
606
+ throw new ECIESError(
607
+ "Invalid encrypted data structure",
608
+ "DECRYPTION_FAILED"
609
+ );
610
+ }
611
+ if (privateKey.length !== CURVE.PRIVATE_KEY_LENGTH) {
612
+ throw new ECIESError(
613
+ `Invalid private key length: ${privateKey.length}`,
614
+ "INVALID_KEY"
615
+ );
616
+ }
617
+ if (!this.verifyPrivateKey(privateKey)) {
618
+ throw new ECIESError("Invalid private key", "INVALID_KEY");
619
+ }
620
+ const ephemeralPublicKey = this.normalizePublicKey(
621
+ encrypted.ephemPublicKey
622
+ );
623
+ const sharedSecret = this.performECDH(ephemeralPublicKey, privateKey);
624
+ const kdf = this.sha512(sharedSecret);
625
+ const encryptionKey = kdf.slice(
626
+ KDF.ENCRYPTION_KEY_OFFSET,
627
+ KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH
628
+ );
629
+ const macKey = kdf.slice(
630
+ KDF.MAC_KEY_OFFSET,
631
+ KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH
632
+ );
633
+ const macData = concatBytes2(
634
+ encrypted.iv,
635
+ encrypted.ephemPublicKey,
636
+ encrypted.ciphertext
637
+ );
638
+ const expectedMac = this.hmacSha256(macKey, macData);
639
+ if (!constantTimeEqual(encrypted.mac, expectedMac)) {
640
+ throw new ECIESError("MAC verification failed", "MAC_MISMATCH");
641
+ }
642
+ const decrypted = await this.aesDecrypt(
643
+ encryptionKey,
644
+ encrypted.iv,
645
+ encrypted.ciphertext
646
+ );
647
+ this.clearBuffer(sharedSecret);
648
+ this.clearBuffer(kdf);
649
+ return decrypted;
650
+ } catch (error) {
651
+ if (error instanceof ECIESError) throw error;
652
+ throw new ECIESError(
653
+ `Decryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
654
+ "DECRYPTION_FAILED",
655
+ error instanceof Error ? error : void 0
656
+ );
657
+ }
658
+ }
659
+ /**
660
+ * Clears sensitive data from memory using multi-pass overwrite.
661
+ *
662
+ * @remarks
663
+ * Uses multiple passes with different patterns to make it harder
664
+ * for JIT compilers to optimize away the operation. While not
665
+ * guaranteed in JavaScript, this is a best-effort approach to
666
+ * clear sensitive data from memory.
667
+ *
668
+ * @param buffer - The buffer to clear
669
+ */
670
+ clearBuffer(buffer) {
671
+ if (buffer && buffer.length > 0) {
672
+ buffer.fill(0);
673
+ buffer.fill(255);
674
+ buffer.fill(170);
675
+ buffer.fill(0);
676
+ for (let i = 0; i < buffer.length; i++) {
677
+ buffer[i] = i & 255 ^ 90;
678
+ }
679
+ buffer.fill(0);
680
+ }
681
+ }
682
+ };
683
+ }
684
+ });
685
+
686
+ // src/crypto/ecies/browser.ts
687
+ import * as secp256k1 from "@noble/secp256k1";
688
+ import { hmac } from "@noble/hashes/hmac";
689
+ import { sha256, sha512 as nobleSha512 } from "@noble/hashes/sha2";
690
+ var BrowserECIESUint8Provider;
691
+ var init_browser = __esm({
692
+ "src/crypto/ecies/browser.ts"() {
693
+ "use strict";
694
+ init_base();
695
+ BrowserECIESUint8Provider = class extends BaseECIESUint8 {
696
+ generateRandomBytes(length) {
697
+ const bytes = new Uint8Array(length);
698
+ crypto.getRandomValues(bytes);
699
+ return bytes;
700
+ }
701
+ verifyPrivateKey(privateKey) {
702
+ try {
703
+ return secp256k1.utils.isValidPrivateKey(privateKey);
704
+ } catch {
705
+ return false;
706
+ }
707
+ }
708
+ createPublicKey(privateKey, compressed) {
709
+ try {
710
+ return secp256k1.getPublicKey(privateKey, compressed);
711
+ } catch {
712
+ return null;
713
+ }
714
+ }
715
+ validatePublicKey(publicKey) {
716
+ try {
717
+ secp256k1.Point.fromHex(publicKey);
718
+ return true;
719
+ } catch {
720
+ return false;
721
+ }
722
+ }
723
+ decompressPublicKey(publicKey) {
724
+ try {
725
+ const point = secp256k1.Point.fromHex(publicKey);
726
+ return point.toRawBytes(false);
727
+ } catch {
728
+ return null;
729
+ }
730
+ }
731
+ performECDH(publicKey, privateKey) {
732
+ try {
733
+ const sharedPoint = secp256k1.getSharedSecret(
734
+ privateKey,
735
+ publicKey,
736
+ true
737
+ );
738
+ return sharedPoint.slice(1);
739
+ } catch (error) {
740
+ throw new Error(
741
+ `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
742
+ );
743
+ }
744
+ }
745
+ sha512(data) {
746
+ return nobleSha512(data);
747
+ }
748
+ hmacSha256(key, data) {
749
+ return hmac(sha256, key, data);
750
+ }
751
+ async aesEncrypt(key, iv, plaintext) {
752
+ const cryptoKey = await crypto.subtle.importKey(
753
+ "raw",
754
+ key,
755
+ { name: "AES-CBC" },
756
+ false,
757
+ ["encrypt"]
758
+ );
759
+ const encrypted = await crypto.subtle.encrypt(
760
+ { name: "AES-CBC", iv },
761
+ cryptoKey,
762
+ plaintext
763
+ );
764
+ return new Uint8Array(encrypted);
765
+ }
766
+ async aesDecrypt(key, iv, ciphertext) {
767
+ const cryptoKey = await crypto.subtle.importKey(
768
+ "raw",
769
+ key,
770
+ { name: "AES-CBC" },
771
+ false,
772
+ ["decrypt"]
773
+ );
774
+ const decrypted = await crypto.subtle.decrypt(
775
+ { name: "AES-CBC", iv },
776
+ cryptoKey,
777
+ ciphertext
778
+ );
779
+ return new Uint8Array(decrypted);
780
+ }
781
+ };
782
+ }
783
+ });
784
+
78
785
  // src/platform/browser.ts
79
786
  var browser_exports = {};
80
787
  __export(browser_exports, {
81
- BrowserPlatformAdapter: () => BrowserPlatformAdapter,
82
- browserPlatformAdapter: () => browserPlatformAdapter
788
+ BrowserPlatformAdapter: () => BrowserPlatformAdapter
83
789
  });
84
- import * as openpgp from "openpgp";
85
- var BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
86
- var init_browser = __esm({
790
+ import * as secp256k12 from "@noble/secp256k1";
791
+ var getOpenPGP, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter;
792
+ var init_browser2 = __esm({
87
793
  "src/platform/browser.ts"() {
88
794
  "use strict";
89
- init_crypto_utils();
90
795
  init_pgp_utils();
91
796
  init_error_utils();
797
+ init_lazy_import();
798
+ init_WalletKeyEncryptionService();
799
+ init_crypto_utils();
800
+ init_utils();
801
+ init_browser();
802
+ getOpenPGP = lazyImport(() => import("openpgp"));
92
803
  BrowserCryptoAdapter = class {
804
+ eciesProvider = new BrowserECIESUint8Provider();
805
+ walletKeyEncryptionService = new WalletKeyEncryptionService({
806
+ eciesProvider: this.eciesProvider
807
+ });
93
808
  async encryptWithPublicKey(data, publicKeyHex) {
94
809
  try {
95
- const eccrypto2 = await import("eccrypto-js");
96
- const publicKeyBuffer = Buffer.from(publicKeyHex, "hex");
97
- const encrypted = await eccrypto2.encrypt(
98
- publicKeyBuffer,
99
- Buffer.from(data, "utf8")
810
+ const publicKeyBytes = hexToBytes2(publicKeyHex);
811
+ const encrypted = await this.eciesProvider.encrypt(
812
+ publicKeyBytes,
813
+ stringToBytes2(data)
100
814
  );
101
- const result = Buffer.concat([
815
+ const result = concatBytes2(
102
816
  encrypted.iv,
103
817
  encrypted.ephemPublicKey,
104
818
  encrypted.ciphertext,
105
819
  encrypted.mac
106
- ]);
107
- return result.toString("hex");
820
+ );
821
+ return bytesToHex2(result);
108
822
  } catch (error) {
109
- throw new Error(`Encryption failed: ${error}`);
823
+ throw wrapCryptoError("encryptWithPublicKey", error);
110
824
  }
111
825
  }
112
826
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
113
827
  try {
114
- const eccrypto2 = await import("eccrypto-js");
115
- const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
116
- const encryptedBuffer = Buffer.from(encryptedData, "hex");
117
- const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
118
- const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
119
- const decryptedBuffer = await eccrypto2.decrypt(
120
- privateKeyBuffer,
121
- encryptedObj
828
+ const encryptedBytes = hexToBytes2(encryptedData);
829
+ const privateKeyBytes = hexToBytes2(privateKeyHex);
830
+ const encrypted = parseEncryptedDataBuffer(encryptedBytes);
831
+ const decrypted = await this.eciesProvider.decrypt(
832
+ privateKeyBytes,
833
+ encrypted
122
834
  );
123
- return decryptedBuffer.toString("utf8");
835
+ return bytesToString2(decrypted);
124
836
  } catch (error) {
125
- throw new Error(`Decryption failed: ${error}`);
837
+ throw wrapCryptoError("decryptWithPrivateKey", error);
126
838
  }
127
839
  }
128
- async generateKeyPair() {
840
+ async encryptWithWalletPublicKey(data, publicKey) {
129
841
  try {
130
- const eccrypto2 = await import("eccrypto-js");
131
- const privateKeyBytes = new Uint8Array(32);
132
- crypto.getRandomValues(privateKeyBytes);
133
- const privateKey = Buffer.from(privateKeyBytes);
134
- const publicKey = eccrypto2.getPublicCompressed(privateKey);
135
- return {
136
- privateKey: privateKey.toString("hex"),
137
- publicKey: publicKey.toString("hex")
138
- };
842
+ return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
843
+ data,
844
+ publicKey
845
+ );
139
846
  } catch (error) {
140
- throw wrapCryptoError("key generation", error);
847
+ throw wrapCryptoError("encryptWithWalletPublicKey", error);
141
848
  }
142
849
  }
143
- async encryptWithWalletPublicKey(data, publicKey) {
850
+ async decryptWithWalletPrivateKey(encryptedData, privateKey) {
144
851
  try {
145
- const eccrypto2 = await import("eccrypto-js");
146
- const uncompressedKey = processWalletPublicKey(publicKey);
147
- const encryptedBuffer = await eccrypto2.encrypt(
148
- uncompressedKey,
149
- Buffer.from(data)
852
+ return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
853
+ encryptedData,
854
+ privateKey
150
855
  );
151
- const result = Buffer.concat([
152
- encryptedBuffer.iv,
153
- encryptedBuffer.ephemPublicKey,
154
- encryptedBuffer.ciphertext,
155
- encryptedBuffer.mac
156
- ]);
157
- return result.toString("hex");
158
856
  } catch (error) {
159
- throw wrapCryptoError("encrypt with wallet public key", error);
857
+ throw wrapCryptoError("decryptWithWalletPrivateKey", error);
160
858
  }
161
859
  }
162
- async decryptWithWalletPrivateKey(encryptedData, privateKey) {
860
+ async generateKeyPair() {
163
861
  try {
164
- const eccrypto2 = await import("eccrypto-js");
165
- const privateKeyBuffer = processWalletPrivateKey(privateKey);
166
- const encryptedBuffer = Buffer.from(encryptedData, "hex");
167
- const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
168
- const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
169
- const decryptedBuffer = await eccrypto2.decrypt(
170
- privateKeyBuffer,
171
- encryptedObj
172
- );
173
- return decryptedBuffer.toString("utf8");
862
+ const privateKeyBytes = secp256k12.utils.randomPrivateKey();
863
+ const publicKeyBytes = secp256k12.getPublicKey(privateKeyBytes, true);
864
+ return {
865
+ privateKey: bytesToHex2(privateKeyBytes),
866
+ publicKey: bytesToHex2(publicKeyBytes)
867
+ };
174
868
  } catch (error) {
175
- throw wrapCryptoError("decrypt with wallet private key", error);
869
+ throw wrapCryptoError("generateKeyPair", error);
176
870
  }
177
871
  }
178
872
  async encryptWithPassword(data, password) {
179
873
  try {
180
- const openpgp3 = await import("openpgp");
181
- const message = await openpgp3.createMessage({
182
- binary: data
183
- });
184
- const encrypted = await openpgp3.encrypt({
874
+ const openpgp = await getOpenPGP();
875
+ const message = await openpgp.createMessage({ binary: data });
876
+ const encrypted = await openpgp.encrypt({
185
877
  message,
186
878
  passwords: [password],
187
879
  format: "binary"
188
880
  });
189
- const response = new Response(encrypted);
190
- const arrayBuffer = await response.arrayBuffer();
191
- return new Uint8Array(arrayBuffer);
881
+ return new Uint8Array(encrypted);
192
882
  } catch (error) {
193
- throw new Error(`Failed to encrypt with password: ${error}`);
883
+ throw wrapCryptoError("encryptWithPassword", error);
194
884
  }
195
885
  }
196
886
  async decryptWithPassword(encryptedData, password) {
197
887
  try {
198
- const openpgp3 = await import("openpgp");
199
- const message = await openpgp3.readMessage({
888
+ const openpgp = await getOpenPGP();
889
+ const message = await openpgp.readMessage({
200
890
  binaryMessage: encryptedData
201
891
  });
202
- const { data: decrypted } = await openpgp3.decrypt({
892
+ const { data } = await openpgp.decrypt({
203
893
  message,
204
894
  passwords: [password],
205
895
  format: "binary"
206
896
  });
207
- return new Uint8Array(decrypted);
897
+ return new Uint8Array(data);
208
898
  } catch (error) {
209
- throw new Error(`Failed to decrypt with password: ${error}`);
899
+ throw wrapCryptoError("decryptWithPassword", error);
210
900
  }
211
901
  }
212
902
  };
213
903
  BrowserPGPAdapter = class {
214
904
  async encrypt(data, publicKeyArmored) {
215
905
  try {
906
+ const openpgp = await getOpenPGP();
216
907
  const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
217
908
  const encrypted = await openpgp.encrypt({
218
909
  message: await openpgp.createMessage({ text: data }),
@@ -228,6 +919,7 @@ var init_browser = __esm({
228
919
  }
229
920
  async decrypt(encryptedData, privateKeyArmored) {
230
921
  try {
922
+ const openpgp = await getOpenPGP();
231
923
  const privateKey = await openpgp.readPrivateKey({
232
924
  armoredKey: privateKeyArmored
233
925
  });
@@ -245,6 +937,7 @@ var init_browser = __esm({
245
937
  }
246
938
  async generateKeyPair(options) {
247
939
  try {
940
+ const openpgp = await getOpenPGP();
248
941
  const keyGenParams = getPGPKeyGenParams(options);
249
942
  const { privateKey, publicKey } = await openpgp.generateKey(keyGenParams);
250
943
  return { publicKey, privateKey };
@@ -255,9 +948,6 @@ var init_browser = __esm({
255
948
  };
256
949
  BrowserHttpAdapter = class {
257
950
  async fetch(url, options) {
258
- if (typeof fetch === "undefined") {
259
- throw new Error("Fetch API not available in this browser environment");
260
- }
261
951
  return fetch(url, options);
262
952
  }
263
953
  };
@@ -275,17 +965,19 @@ var init_browser = __esm({
275
965
  }
276
966
  set(key, value) {
277
967
  try {
278
- if (typeof sessionStorage !== "undefined") {
279
- sessionStorage.setItem(this.prefix + key, value);
968
+ if (typeof sessionStorage === "undefined") {
969
+ return;
280
970
  }
971
+ sessionStorage.setItem(this.prefix + key, value);
281
972
  } catch {
282
973
  }
283
974
  }
284
975
  delete(key) {
285
976
  try {
286
- if (typeof sessionStorage !== "undefined") {
287
- sessionStorage.removeItem(this.prefix + key);
977
+ if (typeof sessionStorage === "undefined") {
978
+ return;
288
979
  }
980
+ sessionStorage.removeItem(this.prefix + key);
289
981
  } catch {
290
982
  }
291
983
  }
@@ -294,42 +986,34 @@ var init_browser = __esm({
294
986
  if (typeof sessionStorage === "undefined") {
295
987
  return;
296
988
  }
297
- const keys = Object.keys(sessionStorage);
298
- for (const key of keys) {
299
- if (key.startsWith(this.prefix)) {
300
- sessionStorage.removeItem(key);
989
+ const keysToRemove = [];
990
+ for (let i = 0; i < sessionStorage.length; i++) {
991
+ const key = sessionStorage.key(i);
992
+ if (key?.startsWith(this.prefix)) {
993
+ keysToRemove.push(key);
301
994
  }
302
995
  }
996
+ keysToRemove.forEach((key) => sessionStorage.removeItem(key));
303
997
  } catch {
304
998
  }
305
999
  }
306
1000
  };
307
1001
  BrowserPlatformAdapter = class {
308
- crypto;
309
- pgp;
310
- http;
311
- cache;
1002
+ crypto = new BrowserCryptoAdapter();
1003
+ pgp = new BrowserPGPAdapter();
1004
+ http = new BrowserHttpAdapter();
1005
+ cache = new BrowserCacheAdapter();
312
1006
  platform = "browser";
313
- constructor() {
314
- this.crypto = new BrowserCryptoAdapter();
315
- this.pgp = new BrowserPGPAdapter();
316
- this.http = new BrowserHttpAdapter();
317
- this.cache = new BrowserCacheAdapter();
318
- }
319
1007
  };
320
- browserPlatformAdapter = new BrowserPlatformAdapter();
321
1008
  }
322
1009
  });
323
1010
 
324
1011
  // src/platform.ts
325
- init_browser();
1012
+ init_browser2();
326
1013
 
327
1014
  // src/platform/node.ts
328
- init_crypto_utils();
329
1015
  init_pgp_utils();
330
1016
  init_error_utils();
331
- import { randomBytes } from "crypto";
332
- import * as openpgp2 from "openpgp";
333
1017
 
334
1018
  // src/platform/shared/stream-utils.ts
335
1019
  async function streamToUint8Array(stream) {
@@ -355,29 +1039,130 @@ async function streamToUint8Array(stream) {
355
1039
  }
356
1040
 
357
1041
  // src/platform/node.ts
358
- var eccrypto = null;
359
- async function getEccrypto() {
360
- if (!eccrypto) {
1042
+ init_lazy_import();
1043
+ init_WalletKeyEncryptionService();
1044
+ init_crypto_utils();
1045
+
1046
+ // src/crypto/ecies/node.ts
1047
+ init_base();
1048
+ import {
1049
+ randomBytes,
1050
+ createHash,
1051
+ createHmac,
1052
+ createCipheriv,
1053
+ createDecipheriv
1054
+ } from "crypto";
1055
+ var secp256k13;
1056
+ try {
1057
+ secp256k13 = __require("secp256k1");
1058
+ } catch {
1059
+ throw new Error(
1060
+ "Native secp256k1 module not found. Please install with: npm install secp256k1\nThis is required for optimal performance in Node.js environments."
1061
+ );
1062
+ }
1063
+ var NodeECIESUint8Provider = class extends BaseECIESUint8 {
1064
+ // Identity hash function for ECDH - returns raw X coordinate
1065
+ // CRITICAL: Must handle (x, y, output) signature correctly
1066
+ identityHashFn = (x, y, output) => {
1067
+ if (output && output.length >= 32) {
1068
+ output.set(x);
1069
+ return output;
1070
+ }
1071
+ return x;
1072
+ };
1073
+ generateRandomBytes(length) {
1074
+ return new Uint8Array(randomBytes(length));
1075
+ }
1076
+ verifyPrivateKey(privateKey) {
1077
+ return secp256k13.privateKeyVerify(Buffer.from(privateKey)) === true;
1078
+ }
1079
+ createPublicKey(privateKey, compressed) {
361
1080
  try {
362
- const eccryptoLib = await import("eccrypto");
363
- eccrypto = {
364
- encrypt: eccryptoLib.encrypt,
365
- decrypt: eccryptoLib.decrypt,
366
- getPublicCompressed: eccryptoLib.getPublicCompressed
367
- };
1081
+ return new Uint8Array(
1082
+ secp256k13.publicKeyCreate(Buffer.from(privateKey), compressed)
1083
+ );
1084
+ } catch {
1085
+ return null;
1086
+ }
1087
+ }
1088
+ validatePublicKey(publicKey) {
1089
+ return secp256k13.publicKeyVerify(Buffer.from(publicKey)) === true;
1090
+ }
1091
+ decompressPublicKey(publicKey) {
1092
+ try {
1093
+ return new Uint8Array(
1094
+ secp256k13.publicKeyConvert(Buffer.from(publicKey), false)
1095
+ );
1096
+ } catch {
1097
+ return null;
1098
+ }
1099
+ }
1100
+ performECDH(publicKey, privateKey) {
1101
+ try {
1102
+ const output = Buffer.alloc(32);
1103
+ secp256k13.ecdh(
1104
+ Buffer.from(publicKey),
1105
+ Buffer.from(privateKey),
1106
+ { hashfn: this.identityHashFn },
1107
+ output
1108
+ );
1109
+ return new Uint8Array(output);
368
1110
  } catch (error) {
369
- throw new Error(`Failed to load eccrypto library: ${error}`);
1111
+ throw new Error(
1112
+ `ECDH failed: ${error instanceof Error ? error.message : "Unknown error"}`
1113
+ );
370
1114
  }
371
1115
  }
372
- return eccrypto;
373
- }
1116
+ sha512(data) {
1117
+ return new Uint8Array(
1118
+ createHash("sha512").update(Buffer.from(data)).digest()
1119
+ );
1120
+ }
1121
+ hmacSha256(key, data) {
1122
+ return new Uint8Array(
1123
+ createHmac("sha256", Buffer.from(key)).update(Buffer.from(data)).digest()
1124
+ );
1125
+ }
1126
+ async aesEncrypt(key, iv, plaintext) {
1127
+ const cipher = createCipheriv(
1128
+ "aes-256-cbc",
1129
+ Buffer.from(key),
1130
+ Buffer.from(iv)
1131
+ );
1132
+ const encrypted = Buffer.concat([
1133
+ cipher.update(Buffer.from(plaintext)),
1134
+ cipher.final()
1135
+ ]);
1136
+ return new Uint8Array(encrypted);
1137
+ }
1138
+ async aesDecrypt(key, iv, ciphertext) {
1139
+ const decipher = createDecipheriv(
1140
+ "aes-256-cbc",
1141
+ Buffer.from(key),
1142
+ Buffer.from(iv)
1143
+ );
1144
+ const decrypted = Buffer.concat([
1145
+ decipher.update(Buffer.from(ciphertext)),
1146
+ decipher.final()
1147
+ ]);
1148
+ return new Uint8Array(decrypted);
1149
+ }
1150
+ // No Buffer compatibility methods - Uint8Array only public API
1151
+ };
1152
+
1153
+ // src/platform/node.ts
1154
+ init_interface();
1155
+ var getOpenPGP2 = lazyImport(() => import("openpgp"));
374
1156
  var NodeCryptoAdapter = class {
1157
+ eciesProvider = new NodeECIESUint8Provider();
1158
+ walletKeyEncryptionService = new WalletKeyEncryptionService({
1159
+ eciesProvider: this.eciesProvider
1160
+ });
375
1161
  async encryptWithPublicKey(data, publicKeyHex) {
376
1162
  try {
377
- const eccryptoLib = await getEccrypto();
378
1163
  const publicKey = Buffer.from(publicKeyHex, "hex");
379
1164
  const message = Buffer.from(data, "utf8");
380
- const encrypted = await eccryptoLib.encrypt(publicKey, message);
1165
+ const encrypted = await this.eciesProvider.encrypt(publicKey, message);
381
1166
  const result = Buffer.concat([
382
1167
  encrypted.iv,
383
1168
  encrypted.ephemPublicKey,
@@ -386,30 +1171,54 @@ var NodeCryptoAdapter = class {
386
1171
  ]);
387
1172
  return result.toString("hex");
388
1173
  } catch (error) {
389
- throw new Error(`Encryption failed: ${error}`);
1174
+ if (error instanceof ECIESError) {
1175
+ throw error;
1176
+ }
1177
+ throw new ECIESError(
1178
+ `Encryption failed: ${error instanceof Error ? error.message : String(error)}`,
1179
+ "ENCRYPTION_FAILED",
1180
+ error instanceof Error ? error : void 0
1181
+ );
390
1182
  }
391
1183
  }
392
1184
  async decryptWithPrivateKey(encryptedData, privateKeyHex) {
393
1185
  try {
394
- const eccryptoLib = await getEccrypto();
395
1186
  const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
396
1187
  const encryptedBuffer = Buffer.from(encryptedData, "hex");
397
1188
  const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
398
- const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
399
- const decrypted = await eccryptoLib.decrypt(
1189
+ const encryptedObj = {
1190
+ iv,
1191
+ ephemPublicKey,
1192
+ ciphertext,
1193
+ mac
1194
+ };
1195
+ const decrypted = await this.eciesProvider.decrypt(
400
1196
  privateKeyBuffer,
401
1197
  encryptedObj
402
1198
  );
403
- return decrypted.toString("utf8");
1199
+ return new TextDecoder().decode(decrypted);
404
1200
  } catch (error) {
405
- throw new Error(`Decryption failed: ${error}`);
1201
+ if (error instanceof ECIESError) {
1202
+ throw error;
1203
+ }
1204
+ throw new ECIESError(
1205
+ `Decryption failed: ${error instanceof Error ? error.message : String(error)}`,
1206
+ "DECRYPTION_FAILED",
1207
+ error instanceof Error ? error : void 0
1208
+ );
406
1209
  }
407
1210
  }
408
1211
  async generateKeyPair() {
409
1212
  try {
410
- const eccryptoLib = await getEccrypto();
411
- const privateKey = randomBytes(32);
412
- const publicKey = eccryptoLib.getPublicCompressed(privateKey);
1213
+ const { randomBytes: randomBytes2 } = await import("crypto");
1214
+ const secp256k14 = await import("secp256k1");
1215
+ let privateKey;
1216
+ do {
1217
+ privateKey = randomBytes2(32);
1218
+ } while (!secp256k14.privateKeyVerify(privateKey));
1219
+ const publicKey = Buffer.from(
1220
+ secp256k14.publicKeyCreate(privateKey, true)
1221
+ );
413
1222
  return {
414
1223
  privateKey: privateKey.toString("hex"),
415
1224
  publicKey: publicKey.toString("hex")
@@ -420,45 +1229,31 @@ var NodeCryptoAdapter = class {
420
1229
  }
421
1230
  async encryptWithWalletPublicKey(data, publicKey) {
422
1231
  try {
423
- const eccryptoLib = await getEccrypto();
424
- const uncompressedKey = processWalletPublicKey(publicKey);
425
- const encrypted = await eccryptoLib.encrypt(
426
- uncompressedKey,
427
- Buffer.from(data)
1232
+ return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(
1233
+ data,
1234
+ publicKey
428
1235
  );
429
- const result = Buffer.concat([
430
- encrypted.iv,
431
- encrypted.ephemPublicKey,
432
- encrypted.ciphertext,
433
- encrypted.mac
434
- ]);
435
- return result.toString("hex");
436
1236
  } catch (error) {
437
1237
  throw wrapCryptoError("encrypt with wallet public key", error);
438
1238
  }
439
1239
  }
440
1240
  async decryptWithWalletPrivateKey(encryptedData, privateKey) {
441
1241
  try {
442
- const eccryptoLib = await getEccrypto();
443
- const privateKeyBuffer = processWalletPrivateKey(privateKey);
444
- const encryptedBuffer = Buffer.from(encryptedData, "hex");
445
- const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
446
- const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
447
- const decryptedBuffer = await eccryptoLib.decrypt(
448
- privateKeyBuffer,
449
- encryptedObj
1242
+ return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(
1243
+ encryptedData,
1244
+ privateKey
450
1245
  );
451
- return decryptedBuffer.toString("utf8");
452
1246
  } catch (error) {
453
1247
  throw wrapCryptoError("decrypt with wallet private key", error);
454
1248
  }
455
1249
  }
456
1250
  async encryptWithPassword(data, password) {
457
1251
  try {
458
- const message = await openpgp2.createMessage({
1252
+ const openpgp = await getOpenPGP2();
1253
+ const message = await openpgp.createMessage({
459
1254
  binary: data
460
1255
  });
461
- const encrypted = await openpgp2.encrypt({
1256
+ const encrypted = await openpgp.encrypt({
462
1257
  message,
463
1258
  passwords: [password],
464
1259
  format: "binary"
@@ -478,10 +1273,11 @@ var NodeCryptoAdapter = class {
478
1273
  }
479
1274
  async decryptWithPassword(encryptedData, password) {
480
1275
  try {
481
- const message = await openpgp2.readMessage({
1276
+ const openpgp = await getOpenPGP2();
1277
+ const message = await openpgp.readMessage({
482
1278
  binaryMessage: encryptedData
483
1279
  });
484
- const { data: decrypted } = await openpgp2.decrypt({
1280
+ const { data: decrypted } = await openpgp.decrypt({
485
1281
  message,
486
1282
  passwords: [password],
487
1283
  format: "binary"
@@ -495,12 +1291,13 @@ var NodeCryptoAdapter = class {
495
1291
  var NodePGPAdapter = class {
496
1292
  async encrypt(data, publicKeyArmored) {
497
1293
  try {
498
- const publicKey = await openpgp2.readKey({ armoredKey: publicKeyArmored });
499
- const encrypted = await openpgp2.encrypt({
500
- message: await openpgp2.createMessage({ text: data }),
1294
+ const openpgp = await getOpenPGP2();
1295
+ const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
1296
+ const encrypted = await openpgp.encrypt({
1297
+ message: await openpgp.createMessage({ text: data }),
501
1298
  encryptionKeys: publicKey,
502
1299
  config: {
503
- preferredCompressionAlgorithm: openpgp2.enums.compression.zlib
1300
+ preferredCompressionAlgorithm: openpgp.enums.compression.zlib
504
1301
  }
505
1302
  });
506
1303
  return encrypted;
@@ -510,13 +1307,14 @@ var NodePGPAdapter = class {
510
1307
  }
511
1308
  async decrypt(encryptedData, privateKeyArmored) {
512
1309
  try {
513
- const privateKey = await openpgp2.readPrivateKey({
1310
+ const openpgp = await getOpenPGP2();
1311
+ const privateKey = await openpgp.readPrivateKey({
514
1312
  armoredKey: privateKeyArmored
515
1313
  });
516
- const message = await openpgp2.readMessage({
1314
+ const message = await openpgp.readMessage({
517
1315
  armoredMessage: encryptedData
518
1316
  });
519
- const { data: decrypted } = await openpgp2.decrypt({
1317
+ const { data: decrypted } = await openpgp.decrypt({
520
1318
  message,
521
1319
  decryptionKeys: privateKey
522
1320
  });
@@ -527,8 +1325,9 @@ var NodePGPAdapter = class {
527
1325
  }
528
1326
  async generateKeyPair(options) {
529
1327
  try {
1328
+ const openpgp = await getOpenPGP2();
530
1329
  const keyGenParams = getPGPKeyGenParams(options);
531
- const { privateKey, publicKey } = await openpgp2.generateKey(keyGenParams);
1330
+ const { privateKey, publicKey } = await openpgp.generateKey(keyGenParams);
532
1331
  return { publicKey, privateKey };
533
1332
  } catch (error) {
534
1333
  throw wrapCryptoError("PGP key generation", error);
@@ -609,7 +1408,7 @@ async function createPlatformAdapter() {
609
1408
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
610
1409
  return new NodePlatformAdapter2();
611
1410
  } else {
612
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
1411
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
613
1412
  return new BrowserPlatformAdapter2();
614
1413
  }
615
1414
  } catch (error) {
@@ -630,7 +1429,7 @@ async function createPlatformAdapterFor(platformType) {
630
1429
  const { NodePlatformAdapter: NodePlatformAdapter2 } = await import(moduleName);
631
1430
  return new NodePlatformAdapter2();
632
1431
  } else {
633
- const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
1432
+ const { BrowserPlatformAdapter: BrowserPlatformAdapter2 } = await Promise.resolve().then(() => (init_browser2(), browser_exports));
634
1433
  return new BrowserPlatformAdapter2();
635
1434
  }
636
1435
  } catch (error) {
@@ -657,7 +1456,7 @@ function getPlatformCapabilities() {
657
1456
  }
658
1457
 
659
1458
  // src/platform/browser-safe.ts
660
- init_browser();
1459
+ init_browser2();
661
1460
  async function createNodePlatformAdapter() {
662
1461
  if (typeof window !== "undefined") {
663
1462
  throw new Error(