@opendatalabs/vana-sdk 0.1.0-alpha.82bbb39 → 0.1.0-alpha.899ca9d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -0
- package/dist/browser-DY8XDblx.d.ts +241 -0
- package/dist/browser.d.ts +1 -0
- package/dist/browser.js +309 -0
- package/dist/browser.js.map +1 -0
- package/dist/chains.browser.cjs +2 -2
- package/dist/chains.browser.cjs.map +1 -1
- package/dist/chains.browser.js +2 -2
- package/dist/chains.browser.js.map +1 -1
- package/dist/chains.cjs +2 -2
- package/dist/chains.cjs.map +1 -1
- package/dist/chains.js +2 -2
- package/dist/chains.js.map +1 -1
- package/dist/chains.node.cjs +2 -2
- package/dist/chains.node.cjs.map +1 -1
- package/dist/chains.node.js +2 -2
- package/dist/chains.node.js.map +1 -1
- package/dist/index.browser.d.ts +1756 -1479
- package/dist/index.browser.js +37686 -35103
- package/dist/index.browser.js.map +1 -1
- package/dist/index.node.cjs +38174 -35582
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.d.cts +1790 -1486
- package/dist/index.node.d.ts +1790 -1486
- package/dist/index.node.js +38402 -35813
- package/dist/index.node.js.map +1 -1
- package/dist/node-D9-F9uEP.d.cts +238 -0
- package/dist/node-D9-F9uEP.d.ts +238 -0
- package/dist/node.cjs +348 -0
- package/dist/node.cjs.map +1 -0
- package/dist/node.d.cts +1 -0
- package/dist/node.d.ts +1 -0
- package/dist/node.js +311 -0
- package/dist/node.js.map +1 -0
- package/dist/platform.browser.d.ts +3 -236
- package/dist/platform.browser.js +31 -8
- package/dist/platform.browser.js.map +1 -1
- package/dist/platform.cjs +72 -62
- package/dist/platform.cjs.map +1 -1
- package/dist/platform.d.cts +2 -1
- package/dist/platform.d.ts +2 -1
- package/dist/platform.js +72 -62
- package/dist/platform.js.map +1 -1
- package/dist/platform.node.cjs +72 -62
- package/dist/platform.node.cjs.map +1 -1
- package/dist/platform.node.d.cts +7 -236
- package/dist/platform.node.d.ts +7 -236
- package/dist/platform.node.js +72 -62
- package/dist/platform.node.js.map +1 -1
- package/package.json +17 -12
package/dist/platform.browser.js
CHANGED
|
@@ -73,15 +73,35 @@ var init_error_utils = __esm({
|
|
|
73
73
|
}
|
|
74
74
|
});
|
|
75
75
|
|
|
76
|
+
// src/utils/lazy-import.ts
|
|
77
|
+
function lazyImport(importFn) {
|
|
78
|
+
let cached = null;
|
|
79
|
+
return () => {
|
|
80
|
+
if (!cached) {
|
|
81
|
+
cached = importFn().catch((err) => {
|
|
82
|
+
cached = null;
|
|
83
|
+
throw new Error("Failed to load module", { cause: err });
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
return cached;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
var init_lazy_import = __esm({
|
|
90
|
+
"src/utils/lazy-import.ts"() {
|
|
91
|
+
"use strict";
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
|
|
76
95
|
// src/platform/browser.ts
|
|
77
|
-
|
|
78
|
-
var BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
|
|
96
|
+
var getOpenPGP, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
|
|
79
97
|
var init_browser = __esm({
|
|
80
98
|
"src/platform/browser.ts"() {
|
|
81
99
|
"use strict";
|
|
82
100
|
init_crypto_utils();
|
|
83
101
|
init_pgp_utils();
|
|
84
102
|
init_error_utils();
|
|
103
|
+
init_lazy_import();
|
|
104
|
+
getOpenPGP = lazyImport(() => import("openpgp"));
|
|
85
105
|
BrowserCryptoAdapter = class {
|
|
86
106
|
async encryptWithPublicKey(data, publicKeyHex) {
|
|
87
107
|
try {
|
|
@@ -170,11 +190,11 @@ var init_browser = __esm({
|
|
|
170
190
|
}
|
|
171
191
|
async encryptWithPassword(data, password) {
|
|
172
192
|
try {
|
|
173
|
-
const
|
|
174
|
-
const message = await
|
|
193
|
+
const openpgp = await getOpenPGP();
|
|
194
|
+
const message = await openpgp.createMessage({
|
|
175
195
|
binary: data
|
|
176
196
|
});
|
|
177
|
-
const encrypted = await
|
|
197
|
+
const encrypted = await openpgp.encrypt({
|
|
178
198
|
message,
|
|
179
199
|
passwords: [password],
|
|
180
200
|
format: "binary"
|
|
@@ -188,11 +208,11 @@ var init_browser = __esm({
|
|
|
188
208
|
}
|
|
189
209
|
async decryptWithPassword(encryptedData, password) {
|
|
190
210
|
try {
|
|
191
|
-
const
|
|
192
|
-
const message = await
|
|
211
|
+
const openpgp = await getOpenPGP();
|
|
212
|
+
const message = await openpgp.readMessage({
|
|
193
213
|
binaryMessage: encryptedData
|
|
194
214
|
});
|
|
195
|
-
const { data: decrypted } = await
|
|
215
|
+
const { data: decrypted } = await openpgp.decrypt({
|
|
196
216
|
message,
|
|
197
217
|
passwords: [password],
|
|
198
218
|
format: "binary"
|
|
@@ -206,6 +226,7 @@ var init_browser = __esm({
|
|
|
206
226
|
BrowserPGPAdapter = class {
|
|
207
227
|
async encrypt(data, publicKeyArmored) {
|
|
208
228
|
try {
|
|
229
|
+
const openpgp = await getOpenPGP();
|
|
209
230
|
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
|
|
210
231
|
const encrypted = await openpgp.encrypt({
|
|
211
232
|
message: await openpgp.createMessage({ text: data }),
|
|
@@ -221,6 +242,7 @@ var init_browser = __esm({
|
|
|
221
242
|
}
|
|
222
243
|
async decrypt(encryptedData, privateKeyArmored) {
|
|
223
244
|
try {
|
|
245
|
+
const openpgp = await getOpenPGP();
|
|
224
246
|
const privateKey = await openpgp.readPrivateKey({
|
|
225
247
|
armoredKey: privateKeyArmored
|
|
226
248
|
});
|
|
@@ -238,6 +260,7 @@ var init_browser = __esm({
|
|
|
238
260
|
}
|
|
239
261
|
async generateKeyPair(options) {
|
|
240
262
|
try {
|
|
263
|
+
const openpgp = await getOpenPGP();
|
|
241
264
|
const keyGenParams = getPGPKeyGenParams(options);
|
|
242
265
|
const { privateKey, publicKey } = await openpgp.generateKey(keyGenParams);
|
|
243
266
|
return { publicKey, privateKey };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/platform/shared/crypto-utils.ts","../src/platform/shared/pgp-utils.ts","../src/platform/shared/error-utils.ts","../src/platform/browser.ts","../src/platform.browser.ts","../src/platform/browser-only.ts","../src/platform/utils.ts"],"sourcesContent":["/**\n * Shared crypto utilities for platform adapters\n *\n * IMPORTANT: This module contains NO IMPORTS to avoid affecting bundle loading.\n * All functions are pure utilities that can be safely shared across platforms.\n */\n\n/**\n * Process wallet public key for encryption operations\n * Removes 0x prefix and ensures uncompressed format (65 bytes with 0x04 prefix)\n *\n * @param publicKey The public key (with or without 0x prefix)\n * @returns Buffer containing uncompressed public key\n */\nexport function processWalletPublicKey(publicKey: string): Buffer {\n const publicKeyHex = publicKey.startsWith(\"0x\")\n ? publicKey.slice(2)\n : publicKey;\n const publicKeyBytes = Buffer.from(publicKeyHex, \"hex\");\n\n // Ensure public key is in uncompressed format (65 bytes with 0x04 prefix)\n // If it's 64 bytes, add the 0x04 prefix; if already 65 bytes, use as-is\n return publicKeyBytes.length === 64\n ? Buffer.concat([Buffer.from([4]), publicKeyBytes])\n : publicKeyBytes;\n}\n\n/**\n * Process wallet private key for decryption operations\n * Removes 0x prefix and converts to Buffer\n *\n * @param privateKey The private key (with or without 0x prefix)\n * @returns Buffer containing private key\n */\nexport function processWalletPrivateKey(privateKey: string): Buffer {\n const privateKeyHex = privateKey.startsWith(\"0x\")\n ? privateKey.slice(2)\n : privateKey;\n return Buffer.from(privateKeyHex, \"hex\");\n}\n\n/**\n * Parse encrypted data buffer into components\n * Extracts IV, ephemeral public key, ciphertext, and MAC from a concatenated buffer\n *\n * @param encryptedBuffer The buffer containing encrypted data\n * @returns Object with parsed components\n */\nexport function parseEncryptedDataBuffer(encryptedBuffer: Buffer) {\n return {\n iv: encryptedBuffer.slice(0, 16),\n ephemPublicKey: encryptedBuffer.slice(16, 81), // 65 bytes for uncompressed public key\n ciphertext: encryptedBuffer.slice(81, -32),\n mac: encryptedBuffer.slice(-32),\n };\n}\n\n/**\n * Convert hex string to Uint8Array\n *\n * @param hex The hex string to convert\n * @returns Uint8Array representation\n */\nexport function hexToUint8Array(hex: string): Uint8Array {\n const result = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n result[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n return result;\n}\n\n/**\n * Convert Uint8Array to hex string\n *\n * @param array The Uint8Array to convert\n * @returns Hex string representation\n */\nexport function uint8ArrayToHex(array: Uint8Array): string {\n return Array.from(array, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\n/**\n * Cross-platform base64 encoding\n * Works in both Node.js and browser environments\n *\n * @param str The string to encode\n * @returns Base64 encoded string\n */\nexport function toBase64(str: string): string {\n if (typeof Buffer !== \"undefined\") {\n // Node.js environment\n return Buffer.from(str, \"utf8\").toString(\"base64\");\n } else if (typeof btoa !== \"undefined\") {\n // Browser environment\n return btoa(str);\n } else {\n // Fallback manual implementation\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let result = \"\";\n let i = 0;\n while (i < str.length) {\n const a = str.charCodeAt(i++);\n const b = i < str.length ? str.charCodeAt(i++) : 0;\n const c = i < str.length ? str.charCodeAt(i++) : 0;\n\n const bitmap = (a << 16) | (b << 8) | c;\n\n result += chars.charAt((bitmap >> 18) & 63);\n result += chars.charAt((bitmap >> 12) & 63);\n result += i - 2 < str.length ? chars.charAt((bitmap >> 6) & 63) : \"=\";\n result += i - 1 < str.length ? chars.charAt(bitmap & 63) : \"=\";\n }\n return result;\n }\n}\n\n/**\n * Cross-platform base64 decoding\n * Works in both Node.js and browser environments\n *\n * @param str The base64 string to decode\n * @returns Decoded string\n */\nexport function fromBase64(str: string): string {\n if (typeof Buffer !== \"undefined\") {\n // Node.js environment\n return Buffer.from(str, \"base64\").toString(\"utf8\");\n } else if (typeof atob !== \"undefined\") {\n // Browser environment\n return atob(str);\n } else {\n // Fallback manual implementation\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let result = \"\";\n let i = 0;\n\n // Remove any characters not in the base64 character set\n str = str.replace(/[^A-Za-z0-9+/]/g, \"\");\n\n while (i < str.length) {\n const encoded1 = chars.indexOf(str.charAt(i++));\n const encoded2 = chars.indexOf(str.charAt(i++));\n const encoded3 = chars.indexOf(str.charAt(i++));\n const encoded4 = chars.indexOf(str.charAt(i++));\n\n const bitmap =\n (encoded1 << 18) | (encoded2 << 12) | (encoded3 << 6) | encoded4;\n\n result += String.fromCharCode((bitmap >> 16) & 255);\n if (encoded3 !== 64) result += String.fromCharCode((bitmap >> 8) & 255);\n if (encoded4 !== 64) result += String.fromCharCode(bitmap & 255);\n }\n return result;\n }\n}\n","/**\n * Shared PGP utilities for platform adapters\n *\n * IMPORTANT: This module contains NO IMPORTS to avoid affecting bundle loading.\n * All functions are pure utilities that can be safely shared across platforms.\n */\n\n/**\n * Standard OpenPGP configuration for consistent behavior across platforms\n * Uses enum values instead of importing openpgp to avoid loading issues\n */\nexport const STANDARD_PGP_CONFIG = {\n preferredCompressionAlgorithm: 2, // zlib (openpgp.enums.compression.zlib)\n preferredSymmetricAlgorithm: 7, // aes256 (openpgp.enums.symmetric.aes256)\n} as const;\n\n/**\n * Process PGP key generation options with sensible defaults\n *\n * @param options - Optional key generation parameters\n * @param options.name - The name for the PGP key (defaults to \"Vana User\")\n * @param options.email - The email for the PGP key (defaults to \"user@vana.org\")\n * @param options.passphrase - Optional passphrase to protect the private key\n * @returns Processed options with defaults applied\n */\nexport function processPGPKeyOptions(options?: {\n name?: string;\n email?: string;\n passphrase?: string;\n}) {\n return {\n name: options?.name || \"Vana User\",\n email: options?.email || \"user@vana.org\",\n passphrase: options?.passphrase,\n };\n}\n\n/**\n * Get standard PGP key generation parameters\n * Combines default values with standard configuration\n *\n * @param options - Optional key generation parameters\n * @param options.name - The name for the PGP key (defaults to \"Vana User\")\n * @param options.email - The email for the PGP key (defaults to \"user@vana.org\")\n * @param options.passphrase - Optional passphrase to protect the private key\n * @returns Complete key generation parameters object\n */\nexport function getPGPKeyGenParams(options?: {\n name?: string;\n email?: string;\n passphrase?: string;\n}) {\n const { name, email, passphrase } = processPGPKeyOptions(options);\n\n return {\n type: \"rsa\" as const,\n rsaBits: 2048,\n userIDs: [{ name, email }],\n passphrase,\n config: STANDARD_PGP_CONFIG,\n };\n}\n","/**\n * Shared error utilities for platform adapters\n *\n * IMPORTANT: This module contains NO IMPORTS to avoid affecting bundle loading.\n * All functions are pure utilities that can be safely shared across platforms.\n */\n\n/**\n * Wrap platform-specific errors with consistent messaging\n * Provides consistent error formatting across all crypto operations\n *\n * @param operation The operation that failed (e.g., \"encryption\", \"decryption\")\n * @param error The original error that occurred\n * @returns Wrapped error with consistent format\n */\nexport function wrapCryptoError(operation: string, error: unknown): Error {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return new Error(`${operation} failed: ${message}`);\n}\n\n/**\n * Validate encrypted data structure has required fields\n * Ensures encrypted data objects contain the expected properties\n *\n * @param data The data structure to validate\n * @throws Error if data structure is invalid\n */\nexport function validateEncryptedDataStructure(data: unknown): void {\n if (!data || typeof data !== \"object\") {\n throw new Error(\"Invalid encrypted data format\");\n }\n\n const obj = data as Record<string, unknown>;\n if (!obj.encrypted || !obj.iv || !obj.ephemeralPublicKey) {\n throw new Error(\"Invalid encrypted data format\");\n }\n}\n","/**\n * Browser implementation of the Vana Platform Adapter\n *\n * This implementation uses browser-compatible libraries and configurations\n * to provide crypto, PGP, and HTTP functionality without Node.js dependencies.\n */\n\nimport * as openpgp from \"openpgp\";\nimport {\n VanaPlatformAdapter,\n VanaCryptoAdapter,\n VanaPGPAdapter,\n VanaHttpAdapter,\n VanaCacheAdapter,\n} from \"./interface\";\nimport {\n processWalletPublicKey,\n processWalletPrivateKey,\n parseEncryptedDataBuffer,\n} from \"./shared/crypto-utils\";\nimport { getPGPKeyGenParams } from \"./shared/pgp-utils\";\nimport { wrapCryptoError } from \"./shared/error-utils\";\n\n/**\n * Browser implementation of crypto operations using eccrypto-js\n */\nclass BrowserCryptoAdapter implements VanaCryptoAdapter {\n async encryptWithPublicKey(\n data: string,\n publicKeyHex: string,\n ): Promise<string> {\n try {\n // Import eccrypto-js for secp256k1 encryption\n const eccrypto = await import(\"eccrypto-js\");\n\n // Convert hex public key to Buffer\n const publicKeyBuffer = Buffer.from(publicKeyHex, \"hex\");\n\n // Encrypt data using secp256k1 ECDH\n const encrypted = await eccrypto.encrypt(\n publicKeyBuffer,\n Buffer.from(data, \"utf8\"),\n );\n\n // Concatenate all components and return as hex string for API consistency\n const result = Buffer.concat([\n encrypted.iv,\n encrypted.ephemPublicKey,\n encrypted.ciphertext,\n encrypted.mac,\n ]);\n\n return result.toString(\"hex\");\n } catch (error) {\n throw new Error(`Encryption failed: ${error}`);\n }\n }\n\n async decryptWithPrivateKey(\n encryptedData: string,\n privateKeyHex: string,\n ): Promise<string> {\n try {\n // Import eccrypto-js for secp256k1 decryption\n const eccrypto = await import(\"eccrypto-js\");\n\n // Use shared utilities to process keys and parse data\n const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);\n const encryptedBuffer = Buffer.from(encryptedData, \"hex\");\n const { iv, ephemPublicKey, ciphertext, mac } =\n parseEncryptedDataBuffer(encryptedBuffer);\n\n // Reconstruct the encrypted data structure for eccrypto\n const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };\n\n // Decrypt using secp256k1 ECDH\n const decryptedBuffer = await eccrypto.decrypt(\n privateKeyBuffer,\n encryptedObj,\n );\n\n return decryptedBuffer.toString(\"utf8\");\n } catch (error) {\n throw new Error(`Decryption failed: ${error}`);\n }\n }\n\n async generateKeyPair(): Promise<{ publicKey: string; privateKey: string }> {\n try {\n // Import eccrypto-js for secp256k1 key generation (browser-compatible)\n const eccrypto = await import(\"eccrypto-js\");\n\n // Generate a random 32-byte private key for secp256k1\n const privateKeyBytes = new Uint8Array(32);\n crypto.getRandomValues(privateKeyBytes);\n const privateKey = Buffer.from(privateKeyBytes);\n\n // Generate the corresponding compressed public key\n const publicKey = eccrypto.getPublicCompressed(privateKey);\n\n return {\n privateKey: privateKey.toString(\"hex\"),\n publicKey: publicKey.toString(\"hex\"),\n };\n } catch (error) {\n throw wrapCryptoError(\"key generation\", error);\n }\n }\n\n async encryptWithWalletPublicKey(\n data: string,\n publicKey: string,\n ): Promise<string> {\n try {\n // Import eccrypto for ECDH encryption\n const eccrypto = await import(\"eccrypto-js\");\n\n // Use shared utility to process public key\n const uncompressedKey = processWalletPublicKey(publicKey);\n\n // Encrypt using ECDH with randomly generated parameters\n const encryptedBuffer = await eccrypto.encrypt(\n uncompressedKey,\n Buffer.from(data),\n );\n\n // Concatenate all components and return as hex\n const result = Buffer.concat([\n encryptedBuffer.iv,\n encryptedBuffer.ephemPublicKey,\n encryptedBuffer.ciphertext,\n encryptedBuffer.mac,\n ]);\n\n return result.toString(\"hex\");\n } catch (error) {\n throw wrapCryptoError(\"encrypt with wallet public key\", error);\n }\n }\n\n async decryptWithWalletPrivateKey(\n encryptedData: string,\n privateKey: string,\n ): Promise<string> {\n try {\n // Import eccrypto for ECDH decryption\n const eccrypto = await import(\"eccrypto-js\");\n\n // Use shared utilities to process keys and parse data\n const privateKeyBuffer = processWalletPrivateKey(privateKey);\n const encryptedBuffer = Buffer.from(encryptedData, \"hex\");\n const { iv, ephemPublicKey, ciphertext, mac } =\n parseEncryptedDataBuffer(encryptedBuffer);\n\n // Reconstruct the encrypted data structure for eccrypto\n const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };\n\n // Decrypt using ECDH\n const decryptedBuffer = await eccrypto.decrypt(\n privateKeyBuffer,\n encryptedObj,\n );\n\n return decryptedBuffer.toString(\"utf8\");\n } catch (error) {\n throw wrapCryptoError(\"decrypt with wallet private key\", error);\n }\n }\n\n async encryptWithPassword(\n data: Uint8Array,\n password: string,\n ): Promise<Uint8Array> {\n try {\n // Import openpgp for password-based encryption\n const openpgp = await import(\"openpgp\");\n\n const message = await openpgp.createMessage({\n binary: data,\n });\n\n // Use password-based encryption with wallet signature as password\n // Note: For deterministic encryption, we would need to control the salt\n // This implementation is secure but not deterministic due to OpenPGP's design\n const encrypted = await openpgp.encrypt({\n message,\n passwords: [password],\n format: \"binary\",\n });\n\n // Convert WebStream<Uint8Array> to Uint8Array\n const response = new Response(encrypted as ReadableStream<Uint8Array>);\n const arrayBuffer = await response.arrayBuffer();\n return new Uint8Array(arrayBuffer);\n } catch (error) {\n throw new Error(`Failed to encrypt with password: ${error}`);\n }\n }\n\n async decryptWithPassword(\n encryptedData: Uint8Array,\n password: string,\n ): Promise<Uint8Array> {\n try {\n // Import openpgp for password-based decryption\n const openpgp = await import(\"openpgp\");\n\n const message = await openpgp.readMessage({\n binaryMessage: encryptedData,\n });\n\n // Use password-based decryption with wallet signature as password\n const { data: decrypted } = await openpgp.decrypt({\n message,\n passwords: [password],\n format: \"binary\",\n });\n\n // Convert decrypted data back to Uint8Array\n return new Uint8Array(decrypted as ArrayBuffer);\n } catch (error) {\n throw new Error(`Failed to decrypt with password: ${error}`);\n }\n }\n}\n\n/**\n * Browser implementation of PGP operations using openpgp with browser-specific configuration\n */\nclass BrowserPGPAdapter implements VanaPGPAdapter {\n async encrypt(data: string, publicKeyArmored: string): Promise<string> {\n try {\n const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });\n\n const encrypted = await openpgp.encrypt({\n message: await openpgp.createMessage({ text: data }),\n encryptionKeys: publicKey,\n config: {\n preferredCompressionAlgorithm: openpgp.enums.compression.zlib,\n },\n });\n\n return encrypted as string;\n } catch (error) {\n throw new Error(`PGP encryption failed: ${error}`);\n }\n }\n\n async decrypt(\n encryptedData: string,\n privateKeyArmored: string,\n ): Promise<string> {\n try {\n const privateKey = await openpgp.readPrivateKey({\n armoredKey: privateKeyArmored,\n });\n const message = await openpgp.readMessage({\n armoredMessage: encryptedData,\n });\n\n const { data: decrypted } = await openpgp.decrypt({\n message,\n decryptionKeys: privateKey,\n });\n\n return decrypted as string;\n } catch (error) {\n throw new Error(`PGP decryption failed: ${error}`);\n }\n }\n\n async generateKeyPair(options?: {\n name?: string;\n email?: string;\n passphrase?: string;\n }): Promise<{ publicKey: string; privateKey: string }> {\n try {\n // Use shared utility to get standardized parameters\n const keyGenParams = getPGPKeyGenParams(options);\n\n const { privateKey, publicKey } = await openpgp.generateKey(keyGenParams);\n\n return { publicKey, privateKey };\n } catch (error) {\n throw wrapCryptoError(\"PGP key generation\", error);\n }\n }\n}\n\n/**\n * Browser implementation of HTTP operations using fetch API\n */\nclass BrowserHttpAdapter implements VanaHttpAdapter {\n async fetch(url: string, options?: RequestInit): Promise<Response> {\n if (typeof fetch === \"undefined\") {\n throw new Error(\"Fetch API not available in this browser environment\");\n }\n\n return fetch(url, options);\n }\n}\n\n/**\n * Browser implementation of cache operations using sessionStorage\n */\nclass BrowserCacheAdapter implements VanaCacheAdapter {\n private readonly prefix = \"vana_cache_\";\n\n get(key: string): string | null {\n try {\n if (typeof sessionStorage === \"undefined\") {\n return null;\n }\n return sessionStorage.getItem(this.prefix + key);\n } catch {\n return null;\n }\n }\n\n set(key: string, value: string): void {\n try {\n if (typeof sessionStorage !== \"undefined\") {\n sessionStorage.setItem(this.prefix + key, value);\n }\n } catch {\n // Silently ignore storage errors (quota exceeded, etc.)\n }\n }\n\n delete(key: string): void {\n try {\n if (typeof sessionStorage !== \"undefined\") {\n sessionStorage.removeItem(this.prefix + key);\n }\n } catch {\n // Silently ignore storage errors\n }\n }\n\n clear(): void {\n try {\n if (typeof sessionStorage === \"undefined\") {\n return;\n }\n\n const keys = Object.keys(sessionStorage);\n for (const key of keys) {\n if (key.startsWith(this.prefix)) {\n sessionStorage.removeItem(key);\n }\n }\n } catch {\n // Silently ignore storage errors\n }\n }\n}\n\n/**\n * Complete browser platform adapter implementation\n */\nexport class BrowserPlatformAdapter implements VanaPlatformAdapter {\n crypto: VanaCryptoAdapter;\n pgp: VanaPGPAdapter;\n http: VanaHttpAdapter;\n cache: VanaCacheAdapter;\n platform: \"browser\" = \"browser\" as const;\n\n constructor() {\n this.crypto = new BrowserCryptoAdapter();\n this.pgp = new BrowserPGPAdapter();\n this.http = new BrowserHttpAdapter();\n this.cache = new BrowserCacheAdapter();\n }\n}\n\n/**\n * Default instance export for backwards compatibility\n */\nexport const browserPlatformAdapter: VanaPlatformAdapter =\n new BrowserPlatformAdapter();\n","/**\n * Browser-specific platform adapters entry point\n *\n * This module provides browser-safe platform utilities without Node.js dependencies.\n */\n\n// Export browser platform adapter\nexport { BrowserPlatformAdapter } from \"./platform/browser\";\n\n// Export platform interface\nexport type { VanaPlatformAdapter } from \"./platform/interface\";\n\n// Export browser-safe utilities only\nexport {\n createBrowserPlatformAdapter,\n createPlatformAdapterSafe,\n} from \"./platform/browser-only\";\n\n// Export safe platform utilities (no Node.js imports)\nexport {\n detectPlatform,\n isPlatformSupported,\n getPlatformCapabilities,\n} from \"./platform/utils\";\n","/**\n * Browser-only exports for platform adapters\n *\n * This file provides browser-only exports that completely avoid Node.js imports\n * when bundling for browser environments. This is used by the browser entry point.\n */\n\nimport type { VanaPlatformAdapter } from \"./interface\";\nimport { BrowserPlatformAdapter } from \"./browser\";\n\n/**\n * Creates a BrowserPlatformAdapter instance\n *\n * @returns A BrowserPlatformAdapter instance\n */\nexport function createBrowserPlatformAdapter(): VanaPlatformAdapter {\n return new BrowserPlatformAdapter();\n}\n\n/**\n * Browser-only platform adapter factory\n * This version does not include Node.js imports at all\n *\n * @returns A BrowserPlatformAdapter instance\n */\nexport function createPlatformAdapterSafe(): VanaPlatformAdapter {\n // Always return browser adapter in browser environments\n return createBrowserPlatformAdapter();\n}\n\n// Export types\nexport type { VanaPlatformAdapter } from \"./interface\";\nexport type { BrowserPlatformAdapter } from \"./browser\";\n","/**\n * Platform detection and adapter utilities\n *\n * This module provides utilities for detecting the current runtime environment\n * and creating appropriate platform adapters automatically.\n */\n\nimport type { VanaPlatformAdapter, PlatformType } from \"./interface\";\n\n/**\n * Detects the current runtime environment\n *\n * @returns The detected platform type\n */\nexport function detectPlatform(): PlatformType {\n // Check for Node.js environment\n if (\n typeof process !== \"undefined\" &&\n process.versions &&\n process.versions.node\n ) {\n return \"node\";\n }\n\n // Check for browser environment\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n return \"browser\";\n }\n\n // Default to Node.js if we can't determine (e.g., SSR environments)\n return \"node\";\n}\n\n/**\n * Creates the appropriate platform adapter based on the current environment\n *\n * @returns A platform adapter instance for the current environment\n * @throws {Error} If platform adapters cannot be imported or created\n */\nexport async function createPlatformAdapter(): Promise<VanaPlatformAdapter> {\n const platform = detectPlatform();\n\n try {\n if (platform === \"node\") {\n // Check if we're in a browser environment\n if (typeof window !== \"undefined\") {\n throw new Error(\n \"NodePlatformAdapter is not available in browser environments. Use BrowserPlatformAdapter instead.\",\n );\n }\n\n // Use string concatenation to avoid static analysis\n const moduleName = \"./node\";\n const { NodePlatformAdapter } = await import(moduleName);\n return new NodePlatformAdapter();\n } else {\n const { BrowserPlatformAdapter } = await import(\"./browser\");\n return new BrowserPlatformAdapter();\n }\n } catch (error) {\n throw new Error(\n `Failed to create platform adapter for ${platform}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n}\n\n/**\n * Creates a platform adapter for a specific platform type\n *\n * @param platformType - The platform type to create an adapter for\n * @returns A platform adapter instance for the specified platform\n * @throws {Error} If platform adapters cannot be imported or created\n */\nexport async function createPlatformAdapterFor(\n platformType: PlatformType,\n): Promise<VanaPlatformAdapter> {\n try {\n if (platformType === \"node\") {\n // Check if we're in a browser environment\n if (typeof window !== \"undefined\") {\n throw new Error(\n \"NodePlatformAdapter is not available in browser environments. Use BrowserPlatformAdapter instead.\",\n );\n }\n\n // Use string concatenation to avoid static analysis\n const moduleName = \"./node\";\n const { NodePlatformAdapter } = await import(moduleName);\n return new NodePlatformAdapter();\n } else {\n const { BrowserPlatformAdapter } = await import(\"./browser\");\n return new BrowserPlatformAdapter();\n }\n } catch (error) {\n throw new Error(\n `Failed to create platform adapter for ${platformType}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n}\n\n/**\n * Checks if the current environment supports the given platform adapter\n *\n * @param platformType - The platform type to check\n * @returns True if the platform is supported, false otherwise\n */\nexport function isPlatformSupported(platformType: PlatformType): boolean {\n const currentPlatform = detectPlatform();\n return currentPlatform === platformType;\n}\n\n/**\n * Gets platform-specific capabilities\n *\n * @returns Object describing available platform capabilities\n */\nexport function getPlatformCapabilities() {\n const platform = detectPlatform();\n\n return {\n platform,\n crypto: {\n webCrypto: typeof crypto !== \"undefined\" && crypto.subtle,\n nodeCrypto:\n typeof process !== \"undefined\" &&\n process.versions &&\n process.versions.node,\n },\n fetch:\n typeof fetch !== \"undefined\" || typeof globalThis.fetch !== \"undefined\",\n streams: typeof ReadableStream !== \"undefined\",\n };\n}\n"],"mappings":";;;;;;;;;AAcO,SAAS,uBAAuB,WAA2B;AAChE,QAAM,eAAe,UAAU,WAAW,IAAI,IAC1C,UAAU,MAAM,CAAC,IACjB;AACJ,QAAM,iBAAiB,OAAO,KAAK,cAAc,KAAK;AAItD,SAAO,eAAe,WAAW,KAC7B,OAAO,OAAO,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,cAAc,CAAC,IAChD;AACN;AASO,SAAS,wBAAwB,YAA4B;AAClE,QAAM,gBAAgB,WAAW,WAAW,IAAI,IAC5C,WAAW,MAAM,CAAC,IAClB;AACJ,SAAO,OAAO,KAAK,eAAe,KAAK;AACzC;AASO,SAAS,yBAAyB,iBAAyB;AAChE,SAAO;AAAA,IACL,IAAI,gBAAgB,MAAM,GAAG,EAAE;AAAA,IAC/B,gBAAgB,gBAAgB,MAAM,IAAI,EAAE;AAAA;AAAA,IAC5C,YAAY,gBA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MAAM,GAAG;AAC/B,6BAAe,WAAW,GAAG;AAAA,YAC/B;AAAA,UACF;AAAA,QACF,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAKO,IAAM,yBAAN,MAA4D;AAAA,MAOjE,cAAc;AANd;AACA;AACA;AACA;AACA,wCAAsB;AAGpB,aAAK,SAAS,IAAI,qBAAqB;AACvC,aAAK,MAAM,IAAI,kBAAkB;AACjC,aAAK,OAAO,IAAI,mBAAmB;AACnC,aAAK,QAAQ,IAAI,oBAAoB;AAAA,MACvC;AAAA,IACF;AAKO,IAAM,yBACX,IAAI,uBAAuB;AAAA;AAAA;;;ACpX7B;;;ACCA;AAOO,SAAS,+BAAoD;AAClE,SAAO,IAAI,uBAAuB;AACpC;AAQO,SAAS,4BAAiD;AAE/D,SAAO,6BAA6B;AACtC;;;ACdO,SAAS,iBAA+B;AAE7C,MACE,OAAO,YAAY,eACnB,QAAQ,YACR,QAAQ,SAAS,MACjB;AACA,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,WAAW,eAAe,OAAO,aAAa,aAAa;AACpE,WAAO;AAAA,EACT;AAGA,SAAO;AACT;AA2EO,SAAS,oBAAoB,cAAqC;AACvE,QAAM,kBAAkB,eAAe;AACvC,SAAO,oBAAoB;AAC7B;AAOO,SAAS,0BAA0B;AACxC,QAAM,WAAW,eAAe;AAEhC,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,MACN,WAAW,OAAO,WAAW,eAAe,OAAO;AAAA,MACnD,YACE,OAAO,YAAY,eACnB,QAAQ,YACR,QAAQ,SAAS;AAAA,IACrB;AAAA,IACA,OACE,OAAO,UAAU,eAAe,OAAO,WAAW,UAAU;AAAA,IAC9D,SAAS,OAAO,mBAAmB;AAAA,EACrC;AACF;","names":["openpgp"]}
|
|
1
|
+
{"version":3,"sources":["../src/platform/shared/crypto-utils.ts","../src/platform/shared/pgp-utils.ts","../src/platform/shared/error-utils.ts","../src/utils/lazy-import.ts","../src/platform/browser.ts","../src/platform.browser.ts","../src/platform/browser-only.ts","../src/platform/utils.ts"],"sourcesContent":["/**\n * Shared crypto utilities for platform adapters\n *\n * IMPORTANT: This module contains NO IMPORTS to avoid affecting bundle loading.\n * All functions are pure utilities that can be safely shared across platforms.\n */\n\n/**\n * Process wallet public key for encryption operations\n * Removes 0x prefix and ensures uncompressed format (65 bytes with 0x04 prefix)\n *\n * @param publicKey The public key (with or without 0x prefix)\n * @returns Buffer containing uncompressed public key\n */\nexport function processWalletPublicKey(publicKey: string): Buffer {\n const publicKeyHex = publicKey.startsWith(\"0x\")\n ? publicKey.slice(2)\n : publicKey;\n const publicKeyBytes = Buffer.from(publicKeyHex, \"hex\");\n\n // Ensure public key is in uncompressed format (65 bytes with 0x04 prefix)\n // If it's 64 bytes, add the 0x04 prefix; if already 65 bytes, use as-is\n return publicKeyBytes.length === 64\n ? Buffer.concat([Buffer.from([4]), publicKeyBytes])\n : publicKeyBytes;\n}\n\n/**\n * Process wallet private key for decryption operations\n * Removes 0x prefix and converts to Buffer\n *\n * @param privateKey The private key (with or without 0x prefix)\n * @returns Buffer containing private key\n */\nexport function processWalletPrivateKey(privateKey: string): Buffer {\n const privateKeyHex = privateKey.startsWith(\"0x\")\n ? privateKey.slice(2)\n : privateKey;\n return Buffer.from(privateKeyHex, \"hex\");\n}\n\n/**\n * Parse encrypted data buffer into components\n * Extracts IV, ephemeral public key, ciphertext, and MAC from a concatenated buffer\n *\n * @param encryptedBuffer The buffer containing encrypted data\n * @returns Object with parsed components\n */\nexport function parseEncryptedDataBuffer(encryptedBuffer: Buffer) {\n return {\n iv: encryptedBuffer.slice(0, 16),\n ephemPublicKey: encryptedBuffer.slice(16, 81), // 65 bytes for uncompressed public key\n ciphertext: encryptedBuffer.slice(81, -32),\n mac: encryptedBuffer.slice(-32),\n };\n}\n\n/**\n * Convert hex string to Uint8Array\n *\n * @param hex The hex string to convert\n * @returns Uint8Array representation\n */\nexport function hexToUint8Array(hex: string): Uint8Array {\n const result = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n result[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n return result;\n}\n\n/**\n * Convert Uint8Array to hex string\n *\n * @param array The Uint8Array to convert\n * @returns Hex string representation\n */\nexport function uint8ArrayToHex(array: Uint8Array): string {\n return Array.from(array, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\n/**\n * Cross-platform base64 encoding\n * Works in both Node.js and browser environments\n *\n * @param str The string to encode\n * @returns Base64 encoded string\n */\nexport function toBase64(str: string): string {\n if (typeof Buffer !== \"undefined\") {\n // Node.js environment\n return Buffer.from(str, \"utf8\").toString(\"base64\");\n } else if (typeof btoa !== \"undefined\") {\n // Browser environment\n return btoa(str);\n } else {\n // Fallback manual implementation\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let result = \"\";\n let i = 0;\n while (i < str.length) {\n const a = str.charCodeAt(i++);\n const b = i < str.length ? str.charCodeAt(i++) : 0;\n const c = i < str.length ? str.charCodeAt(i++) : 0;\n\n const bitmap = (a << 16) | (b << 8) | c;\n\n result += chars.charAt((bitmap >> 18) & 63);\n result += chars.charAt((bitmap >> 12) & 63);\n result += i - 2 < str.length ? chars.charAt((bitmap >> 6) & 63) : \"=\";\n result += i - 1 < str.length ? chars.charAt(bitmap & 63) : \"=\";\n }\n return result;\n }\n}\n\n/**\n * Cross-platform base64 decoding\n * Works in both Node.js and browser environments\n *\n * @param str The base64 string to decode\n * @returns Decoded string\n */\nexport function fromBase64(str: string): string {\n if (typeof Buffer !== \"undefined\") {\n // Node.js environment\n return Buffer.from(str, \"base64\").toString(\"utf8\");\n } else if (typeof atob !== \"undefined\") {\n // Browser environment\n return atob(str);\n } else {\n // Fallback manual implementation\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let result = \"\";\n let i = 0;\n\n // Remove any characters not in the base64 character set\n str = str.replace(/[^A-Za-z0-9+/]/g, \"\");\n\n while (i < str.length) {\n const encoded1 = chars.indexOf(str.charAt(i++));\n const encoded2 = chars.indexOf(str.charAt(i++));\n const encoded3 = chars.indexOf(str.charAt(i++));\n const encoded4 = chars.indexOf(str.charAt(i++));\n\n const bitmap =\n (encoded1 << 18) | (encoded2 << 12) | (encoded3 << 6) | encoded4;\n\n result += String.fromCharCode((bitmap >> 16) & 255);\n if (encoded3 !== 64) result += String.fromCharCode((bitmap >> 8) & 255);\n if (encoded4 !== 64) result += String.fromCharCode(bitmap & 255);\n }\n return result;\n }\n}\n","/**\n * Shared PGP utilities for platform adapters\n *\n * IMPORTANT: This module contains NO IMPORTS to avoid affecting bundle loading.\n * All functions are pure utilities that can be safely shared across platforms.\n */\n\n/**\n * Standard OpenPGP configuration for consistent behavior across platforms\n * Uses enum values instead of importing openpgp to avoid loading issues\n */\nexport const STANDARD_PGP_CONFIG = {\n preferredCompressionAlgorithm: 2, // zlib (openpgp.enums.compression.zlib)\n preferredSymmetricAlgorithm: 7, // aes256 (openpgp.enums.symmetric.aes256)\n} as const;\n\n/**\n * Process PGP key generation options with sensible defaults\n *\n * @param options - Optional key generation parameters\n * @param options.name - The name for the PGP key (defaults to \"Vana User\")\n * @param options.email - The email for the PGP key (defaults to \"user@vana.org\")\n * @param options.passphrase - Optional passphrase to protect the private key\n * @returns Processed options with defaults applied\n */\nexport function processPGPKeyOptions(options?: {\n name?: string;\n email?: string;\n passphrase?: string;\n}) {\n return {\n name: options?.name || \"Vana User\",\n email: options?.email || \"user@vana.org\",\n passphrase: options?.passphrase,\n };\n}\n\n/**\n * Get standard PGP key generation parameters\n * Combines default values with standard configuration\n *\n * @param options - Optional key generation parameters\n * @param options.name - The name for the PGP key (defaults to \"Vana User\")\n * @param options.email - The email for the PGP key (defaults to \"user@vana.org\")\n * @param options.passphrase - Optional passphrase to protect the private key\n * @returns Complete key generation parameters object\n */\nexport function getPGPKeyGenParams(options?: {\n name?: string;\n email?: string;\n passphrase?: string;\n}) {\n const { name, email, passphrase } = processPGPKeyOptions(options);\n\n return {\n type: \"rsa\" as const,\n rsaBits: 2048,\n userIDs: [{ name, email }],\n passphrase,\n config: STANDARD_PGP_CONFIG,\n };\n}\n","/**\n * Shared error utilities for platform adapters\n *\n * IMPORTANT: This module contains NO IMPORTS to avoid affecting bundle loading.\n * All functions are pure utilities that can be safely shared across platforms.\n */\n\n/**\n * Wrap platform-specific errors with consistent messaging\n * Provides consistent error formatting across all crypto operations\n *\n * @param operation The operation that failed (e.g., \"encryption\", \"decryption\")\n * @param error The original error that occurred\n * @returns Wrapped error with consistent format\n */\nexport function wrapCryptoError(operation: string, error: unknown): Error {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return new Error(`${operation} failed: ${message}`);\n}\n\n/**\n * Validate encrypted data structure has required fields\n * Ensures encrypted data objects contain the expected properties\n *\n * @param data The data structure to validate\n * @throws Error if data structure is invalid\n */\nexport function validateEncryptedDataStructure(data: unknown): void {\n if (!data || typeof data !== \"object\") {\n throw new Error(\"Invalid encrypted data format\");\n }\n\n const obj = data as Record<string, unknown>;\n if (!obj.encrypted || !obj.iv || !obj.ephemeralPublicKey) {\n throw new Error(\"Invalid encrypted data format\");\n }\n}\n","/**\n * Utility for lazy-loading modules to avoid Turbopack TDZ issues\n *\n * WARNING: This is a workaround for Turbopack's strict module initialization.\n * Dependencies that access globals during init must be dynamically imported.\n */\n\n/**\n * Creates a lazy import function that caches the promise (not the module)\n * to avoid race conditions on concurrent first calls\n *\n * @param importFn - Function that returns a dynamic import promise\n * @returns Function that returns the cached import promise\n *\n * @example\n * const getOpenPGP = lazyImport(() => import('openpgp'));\n * const openpgp = await getOpenPGP();\n */\nexport function lazyImport<T>(importFn: () => Promise<T>): () => Promise<T> {\n let cached: Promise<T> | null = null;\n\n return () => {\n if (!cached) {\n cached = importFn().catch((err) => {\n // Clear cache on error so next attempt can retry\n cached = null;\n throw new Error(\"Failed to load module\", { cause: err });\n });\n }\n return cached;\n };\n}\n","/**\n * Browser implementation of the Vana Platform Adapter\n *\n * This implementation uses browser-compatible libraries and configurations\n * to provide crypto, PGP, and HTTP functionality without Node.js dependencies.\n *\n * WARNING: Dependencies that access globals during init\n * MUST be dynamically imported to support Turbopack.\n * See: https://github.com/vercel/next.js/issues/82632\n */\n\nimport type {\n VanaPlatformAdapter,\n VanaCryptoAdapter,\n VanaPGPAdapter,\n VanaHttpAdapter,\n VanaCacheAdapter,\n} from \"./interface\";\nimport {\n processWalletPublicKey,\n processWalletPrivateKey,\n parseEncryptedDataBuffer,\n} from \"./shared/crypto-utils\";\nimport { getPGPKeyGenParams } from \"./shared/pgp-utils\";\nimport { wrapCryptoError } from \"./shared/error-utils\";\nimport { lazyImport } from \"../utils/lazy-import\";\n\n// Lazy-loaded dependencies to avoid Turbopack TDZ issues\nconst getOpenPGP = lazyImport(() => import(\"openpgp\"));\n\n/**\n * Browser implementation of crypto operations using eccrypto-js\n */\nclass BrowserCryptoAdapter implements VanaCryptoAdapter {\n async encryptWithPublicKey(\n data: string,\n publicKeyHex: string,\n ): Promise<string> {\n try {\n // Import eccrypto-js for secp256k1 encryption\n const eccrypto = await import(\"eccrypto-js\");\n\n // Convert hex public key to Buffer\n const publicKeyBuffer = Buffer.from(publicKeyHex, \"hex\");\n\n // Encrypt data using secp256k1 ECDH\n const encrypted = await eccrypto.encrypt(\n publicKeyBuffer,\n Buffer.from(data, \"utf8\"),\n );\n\n // Concatenate all components and return as hex string for API consistency\n const result = Buffer.concat([\n encrypted.iv,\n encrypted.ephemPublicKey,\n encrypted.ciphertext,\n encrypted.mac,\n ]);\n\n return result.toString(\"hex\");\n } catch (error) {\n throw new Error(`Encryption failed: ${error}`);\n }\n }\n\n async decryptWithPrivateKey(\n encryptedData: string,\n privateKeyHex: string,\n ): Promise<string> {\n try {\n // Import eccrypto-js for secp256k1 decryption\n const eccrypto = await import(\"eccrypto-js\");\n\n // Use shared utilities to process keys and parse data\n const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);\n const encryptedBuffer = Buffer.from(encryptedData, \"hex\");\n const { iv, ephemPublicKey, ciphertext, mac } =\n parseEncryptedDataBuffer(encryptedBuffer);\n\n // Reconstruct the encrypted data structure for eccrypto\n const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };\n\n // Decrypt using secp256k1 ECDH\n const decryptedBuffer = await eccrypto.decrypt(\n privateKeyBuffer,\n encryptedObj,\n );\n\n return decryptedBuffer.toString(\"utf8\");\n } catch (error) {\n throw new Error(`Decryption failed: ${error}`);\n }\n }\n\n async generateKeyPair(): Promise<{ publicKey: string; privateKey: string }> {\n try {\n // Import eccrypto-js for secp256k1 key generation (browser-compatible)\n const eccrypto = await import(\"eccrypto-js\");\n\n // Generate a random 32-byte private key for secp256k1\n const privateKeyBytes = new Uint8Array(32);\n crypto.getRandomValues(privateKeyBytes);\n const privateKey = Buffer.from(privateKeyBytes);\n\n // Generate the corresponding compressed public key\n const publicKey = eccrypto.getPublicCompressed(privateKey);\n\n return {\n privateKey: privateKey.toString(\"hex\"),\n publicKey: publicKey.toString(\"hex\"),\n };\n } catch (error) {\n throw wrapCryptoError(\"key generation\", error);\n }\n }\n\n async encryptWithWalletPublicKey(\n data: string,\n publicKey: string,\n ): Promise<string> {\n try {\n // Import eccrypto for ECDH encryption\n const eccrypto = await import(\"eccrypto-js\");\n\n // Use shared utility to process public key\n const uncompressedKey = processWalletPublicKey(publicKey);\n\n // Encrypt using ECDH with randomly generated parameters\n const encryptedBuffer = await eccrypto.encrypt(\n uncompressedKey,\n Buffer.from(data),\n );\n\n // Concatenate all components and return as hex\n const result = Buffer.concat([\n encryptedBuffer.iv,\n encryptedBuffer.ephemPublicKey,\n encryptedBuffer.ciphertext,\n encryptedBuffer.mac,\n ]);\n\n return result.toString(\"hex\");\n } catch (error) {\n throw wrapCryptoError(\"encrypt with wallet public key\", error);\n }\n }\n\n async decryptWithWalletPrivateKey(\n encryptedData: string,\n privateKey: string,\n ): Promise<string> {\n try {\n // Import eccrypto for ECDH decryption\n const eccrypto = await import(\"eccrypto-js\");\n\n // Use shared utilities to process keys and parse data\n const privateKeyBuffer = processWalletPrivateKey(privateKey);\n const encryptedBuffer = Buffer.from(encryptedData, \"hex\");\n const { iv, ephemPublicKey, ciphertext, mac } =\n parseEncryptedDataBuffer(encryptedBuffer);\n\n // Reconstruct the encrypted data structure for eccrypto\n const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };\n\n // Decrypt using ECDH\n const decryptedBuffer = await eccrypto.decrypt(\n privateKeyBuffer,\n encryptedObj,\n );\n\n return decryptedBuffer.toString(\"utf8\");\n } catch (error) {\n throw wrapCryptoError(\"decrypt with wallet private key\", error);\n }\n }\n\n async encryptWithPassword(\n data: Uint8Array,\n password: string,\n ): Promise<Uint8Array> {\n try {\n // Import openpgp for password-based encryption\n const openpgp = await getOpenPGP();\n\n const message = await openpgp.createMessage({\n binary: data,\n });\n\n // Use password-based encryption with wallet signature as password\n // Note: For deterministic encryption, we would need to control the salt\n // This implementation is secure but not deterministic due to OpenPGP's design\n const encrypted = await openpgp.encrypt({\n message,\n passwords: [password],\n format: \"binary\",\n });\n\n // Convert WebStream<Uint8Array> to Uint8Array\n const response = new Response(encrypted as ReadableStream<Uint8Array>);\n const arrayBuffer = await response.arrayBuffer();\n return new Uint8Array(arrayBuffer);\n } catch (error) {\n throw new Error(`Failed to encrypt with password: ${error}`);\n }\n }\n\n async decryptWithPassword(\n encryptedData: Uint8Array,\n password: string,\n ): Promise<Uint8Array> {\n try {\n // Import openpgp for password-based decryption\n const openpgp = await getOpenPGP();\n\n const message = await openpgp.readMessage({\n binaryMessage: encryptedData,\n });\n\n // Use password-based decryption with wallet signature as password\n const { data: decrypted } = await openpgp.decrypt({\n message,\n passwords: [password],\n format: \"binary\",\n });\n\n // Convert decrypted data back to Uint8Array\n return new Uint8Array(decrypted as ArrayBuffer);\n } catch (error) {\n throw new Error(`Failed to decrypt with password: ${error}`);\n }\n }\n}\n\n/**\n * Browser implementation of PGP operations using openpgp with browser-specific configuration\n */\nclass BrowserPGPAdapter implements VanaPGPAdapter {\n async encrypt(data: string, publicKeyArmored: string): Promise<string> {\n try {\n const openpgp = await getOpenPGP();\n const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });\n\n const encrypted = await openpgp.encrypt({\n message: await openpgp.createMessage({ text: data }),\n encryptionKeys: publicKey,\n config: {\n preferredCompressionAlgorithm: openpgp.enums.compression.zlib,\n },\n });\n\n return encrypted as string;\n } catch (error) {\n throw new Error(`PGP encryption failed: ${error}`);\n }\n }\n\n async decrypt(\n encryptedData: string,\n privateKeyArmored: string,\n ): Promise<string> {\n try {\n const openpgp = await getOpenPGP();\n const privateKey = await openpgp.readPrivateKey({\n armoredKey: privateKeyArmored,\n });\n const message = await openpgp.readMessage({\n armoredMessage: encryptedData,\n });\n\n const { data: decrypted } = await openpgp.decrypt({\n message,\n decryptionKeys: privateKey,\n });\n\n return decrypted as string;\n } catch (error) {\n throw new Error(`PGP decryption failed: ${error}`);\n }\n }\n\n async generateKeyPair(options?: {\n name?: string;\n email?: string;\n passphrase?: string;\n }): Promise<{ publicKey: string; privateKey: string }> {\n try {\n const openpgp = await getOpenPGP();\n // Use shared utility to get standardized parameters\n const keyGenParams = getPGPKeyGenParams(options);\n\n const { privateKey, publicKey } = await openpgp.generateKey(keyGenParams);\n\n return { publicKey, privateKey };\n } catch (error) {\n throw wrapCryptoError(\"PGP key generation\", error);\n }\n }\n}\n\n/**\n * Browser implementation of HTTP operations using fetch API\n */\nclass BrowserHttpAdapter implements VanaHttpAdapter {\n async fetch(url: string, options?: RequestInit): Promise<Response> {\n if (typeof fetch === \"undefined\") {\n throw new Error(\"Fetch API not available in this browser environment\");\n }\n\n return fetch(url, options);\n }\n}\n\n/**\n * Browser implementation of cache operations using sessionStorage\n */\nclass BrowserCacheAdapter implements VanaCacheAdapter {\n private readonly prefix = \"vana_cache_\";\n\n get(key: string): string | null {\n try {\n if (typeof sessionStorage === \"undefined\") {\n return null;\n }\n return sessionStorage.getItem(this.prefix + key);\n } catch {\n return null;\n }\n }\n\n set(key: string, value: string): void {\n try {\n if (typeof sessionStorage !== \"undefined\") {\n sessionStorage.setItem(this.prefix + key, value);\n }\n } catch {\n // Silently ignore storage errors (quota exceeded, etc.)\n }\n }\n\n delete(key: string): void {\n try {\n if (typeof sessionStorage !== \"undefined\") {\n sessionStorage.removeItem(this.prefix + key);\n }\n } catch {\n // Silently ignore storage errors\n }\n }\n\n clear(): void {\n try {\n if (typeof sessionStorage === \"undefined\") {\n return;\n }\n\n const keys = Object.keys(sessionStorage);\n for (const key of keys) {\n if (key.startsWith(this.prefix)) {\n sessionStorage.removeItem(key);\n }\n }\n } catch {\n // Silently ignore storage errors\n }\n }\n}\n\n/**\n * Complete browser platform adapter implementation\n */\nexport class BrowserPlatformAdapter implements VanaPlatformAdapter {\n crypto: VanaCryptoAdapter;\n pgp: VanaPGPAdapter;\n http: VanaHttpAdapter;\n cache: VanaCacheAdapter;\n platform: \"browser\" = \"browser\" as const;\n\n constructor() {\n this.crypto = new BrowserCryptoAdapter();\n this.pgp = new BrowserPGPAdapter();\n this.http = new BrowserHttpAdapter();\n this.cache = new BrowserCacheAdapter();\n }\n}\n\n/**\n * Default instance export for backwards compatibility\n */\nexport const browserPlatformAdapter: VanaPlatformAdapter =\n new BrowserPlatformAdapter();\n","/**\n * Browser-specific platform adapters entry point\n *\n * This module provides browser-safe platform utilities without Node.js dependencies.\n */\n\n// Export browser platform adapter\nexport { BrowserPlatformAdapter } from \"./platform/browser\";\n\n// Export platform interface\nexport type { VanaPlatformAdapter } from \"./platform/interface\";\n\n// Export browser-safe utilities only\nexport {\n createBrowserPlatformAdapter,\n createPlatformAdapterSafe,\n} from \"./platform/browser-only\";\n\n// Export safe platform utilities (no Node.js imports)\nexport {\n detectPlatform,\n isPlatformSupported,\n getPlatformCapabilities,\n} from \"./platform/utils\";\n","/**\n * Browser-only exports for platform adapters\n *\n * This file provides browser-only exports that completely avoid Node.js imports\n * when bundling for browser environments. This is used by the browser entry point.\n */\n\nimport type { VanaPlatformAdapter } from \"./interface\";\nimport { BrowserPlatformAdapter } from \"./browser\";\n\n/**\n * Creates a BrowserPlatformAdapter instance\n *\n * @returns A BrowserPlatformAdapter instance\n */\nexport function createBrowserPlatformAdapter(): VanaPlatformAdapter {\n return new BrowserPlatformAdapter();\n}\n\n/**\n * Browser-only platform adapter factory\n * This version does not include Node.js imports at all\n *\n * @returns A BrowserPlatformAdapter instance\n */\nexport function createPlatformAdapterSafe(): VanaPlatformAdapter {\n // Always return browser adapter in browser environments\n return createBrowserPlatformAdapter();\n}\n\n// Export types\nexport type { VanaPlatformAdapter } from \"./interface\";\nexport type { BrowserPlatformAdapter } from \"./browser\";\n","/**\n * Platform detection and adapter utilities\n *\n * This module provides utilities for detecting the current runtime environment\n * and creating appropriate platform adapters automatically.\n */\n\nimport type { VanaPlatformAdapter, PlatformType } from \"./interface\";\n\n/**\n * Detects the current runtime environment\n *\n * @returns The detected platform type\n */\nexport function detectPlatform(): PlatformType {\n // Check for Node.js environment\n if (\n typeof process !== \"undefined\" &&\n process.versions &&\n process.versions.node\n ) {\n return \"node\";\n }\n\n // Check for browser environment\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n return \"browser\";\n }\n\n // Default to Node.js if we can't determine (e.g., SSR environments)\n return \"node\";\n}\n\n/**\n * Creates the appropriate platform adapter based on the current environment\n *\n * @returns A platform adapter instance for the current environment\n * @throws {Error} If platform adapters cannot be imported or created\n */\nexport async function createPlatformAdapter(): Promise<VanaPlatformAdapter> {\n const platform = detectPlatform();\n\n try {\n if (platform === \"node\") {\n // Check if we're in a browser environment\n if (typeof window !== \"undefined\") {\n throw new Error(\n \"NodePlatformAdapter is not available in browser environments. Use BrowserPlatformAdapter instead.\",\n );\n }\n\n // Use string concatenation to avoid static analysis\n const moduleName = \"./node\";\n const { NodePlatformAdapter } = await import(moduleName);\n return new NodePlatformAdapter();\n } else {\n const { BrowserPlatformAdapter } = await import(\"./browser\");\n return new BrowserPlatformAdapter();\n }\n } catch (error) {\n throw new Error(\n `Failed to create platform adapter for ${platform}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n}\n\n/**\n * Creates a platform adapter for a specific platform type\n *\n * @param platformType - The platform type to create an adapter for\n * @returns A platform adapter instance for the specified platform\n * @throws {Error} If platform adapters cannot be imported or created\n */\nexport async function createPlatformAdapterFor(\n platformType: PlatformType,\n): Promise<VanaPlatformAdapter> {\n try {\n if (platformType === \"node\") {\n // Check if we're in a browser environment\n if (typeof window !== \"undefined\") {\n throw new Error(\n \"NodePlatformAdapter is not available in browser environments. Use BrowserPlatformAdapter instead.\",\n );\n }\n\n // Use string concatenation to avoid static analysis\n const moduleName = \"./node\";\n const { NodePlatformAdapter } = await import(moduleName);\n return new NodePlatformAdapter();\n } else {\n const { BrowserPlatformAdapter } = await import(\"./browser\");\n return new BrowserPlatformAdapter();\n }\n } catch (error) {\n throw new Error(\n `Failed to create platform adapter for ${platformType}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n}\n\n/**\n * Checks if the current environment supports the given platform adapter\n *\n * @param platformType - The platform type to check\n * @returns True if the platform is supported, false otherwise\n */\nexport function isPlatformSupported(platformType: PlatformType): boolean {\n const currentPlatform = detectPlatform();\n return currentPlatform === platformType;\n}\n\n/**\n * Gets platform-specific capabilities\n *\n * @returns Object describing available platform capabilities\n */\nexport function getPlatformCapabilities() {\n const platform = detectPlatform();\n\n return {\n platform,\n crypto: {\n webCrypto: typeof crypto !== \"undefined\" && crypto.subtle,\n nodeCrypto:\n typeof process !== \"undefined\" &&\n process.versions &&\n process.versions.node,\n },\n fetch:\n typeof fetch !== \"undefined\" || typeof globalThis.fetch !== \"undefined\",\n streams: typeof ReadableStream !== \"undefined\",\n };\n}\n"],"mappings":";;;;;;;;;AAcO,SAAS,uBAAuB,WAA2B;AAChE,QAAM,eAAe,UAAU,WAAW,IAAI,IAC1C,UAAU,MAAM,CAAC,IACjB;AACJ,QAAM,iBA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IACF;AAKO,IAAM,yBACX,IAAI,uBAAuB;AAAA;AAAA;;;AC9X7B;;;ACCA;AAOO,SAAS,+BAAoD;AAClE,SAAO,IAAI,uBAAuB;AACpC;AAQO,SAAS,4BAAiD;AAE/D,SAAO,6BAA6B;AACtC;;;ACdO,SAAS,iBAA+B;AAE7C,MACE,OAAO,YAAY,eACnB,QAAQ,YACR,QAAQ,SAAS,MACjB;AACA,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,WAAW,eAAe,OAAO,aAAa,aAAa;AACpE,WAAO;AAAA,EACT;AAGA,SAAO;AACT;AA2EO,SAAS,oBAAoB,cAAqC;AACvE,QAAM,kBAAkB,eAAe;AACvC,SAAO,oBAAoB;AAC7B;AAOO,SAAS,0BAA0B;AACxC,QAAM,WAAW,eAAe;AAEhC,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,MACN,WAAW,OAAO,WAAW,eAAe,OAAO;AAAA,MACnD,YACE,OAAO,YAAY,eACnB,QAAQ,YACR,QAAQ,SAAS;AAAA,IACrB;AAAA,IACA,OACE,OAAO,UAAU,eAAe,OAAO,WAAW,UAAU;AAAA,IAC9D,SAAS,OAAO,mBAAmB;AAAA,EACrC;AACF;","names":[]}
|
package/dist/platform.cjs
CHANGED
|
@@ -97,26 +97,46 @@ var init_error_utils = __esm({
|
|
|
97
97
|
}
|
|
98
98
|
});
|
|
99
99
|
|
|
100
|
+
// src/utils/lazy-import.ts
|
|
101
|
+
function lazyImport(importFn) {
|
|
102
|
+
let cached = null;
|
|
103
|
+
return () => {
|
|
104
|
+
if (!cached) {
|
|
105
|
+
cached = importFn().catch((err) => {
|
|
106
|
+
cached = null;
|
|
107
|
+
throw new Error("Failed to load module", { cause: err });
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
return cached;
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
var init_lazy_import = __esm({
|
|
114
|
+
"src/utils/lazy-import.ts"() {
|
|
115
|
+
"use strict";
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
|
|
100
119
|
// src/platform/browser.ts
|
|
101
120
|
var browser_exports = {};
|
|
102
121
|
__export(browser_exports, {
|
|
103
122
|
BrowserPlatformAdapter: () => BrowserPlatformAdapter,
|
|
104
123
|
browserPlatformAdapter: () => browserPlatformAdapter
|
|
105
124
|
});
|
|
106
|
-
var
|
|
125
|
+
var getOpenPGP, BrowserCryptoAdapter, BrowserPGPAdapter, BrowserHttpAdapter, BrowserCacheAdapter, BrowserPlatformAdapter, browserPlatformAdapter;
|
|
107
126
|
var init_browser = __esm({
|
|
108
127
|
"src/platform/browser.ts"() {
|
|
109
128
|
"use strict";
|
|
110
|
-
openpgp = __toESM(require("openpgp"), 1);
|
|
111
129
|
init_crypto_utils();
|
|
112
130
|
init_pgp_utils();
|
|
113
131
|
init_error_utils();
|
|
132
|
+
init_lazy_import();
|
|
133
|
+
getOpenPGP = lazyImport(() => import("openpgp"));
|
|
114
134
|
BrowserCryptoAdapter = class {
|
|
115
135
|
async encryptWithPublicKey(data, publicKeyHex) {
|
|
116
136
|
try {
|
|
117
|
-
const
|
|
137
|
+
const eccrypto = await import("eccrypto-js");
|
|
118
138
|
const publicKeyBuffer = Buffer.from(publicKeyHex, "hex");
|
|
119
|
-
const encrypted = await
|
|
139
|
+
const encrypted = await eccrypto.encrypt(
|
|
120
140
|
publicKeyBuffer,
|
|
121
141
|
Buffer.from(data, "utf8")
|
|
122
142
|
);
|
|
@@ -133,12 +153,12 @@ var init_browser = __esm({
|
|
|
133
153
|
}
|
|
134
154
|
async decryptWithPrivateKey(encryptedData, privateKeyHex) {
|
|
135
155
|
try {
|
|
136
|
-
const
|
|
156
|
+
const eccrypto = await import("eccrypto-js");
|
|
137
157
|
const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
|
|
138
158
|
const encryptedBuffer = Buffer.from(encryptedData, "hex");
|
|
139
159
|
const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
|
|
140
160
|
const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
|
|
141
|
-
const decryptedBuffer = await
|
|
161
|
+
const decryptedBuffer = await eccrypto.decrypt(
|
|
142
162
|
privateKeyBuffer,
|
|
143
163
|
encryptedObj
|
|
144
164
|
);
|
|
@@ -149,11 +169,11 @@ var init_browser = __esm({
|
|
|
149
169
|
}
|
|
150
170
|
async generateKeyPair() {
|
|
151
171
|
try {
|
|
152
|
-
const
|
|
172
|
+
const eccrypto = await import("eccrypto-js");
|
|
153
173
|
const privateKeyBytes = new Uint8Array(32);
|
|
154
174
|
crypto.getRandomValues(privateKeyBytes);
|
|
155
175
|
const privateKey = Buffer.from(privateKeyBytes);
|
|
156
|
-
const publicKey =
|
|
176
|
+
const publicKey = eccrypto.getPublicCompressed(privateKey);
|
|
157
177
|
return {
|
|
158
178
|
privateKey: privateKey.toString("hex"),
|
|
159
179
|
publicKey: publicKey.toString("hex")
|
|
@@ -164,9 +184,9 @@ var init_browser = __esm({
|
|
|
164
184
|
}
|
|
165
185
|
async encryptWithWalletPublicKey(data, publicKey) {
|
|
166
186
|
try {
|
|
167
|
-
const
|
|
187
|
+
const eccrypto = await import("eccrypto-js");
|
|
168
188
|
const uncompressedKey = processWalletPublicKey(publicKey);
|
|
169
|
-
const encryptedBuffer = await
|
|
189
|
+
const encryptedBuffer = await eccrypto.encrypt(
|
|
170
190
|
uncompressedKey,
|
|
171
191
|
Buffer.from(data)
|
|
172
192
|
);
|
|
@@ -183,12 +203,12 @@ var init_browser = __esm({
|
|
|
183
203
|
}
|
|
184
204
|
async decryptWithWalletPrivateKey(encryptedData, privateKey) {
|
|
185
205
|
try {
|
|
186
|
-
const
|
|
206
|
+
const eccrypto = await import("eccrypto-js");
|
|
187
207
|
const privateKeyBuffer = processWalletPrivateKey(privateKey);
|
|
188
208
|
const encryptedBuffer = Buffer.from(encryptedData, "hex");
|
|
189
209
|
const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
|
|
190
210
|
const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
|
|
191
|
-
const decryptedBuffer = await
|
|
211
|
+
const decryptedBuffer = await eccrypto.decrypt(
|
|
192
212
|
privateKeyBuffer,
|
|
193
213
|
encryptedObj
|
|
194
214
|
);
|
|
@@ -199,11 +219,11 @@ var init_browser = __esm({
|
|
|
199
219
|
}
|
|
200
220
|
async encryptWithPassword(data, password) {
|
|
201
221
|
try {
|
|
202
|
-
const
|
|
203
|
-
const message = await
|
|
222
|
+
const openpgp = await getOpenPGP();
|
|
223
|
+
const message = await openpgp.createMessage({
|
|
204
224
|
binary: data
|
|
205
225
|
});
|
|
206
|
-
const encrypted = await
|
|
226
|
+
const encrypted = await openpgp.encrypt({
|
|
207
227
|
message,
|
|
208
228
|
passwords: [password],
|
|
209
229
|
format: "binary"
|
|
@@ -217,11 +237,11 @@ var init_browser = __esm({
|
|
|
217
237
|
}
|
|
218
238
|
async decryptWithPassword(encryptedData, password) {
|
|
219
239
|
try {
|
|
220
|
-
const
|
|
221
|
-
const message = await
|
|
240
|
+
const openpgp = await getOpenPGP();
|
|
241
|
+
const message = await openpgp.readMessage({
|
|
222
242
|
binaryMessage: encryptedData
|
|
223
243
|
});
|
|
224
|
-
const { data: decrypted } = await
|
|
244
|
+
const { data: decrypted } = await openpgp.decrypt({
|
|
225
245
|
message,
|
|
226
246
|
passwords: [password],
|
|
227
247
|
format: "binary"
|
|
@@ -235,6 +255,7 @@ var init_browser = __esm({
|
|
|
235
255
|
BrowserPGPAdapter = class {
|
|
236
256
|
async encrypt(data, publicKeyArmored) {
|
|
237
257
|
try {
|
|
258
|
+
const openpgp = await getOpenPGP();
|
|
238
259
|
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
|
|
239
260
|
const encrypted = await openpgp.encrypt({
|
|
240
261
|
message: await openpgp.createMessage({ text: data }),
|
|
@@ -250,6 +271,7 @@ var init_browser = __esm({
|
|
|
250
271
|
}
|
|
251
272
|
async decrypt(encryptedData, privateKeyArmored) {
|
|
252
273
|
try {
|
|
274
|
+
const openpgp = await getOpenPGP();
|
|
253
275
|
const privateKey = await openpgp.readPrivateKey({
|
|
254
276
|
armoredKey: privateKeyArmored
|
|
255
277
|
});
|
|
@@ -267,6 +289,7 @@ var init_browser = __esm({
|
|
|
267
289
|
}
|
|
268
290
|
async generateKeyPair(options) {
|
|
269
291
|
try {
|
|
292
|
+
const openpgp = await getOpenPGP();
|
|
270
293
|
const keyGenParams = getPGPKeyGenParams(options);
|
|
271
294
|
const { privateKey, publicKey } = await openpgp.generateKey(keyGenParams);
|
|
272
295
|
return { publicKey, privateKey };
|
|
@@ -361,8 +384,6 @@ module.exports = __toCommonJS(platform_exports);
|
|
|
361
384
|
init_browser();
|
|
362
385
|
|
|
363
386
|
// src/platform/node.ts
|
|
364
|
-
var import_crypto = require("crypto");
|
|
365
|
-
var openpgp2 = __toESM(require("openpgp"), 1);
|
|
366
387
|
init_crypto_utils();
|
|
367
388
|
init_pgp_utils();
|
|
368
389
|
init_error_utils();
|
|
@@ -391,29 +412,16 @@ async function streamToUint8Array(stream) {
|
|
|
391
412
|
}
|
|
392
413
|
|
|
393
414
|
// src/platform/node.ts
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
try {
|
|
398
|
-
const eccryptoLib = await import("eccrypto");
|
|
399
|
-
eccrypto = {
|
|
400
|
-
encrypt: eccryptoLib.encrypt,
|
|
401
|
-
decrypt: eccryptoLib.decrypt,
|
|
402
|
-
getPublicCompressed: eccryptoLib.getPublicCompressed
|
|
403
|
-
};
|
|
404
|
-
} catch (error) {
|
|
405
|
-
throw new Error(`Failed to load eccrypto library: ${error}`);
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
return eccrypto;
|
|
409
|
-
}
|
|
415
|
+
init_lazy_import();
|
|
416
|
+
var getOpenPGP2 = lazyImport(() => import("openpgp"));
|
|
417
|
+
var getEccrypto = lazyImport(() => import("eccrypto"));
|
|
410
418
|
var NodeCryptoAdapter = class {
|
|
411
419
|
async encryptWithPublicKey(data, publicKeyHex) {
|
|
412
420
|
try {
|
|
413
|
-
const
|
|
421
|
+
const eccrypto = await getEccrypto();
|
|
414
422
|
const publicKey = Buffer.from(publicKeyHex, "hex");
|
|
415
423
|
const message = Buffer.from(data, "utf8");
|
|
416
|
-
const encrypted = await
|
|
424
|
+
const encrypted = await eccrypto.encrypt(publicKey, message);
|
|
417
425
|
const result = Buffer.concat([
|
|
418
426
|
encrypted.iv,
|
|
419
427
|
encrypted.ephemPublicKey,
|
|
@@ -427,15 +435,12 @@ var NodeCryptoAdapter = class {
|
|
|
427
435
|
}
|
|
428
436
|
async decryptWithPrivateKey(encryptedData, privateKeyHex) {
|
|
429
437
|
try {
|
|
430
|
-
const
|
|
438
|
+
const eccrypto = await getEccrypto();
|
|
431
439
|
const privateKeyBuffer = processWalletPrivateKey(privateKeyHex);
|
|
432
440
|
const encryptedBuffer = Buffer.from(encryptedData, "hex");
|
|
433
441
|
const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
|
|
434
442
|
const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
|
|
435
|
-
const decrypted = await
|
|
436
|
-
privateKeyBuffer,
|
|
437
|
-
encryptedObj
|
|
438
|
-
);
|
|
443
|
+
const decrypted = await eccrypto.decrypt(privateKeyBuffer, encryptedObj);
|
|
439
444
|
return decrypted.toString("utf8");
|
|
440
445
|
} catch (error) {
|
|
441
446
|
throw new Error(`Decryption failed: ${error}`);
|
|
@@ -443,9 +448,9 @@ var NodeCryptoAdapter = class {
|
|
|
443
448
|
}
|
|
444
449
|
async generateKeyPair() {
|
|
445
450
|
try {
|
|
446
|
-
const
|
|
447
|
-
const privateKey =
|
|
448
|
-
const publicKey =
|
|
451
|
+
const eccrypto = await getEccrypto();
|
|
452
|
+
const privateKey = eccrypto.generatePrivate();
|
|
453
|
+
const publicKey = eccrypto.getPublicCompressed(privateKey);
|
|
449
454
|
return {
|
|
450
455
|
privateKey: privateKey.toString("hex"),
|
|
451
456
|
publicKey: publicKey.toString("hex")
|
|
@@ -456,9 +461,9 @@ var NodeCryptoAdapter = class {
|
|
|
456
461
|
}
|
|
457
462
|
async encryptWithWalletPublicKey(data, publicKey) {
|
|
458
463
|
try {
|
|
459
|
-
const
|
|
464
|
+
const eccrypto = await getEccrypto();
|
|
460
465
|
const uncompressedKey = processWalletPublicKey(publicKey);
|
|
461
|
-
const encrypted = await
|
|
466
|
+
const encrypted = await eccrypto.encrypt(
|
|
462
467
|
uncompressedKey,
|
|
463
468
|
Buffer.from(data)
|
|
464
469
|
);
|
|
@@ -475,12 +480,12 @@ var NodeCryptoAdapter = class {
|
|
|
475
480
|
}
|
|
476
481
|
async decryptWithWalletPrivateKey(encryptedData, privateKey) {
|
|
477
482
|
try {
|
|
478
|
-
const
|
|
483
|
+
const eccrypto = await getEccrypto();
|
|
479
484
|
const privateKeyBuffer = processWalletPrivateKey(privateKey);
|
|
480
485
|
const encryptedBuffer = Buffer.from(encryptedData, "hex");
|
|
481
486
|
const { iv, ephemPublicKey, ciphertext, mac } = parseEncryptedDataBuffer(encryptedBuffer);
|
|
482
487
|
const encryptedObj = { iv, ephemPublicKey, ciphertext, mac };
|
|
483
|
-
const decryptedBuffer = await
|
|
488
|
+
const decryptedBuffer = await eccrypto.decrypt(
|
|
484
489
|
privateKeyBuffer,
|
|
485
490
|
encryptedObj
|
|
486
491
|
);
|
|
@@ -491,10 +496,11 @@ var NodeCryptoAdapter = class {
|
|
|
491
496
|
}
|
|
492
497
|
async encryptWithPassword(data, password) {
|
|
493
498
|
try {
|
|
494
|
-
const
|
|
499
|
+
const openpgp = await getOpenPGP2();
|
|
500
|
+
const message = await openpgp.createMessage({
|
|
495
501
|
binary: data
|
|
496
502
|
});
|
|
497
|
-
const encrypted = await
|
|
503
|
+
const encrypted = await openpgp.encrypt({
|
|
498
504
|
message,
|
|
499
505
|
passwords: [password],
|
|
500
506
|
format: "binary"
|
|
@@ -514,10 +520,11 @@ var NodeCryptoAdapter = class {
|
|
|
514
520
|
}
|
|
515
521
|
async decryptWithPassword(encryptedData, password) {
|
|
516
522
|
try {
|
|
517
|
-
const
|
|
523
|
+
const openpgp = await getOpenPGP2();
|
|
524
|
+
const message = await openpgp.readMessage({
|
|
518
525
|
binaryMessage: encryptedData
|
|
519
526
|
});
|
|
520
|
-
const { data: decrypted } = await
|
|
527
|
+
const { data: decrypted } = await openpgp.decrypt({
|
|
521
528
|
message,
|
|
522
529
|
passwords: [password],
|
|
523
530
|
format: "binary"
|
|
@@ -531,12 +538,13 @@ var NodeCryptoAdapter = class {
|
|
|
531
538
|
var NodePGPAdapter = class {
|
|
532
539
|
async encrypt(data, publicKeyArmored) {
|
|
533
540
|
try {
|
|
534
|
-
const
|
|
535
|
-
const
|
|
536
|
-
|
|
541
|
+
const openpgp = await getOpenPGP2();
|
|
542
|
+
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
|
|
543
|
+
const encrypted = await openpgp.encrypt({
|
|
544
|
+
message: await openpgp.createMessage({ text: data }),
|
|
537
545
|
encryptionKeys: publicKey,
|
|
538
546
|
config: {
|
|
539
|
-
preferredCompressionAlgorithm:
|
|
547
|
+
preferredCompressionAlgorithm: openpgp.enums.compression.zlib
|
|
540
548
|
}
|
|
541
549
|
});
|
|
542
550
|
return encrypted;
|
|
@@ -546,13 +554,14 @@ var NodePGPAdapter = class {
|
|
|
546
554
|
}
|
|
547
555
|
async decrypt(encryptedData, privateKeyArmored) {
|
|
548
556
|
try {
|
|
549
|
-
const
|
|
557
|
+
const openpgp = await getOpenPGP2();
|
|
558
|
+
const privateKey = await openpgp.readPrivateKey({
|
|
550
559
|
armoredKey: privateKeyArmored
|
|
551
560
|
});
|
|
552
|
-
const message = await
|
|
561
|
+
const message = await openpgp.readMessage({
|
|
553
562
|
armoredMessage: encryptedData
|
|
554
563
|
});
|
|
555
|
-
const { data: decrypted } = await
|
|
564
|
+
const { data: decrypted } = await openpgp.decrypt({
|
|
556
565
|
message,
|
|
557
566
|
decryptionKeys: privateKey
|
|
558
567
|
});
|
|
@@ -563,8 +572,9 @@ var NodePGPAdapter = class {
|
|
|
563
572
|
}
|
|
564
573
|
async generateKeyPair(options) {
|
|
565
574
|
try {
|
|
575
|
+
const openpgp = await getOpenPGP2();
|
|
566
576
|
const keyGenParams = getPGPKeyGenParams(options);
|
|
567
|
-
const { privateKey, publicKey } = await
|
|
577
|
+
const { privateKey, publicKey } = await openpgp.generateKey(keyGenParams);
|
|
568
578
|
return { publicKey, privateKey };
|
|
569
579
|
} catch (error) {
|
|
570
580
|
throw wrapCryptoError("PGP key generation", error);
|