@opendatalabs/vana-sdk 0.1.0-alpha.606fa2d → 0.1.0-alpha.61efc06

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 (44) hide show
  1. package/README.md +4 -13
  2. package/dist/{browser-Bb8gLWHp.d.ts → browser-DY8XDblx.d.ts} +14 -61
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +106 -723
  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 +201 -342
  19. package/dist/index.browser.js +628 -861
  20. package/dist/index.browser.js.map +1 -1
  21. package/dist/index.node.cjs +666 -1010
  22. package/dist/index.node.cjs.map +1 -1
  23. package/dist/index.node.d.cts +205 -101
  24. package/dist/index.node.d.ts +205 -101
  25. package/dist/index.node.js +668 -1024
  26. package/dist/index.node.js.map +1 -1
  27. package/dist/node.cjs +53 -692
  28. package/dist/node.cjs.map +1 -1
  29. package/dist/node.js +52 -704
  30. package/dist/node.js.map +1 -1
  31. package/dist/platform.browser.d.ts +2 -2
  32. package/dist/platform.browser.js +116 -780
  33. package/dist/platform.browser.js.map +1 -1
  34. package/dist/platform.cjs +156 -933
  35. package/dist/platform.cjs.map +1 -1
  36. package/dist/platform.js +156 -945
  37. package/dist/platform.js.map +1 -1
  38. package/dist/platform.node.cjs +156 -933
  39. package/dist/platform.node.cjs.map +1 -1
  40. package/dist/platform.node.d.cts +14 -61
  41. package/dist/platform.node.d.ts +14 -61
  42. package/dist/platform.node.js +156 -945
  43. package/dist/platform.node.js.map +1 -1
  44. package/package.json +15 -31
package/dist/node.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/platform/shared/pgp-utils.ts","../src/platform/shared/error-utils.ts","../src/platform/shared/stream-utils.ts","../src/utils/lazy-import.ts","../src/utils/encoding.ts","../src/utils/crypto-utils.ts","../src/crypto/services/WalletKeyEncryptionService.ts","../src/crypto/ecies/node.ts","../src/crypto/ecies/constants.ts","../src/crypto/ecies/interface.ts","../src/crypto/ecies/utils.ts","../src/crypto/ecies/base.ts","../src/platform/node.ts"],"sourcesContent":["/**\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 * Shared stream 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 * Convert ReadableStream to Uint8Array\n * Used primarily in Node.js environment where OpenPGP may return streams\n *\n * @param stream The ReadableStream to convert\n * @returns Promise resolving to Uint8Array containing all stream data\n */\nexport async function streamToUint8Array(\n stream: ReadableStream<Uint8Array>,\n): Promise<Uint8Array> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n // Concatenate all chunks\n const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n\n return result;\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 * Provides platform-aware encoding and decoding utilities.\n *\n * @remarks\n * This module provides consistent encoding/decoding operations across Node.js and browser\n * environments. It automatically selects the most efficient implementation based\n * on the runtime environment, using native `Buffer` in Node.js and browser APIs like\n * `btoa`/`atob` in browsers.\n *\n * @category Utilities\n */\n\n/**\n * Converts a Uint8Array to a base64 string.\n *\n * @param data - The byte array to encode into base64 format.\n * @returns The base64-encoded string representation.\n * @throws {Error} When no base64 encoding method is available in the environment.\n *\n * @example\n * ```typescript\n * const bytes = new Uint8Array([72, 101, 108, 108, 111]);\n * const encoded = toBase64(bytes);\n * console.log(encoded); // \"SGVsbG8=\"\n * ```\n */\nexport function toBase64(data: Uint8Array): string {\n // Node.js path - most efficient\n if (typeof Buffer !== \"undefined\" && Buffer.from) {\n return Buffer.from(data).toString(\"base64\");\n }\n\n // Browser path - using native btoa\n if (typeof btoa !== \"undefined\") {\n const binary = Array.from(data, (byte) => String.fromCharCode(byte)).join(\n \"\",\n );\n return btoa(binary);\n }\n\n throw new Error(\"No base64 encoding method available in this environment\");\n}\n\n/**\n * Converts a base64 string to a Uint8Array.\n *\n * @param str - The base64-encoded string to decode.\n * @returns The decoded byte array.\n * @throws {Error} When no base64 decoding method is available in the environment.\n *\n * @example\n * ```typescript\n * const decoded = fromBase64(\"SGVsbG8=\");\n * console.log(new TextDecoder().decode(decoded)); // \"Hello\"\n * ```\n */\nexport function fromBase64(str: string): Uint8Array {\n // Node.js path - most efficient\n if (typeof Buffer !== \"undefined\" && Buffer.from) {\n return new Uint8Array(Buffer.from(str, \"base64\"));\n }\n\n // Browser path - using native atob\n if (typeof atob !== \"undefined\") {\n const binary = atob(str);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n }\n\n throw new Error(\"No base64 decoding method available in this environment\");\n}\n\n/**\n * Converts a Uint8Array to a hexadecimal string.\n *\n * @param data - The byte array to encode as hexadecimal.\n * @returns The hex-encoded string (lowercase, without '0x' prefix).\n *\n * @example\n * ```typescript\n * const bytes = new Uint8Array([255, 0, 128]);\n * const hex = toHex(bytes);\n * console.log(hex); // \"ff0080\"\n * ```\n */\nexport function toHex(data: Uint8Array): string {\n // Node.js path - most efficient\n if (typeof Buffer !== \"undefined\" && Buffer.from) {\n return Buffer.from(data).toString(\"hex\");\n }\n\n // Browser path - manual conversion\n return Array.from(data, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\n/**\n * Converts a hexadecimal string to a Uint8Array.\n *\n * @param hex - The hex string to decode (with or without '0x' prefix).\n * @returns The decoded byte array.\n * @throws {Error} When the hex string has odd length or contains non-hex characters.\n *\n * @example\n * ```typescript\n * const bytes = fromHex(\"0xff0080\");\n * console.log(bytes); // Uint8Array([255, 0, 128])\n * ```\n */\nexport function fromHex(hex: string): Uint8Array {\n // Remove 0x prefix if present\n const cleanHex = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\n // Validate hex string\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string: odd length\");\n }\n\n if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {\n throw new Error(\"Invalid hex string: contains non-hex characters\");\n }\n\n // Node.js path - most efficient\n if (typeof Buffer !== \"undefined\" && Buffer.from) {\n return new Uint8Array(Buffer.from(cleanHex, \"hex\"));\n }\n\n // Browser path - manual conversion\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);\n }\n return bytes;\n}\n\n/**\n * Converts a string to a Uint8Array using UTF-8 encoding\n *\n * @param str - The string to encode\n * @returns UTF-8 encoded bytes\n */\nexport function stringToBytes(str: string): Uint8Array {\n // Node.js path - most efficient\n if (typeof Buffer !== \"undefined\" && Buffer.from) {\n return new Uint8Array(Buffer.from(str, \"utf8\"));\n }\n\n // Browser path - using TextEncoder\n if (typeof TextEncoder !== \"undefined\") {\n return new TextEncoder().encode(str);\n }\n\n // Fallback for very old browsers\n const bytes: number[] = [];\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n if (char < 0x80) {\n bytes.push(char);\n } else if (char < 0x800) {\n bytes.push(0xc0 | (char >> 6), 0x80 | (char & 0x3f));\n } else if (char < 0xd800 || char >= 0xe000) {\n bytes.push(\n 0xe0 | (char >> 12),\n 0x80 | ((char >> 6) & 0x3f),\n 0x80 | (char & 0x3f),\n );\n } else {\n // Surrogate pair\n i++;\n const char2 = str.charCodeAt(i);\n const codePoint = 0x10000 + (((char & 0x3ff) << 10) | (char2 & 0x3ff));\n bytes.push(\n 0xf0 | (codePoint >> 18),\n 0x80 | ((codePoint >> 12) & 0x3f),\n 0x80 | ((codePoint >> 6) & 0x3f),\n 0x80 | (codePoint & 0x3f),\n );\n }\n }\n return new Uint8Array(bytes);\n}\n\n/**\n * Converts a Uint8Array to a string using UTF-8 decoding\n *\n * @param bytes - The bytes to decode\n * @returns UTF-8 decoded string\n */\nexport function bytesToString(bytes: Uint8Array): string {\n // Node.js path - most efficient\n if (typeof Buffer !== \"undefined\" && Buffer.from) {\n return Buffer.from(bytes).toString(\"utf8\");\n }\n\n // Browser path - using TextDecoder\n if (typeof TextDecoder !== \"undefined\") {\n return new TextDecoder().decode(bytes);\n }\n\n // Fallback for very old browsers\n let str = \"\";\n let i = 0;\n while (i < bytes.length) {\n const byte = bytes[i];\n if (byte < 0x80) {\n str += String.fromCharCode(byte);\n i++;\n } else if ((byte & 0xe0) === 0xc0) {\n str += String.fromCharCode(((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f));\n i += 2;\n } else if ((byte & 0xf0) === 0xe0) {\n str += String.fromCharCode(\n ((byte & 0x0f) << 12) |\n ((bytes[i + 1] & 0x3f) << 6) |\n (bytes[i + 2] & 0x3f),\n );\n i += 3;\n } else {\n // 4-byte UTF-8\n const codePoint =\n (((byte & 0x07) << 18) |\n ((bytes[i + 1] & 0x3f) << 12) |\n ((bytes[i + 2] & 0x3f) << 6) |\n (bytes[i + 3] & 0x3f)) -\n 0x10000;\n str += String.fromCharCode(\n 0xd800 + (codePoint >> 10),\n 0xdc00 + (codePoint & 0x3ff),\n );\n i += 4;\n }\n }\n return str;\n}\n\n/**\n * Type guard to check if running in Node.js environment\n *\n * @returns True if running in Node.js\n */\nexport function isNodeEnvironment(): boolean {\n return (\n typeof Buffer !== \"undefined\" &&\n typeof Buffer.from === \"function\" &&\n typeof process !== \"undefined\" &&\n process.versions &&\n process.versions.node !== undefined\n );\n}\n\n/**\n * Type guard to check if running in browser environment\n *\n * @returns True if running in browser\n */\nexport function isBrowserEnvironment(): boolean {\n return (\n typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n );\n}\n","/**\n * Provides platform-agnostic cryptographic utility functions.\n *\n * @remarks\n * This module contains utility functions for cryptographic operations that work\n * consistently across Node.js and browser environments. All functions use `Uint8Array`\n * exclusively for binary data to ensure cross-platform compatibility.\n *\n * @category Cryptography\n */\n\nimport { toHex, fromHex } from \"./encoding\";\n\n/**\n * Concatenates multiple Uint8Arrays into a single array.\n *\n * @param arrays - The byte arrays to concatenate in order.\n * @returns A new Uint8Array containing all input arrays concatenated.\n *\n * @example\n * ```typescript\n * const combined = concatBytes(\n * new Uint8Array([1, 2]),\n * new Uint8Array([3, 4])\n * );\n * console.log(combined); // Uint8Array([1, 2, 3, 4])\n * ```\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n\n/**\n * Converts a hexadecimal string to a Uint8Array.\n *\n * @param hex - The hex string to convert (with or without '0x' prefix).\n * @returns The decoded byte array.\n *\n * @example\n * ```typescript\n * const bytes = hexToBytes(\"0x48656c6c6f\");\n * console.log(new TextDecoder().decode(bytes)); // \"Hello\"\n * ```\n */\nexport function hexToBytes(hex: string): Uint8Array {\n return fromHex(hex);\n}\n\n/**\n * Converts a Uint8Array to a hexadecimal string.\n *\n * @param bytes - The byte array to convert to hex.\n * @returns The hex-encoded string (lowercase, without '0x' prefix).\n *\n * @example\n * ```typescript\n * const hex = bytesToHex(new Uint8Array([72, 101, 108, 108, 111]));\n * console.log(hex); // \"48656c6c6f\"\n * ```\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return toHex(bytes);\n}\n\n/**\n * Processes a wallet public key for cryptographic operations.\n *\n * @remarks\n * Normalizes public keys to uncompressed format (65 bytes with 0x04 prefix).\n * If a 64-byte raw coordinate pair is provided, the uncompressed prefix is added.\n *\n * @param publicKey - The wallet public key as hex string or byte array.\n * @returns The normalized public key as a Uint8Array.\n *\n * @example\n * ```typescript\n * const normalized = processWalletPublicKey(\"0x04...\");\n * console.log(normalized.length); // 65 (uncompressed format)\n * ```\n */\nexport function processWalletPublicKey(\n publicKey: string | Uint8Array,\n): Uint8Array {\n const publicKeyHex =\n typeof publicKey === \"string\"\n ? publicKey.startsWith(\"0x\")\n ? publicKey.slice(2)\n : publicKey\n : bytesToHex(publicKey);\n\n const publicKeyBytes = hexToBytes(publicKeyHex);\n\n // If key is 64 bytes (raw coordinates), add uncompressed prefix\n return publicKeyBytes.length === 64\n ? concatBytes(new Uint8Array([4]), publicKeyBytes)\n : publicKeyBytes;\n}\n\n/**\n * Processes a wallet private key for cryptographic operations.\n *\n * @param privateKey - The wallet private key as hex string or byte array.\n * @returns The private key as a Uint8Array.\n *\n * @example\n * ```typescript\n * const key = processWalletPrivateKey(\"0x...\");\n * console.log(key.length); // 32 (secp256k1 private key)\n * ```\n */\nexport function processWalletPrivateKey(\n privateKey: string | Uint8Array,\n): Uint8Array {\n const privateKeyHex =\n typeof privateKey === \"string\"\n ? privateKey.startsWith(\"0x\")\n ? privateKey.slice(2)\n : privateKey\n : bytesToHex(privateKey);\n\n return hexToBytes(privateKeyHex);\n}\n\n/**\n * Parses legacy eccrypto-format encrypted data buffer.\n * Format: [iv(16)][ephemPublicKey(65)][ciphertext(variable)][mac(32)]\n *\n * @param encryptedBuffer - Buffer containing encrypted data in eccrypto format\n * @returns Parsed encrypted data components\n */\nexport function parseEncryptedDataBuffer(encryptedBuffer: Uint8Array): {\n iv: Uint8Array;\n ephemPublicKey: Uint8Array;\n ciphertext: Uint8Array;\n mac: Uint8Array;\n} {\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 * Generates a deterministic seed from a message for key derivation\n *\n * @param message - Message to derive seed from\n * @returns Seed as Uint8Array\n */\nexport function generateSeed(message: string): Uint8Array {\n // Use encoding utils for consistent string-to-bytes conversion\n const encoder = new TextEncoder();\n return encoder.encode(message);\n}\n\n/**\n * Compares two Uint8Arrays for equality\n *\n * @param a - First array\n * @param b - Second array\n * @returns True if arrays are equal\n */\nexport function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Creates a copy of a Uint8Array\n *\n * @param bytes - Array to copy\n * @returns New array with same contents\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return new Uint8Array(bytes);\n}\n\n/**\n * Validates a secp256k1 public key format\n *\n * @param publicKey - Public key to validate\n * @returns True if valid format (33, 65, or 64 bytes)\n */\nexport function isValidPublicKeyFormat(publicKey: Uint8Array): boolean {\n const len = publicKey.length;\n\n // Compressed (33 bytes)\n if (len === 33) {\n return publicKey[0] === 0x02 || publicKey[0] === 0x03;\n }\n\n // Uncompressed (65 bytes)\n if (len === 65) {\n return publicKey[0] === 0x04;\n }\n\n // Raw coordinates (64 bytes - no prefix)\n if (len === 64) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Validates a secp256k1 private key format\n *\n * @param privateKey - Private key to validate\n * @returns True if valid format (32 bytes)\n */\nexport function isValidPrivateKeyFormat(privateKey: Uint8Array): boolean {\n return privateKey.length === 32;\n}\n\n/**\n * Normalizes a public key to uncompressed format (65 bytes with 0x04 prefix)\n * Note: This only checks format, not curve validity\n *\n * @param publicKey - Public key in any format\n * @returns Normalized key or null if invalid format\n */\nexport function normalizePublicKey(publicKey: Uint8Array): Uint8Array | null {\n if (!isValidPublicKeyFormat(publicKey)) {\n return null;\n }\n\n // Already uncompressed\n if (publicKey.length === 65 && publicKey[0] === 0x04) {\n return publicKey;\n }\n\n // Raw coordinates - add prefix\n if (publicKey.length === 64) {\n return concatBytes(new Uint8Array([0x04]), publicKey);\n }\n\n // Compressed - would need curve operations to decompress\n // This should be handled by platform-specific crypto\n if (publicKey.length === 33) {\n // Return as-is, let crypto layer handle decompression\n return publicKey;\n }\n\n return null;\n}\n","/**\n * Service for wallet key encryption and decryption operations.\n *\n * @remarks\n * This service separates business logic (wallet key processing) from crypto primitives\n * (ECIES operations). It handles key normalization, data conversion, and format transformation\n * while delegating actual cryptographic operations to the provided ECIES provider.\n *\n * @category Cryptography\n * @internal\n */\n\nimport type { ECIESProvider, ECIESEncrypted } from \"../ecies/interface\";\nimport {\n processWalletPublicKey,\n processWalletPrivateKey,\n parseEncryptedDataBuffer,\n concatBytes,\n hexToBytes,\n bytesToHex,\n} from \"../../utils/crypto-utils\";\nimport { stringToBytes, bytesToString } from \"../../utils/encoding\";\n\nexport interface WalletKeyEncryptionServiceConfig {\n /** ECIES provider for encryption/decryption */\n eciesProvider: ECIESProvider;\n}\n\n/**\n * Service for wallet key encryption and decryption operations\n *\n * @remarks\n * This service encapsulates the business logic for wallet key operations,\n * delegating actual cryptographic operations to the provided ECIES provider.\n * It handles key normalization, data conversion, and format transformation.\n *\n * @internal\n */\nexport class WalletKeyEncryptionService {\n private readonly eciesProvider: ECIESProvider;\n\n constructor(config: WalletKeyEncryptionServiceConfig) {\n this.eciesProvider = config.eciesProvider;\n }\n\n /**\n * Encrypts data using a wallet's public key.\n *\n * @param data - The plaintext message to encrypt for the wallet owner.\n * @param publicKey - The recipient wallet's public key for encryption.\n * @returns A promise that resolves to the encrypted data as a hex string.\n * @throws {Error} When encryption fails due to invalid key format.\n *\n * @example\n * ```typescript\n * const encrypted = await processor.encryptWithWalletPublicKey(\n * \"Secret message\",\n * \"0x04...\" // 65-byte uncompressed public key\n * );\n * console.log(`Encrypted: ${encrypted}`);\n * ```\n */\n async encryptWithWalletPublicKey(\n data: string,\n publicKey: string | Uint8Array,\n ): Promise<string> {\n // Process the public key to ensure correct format\n const publicKeyBytes = processWalletPublicKey(publicKey);\n\n // Convert string data to bytes\n const dataBytes = stringToBytes(data);\n\n // Perform ECIES encryption\n const encrypted = await this.eciesProvider.encrypt(\n publicKeyBytes,\n dataBytes,\n );\n\n // Concatenate all components for legacy format compatibility\n const result = concatBytes(\n encrypted.iv,\n encrypted.ephemPublicKey,\n encrypted.ciphertext,\n encrypted.mac,\n );\n\n // Return as hex string for API compatibility\n return bytesToHex(result);\n }\n\n /**\n * Decrypts data using a wallet's private key.\n *\n * @param encryptedData - The hex-encoded encrypted data to decrypt.\n * @param privateKey - The wallet's private key for decryption.\n * @returns A promise that resolves to the decrypted plaintext message.\n * @throws {Error} When decryption fails due to invalid data or key format.\n *\n * @example\n * ```typescript\n * const decrypted = await processor.decryptWithWalletPrivateKey(\n * encryptedHexString,\n * \"0x...\" // 32-byte private key\n * );\n * console.log(`Decrypted: ${decrypted}`);\n * ```\n */\n async decryptWithWalletPrivateKey(\n encryptedData: string,\n privateKey: string | Uint8Array,\n ): Promise<string> {\n // Process the private key to ensure correct format\n const privateKeyBytes = processWalletPrivateKey(privateKey);\n\n // Convert hex string to bytes and parse encrypted components\n const encryptedBytes = hexToBytes(encryptedData);\n const encrypted = parseEncryptedDataBuffer(encryptedBytes);\n\n // Perform ECIES decryption\n const decrypted = await this.eciesProvider.decrypt(\n privateKeyBytes,\n encrypted,\n );\n\n // Convert bytes back to string\n return bytesToString(decrypted);\n }\n\n /**\n * Encrypts a Uint8Array with a wallet public key\n *\n * @param data - Binary data to encrypt\n * @param publicKey - Public key as hex string or Uint8Array\n * @returns Encrypted data structure\n */\n async encryptBinary(\n data: Uint8Array,\n publicKey: string | Uint8Array,\n ): Promise<ECIESEncrypted> {\n const publicKeyBytes = processWalletPublicKey(publicKey);\n return this.eciesProvider.encrypt(publicKeyBytes, data);\n }\n\n /**\n * Decrypts to a Uint8Array with a wallet private key\n *\n * @param encrypted - Encrypted data structure\n * @param privateKey - Private key as hex string or Uint8Array\n * @returns Decrypted binary data\n */\n async decryptBinary(\n encrypted: ECIESEncrypted,\n privateKey: string | Uint8Array,\n ): Promise<Uint8Array> {\n const privateKeyBytes = processWalletPrivateKey(privateKey);\n return this.eciesProvider.decrypt(privateKeyBytes, encrypted);\n }\n\n /**\n * Gets the underlying ECIES provider\n *\n * @returns The ECIES provider instance\n */\n getECIESProvider(): ECIESProvider {\n return this.eciesProvider;\n }\n}\n","/**\n * Node.js implementation of ECIES using native secp256k1 for performance\n *\n * @remarks\n * Uses native secp256k1 bindings for all elliptic curve operations.\n * Uses Node.js crypto module for hashing and AES operations.\n * Provides Uint8Array-only interface with no Buffer exposure.\n */\n\nimport {\n randomBytes,\n createHash,\n createHmac,\n createCipheriv,\n createDecipheriv,\n} from \"crypto\";\nimport { BaseECIESUint8 } from \"./base\";\n\n// Type definition for secp256k1 module\ninterface Secp256k1Module {\n privateKeyVerify(privateKey: Buffer): boolean;\n publicKeyCreate(privateKey: Buffer, compressed: boolean): Buffer;\n publicKeyVerify(publicKey: Buffer): boolean;\n publicKeyConvert(publicKey: Buffer, compressed: boolean): Buffer;\n ecdh(\n publicKey: Buffer,\n privateKey: Buffer,\n options: {\n hashfn: (x: Uint8Array, y: Uint8Array, output?: Uint8Array) => Uint8Array;\n },\n output: Buffer,\n ): Buffer;\n}\n\n// Load native secp256k1 as optional dependency\n/* global require */\n\nlet secp256k1: Secp256k1Module;\ntry {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n secp256k1 = require(\"secp256k1\");\n} catch {\n throw new Error(\n \"Native secp256k1 module not found. Please install with: npm install secp256k1\\n\" +\n \"This is required for optimal performance in Node.js environments.\",\n );\n}\n\n/**\n * Node.js-specific ECIES provider using native secp256k1\n *\n * @remarks\n * This implementation:\n * - Uses native secp256k1 for all EC operations (optimal performance)\n * - Uses Node.js crypto for SHA-512, HMAC, and AES operations\n * - Internally works with Uint8Array\n * - Only uses Buffer at crypto API boundaries\n */\nexport class NodeECIESUint8Provider extends BaseECIESUint8 {\n // Identity hash function for ECDH - returns raw X coordinate\n // CRITICAL: Must handle (x, y, output) signature correctly\n private readonly identityHashFn = (\n x: Uint8Array,\n y: Uint8Array,\n output?: Uint8Array,\n ): Uint8Array => {\n // Copy x into output buffer if provided (prevents allocations)\n if (output && output.length >= 32) {\n output.set(x);\n return output;\n }\n return x;\n };\n protected generateRandomBytes(length: number): Uint8Array {\n return new Uint8Array(randomBytes(length));\n }\n\n protected verifyPrivateKey(privateKey: Uint8Array): boolean {\n // Native secp256k1 returns true for valid, false for invalid\n return secp256k1.privateKeyVerify(Buffer.from(privateKey)) === true;\n }\n\n protected createPublicKey(\n privateKey: Uint8Array,\n compressed: boolean,\n ): Uint8Array | null {\n try {\n return new Uint8Array(\n secp256k1.publicKeyCreate(Buffer.from(privateKey), compressed),\n );\n } catch {\n return null;\n }\n }\n\n protected validatePublicKey(publicKey: Uint8Array): boolean {\n // Native secp256k1 returns true for valid, false for invalid\n return secp256k1.publicKeyVerify(Buffer.from(publicKey)) === true;\n }\n\n protected decompressPublicKey(publicKey: Uint8Array): Uint8Array | null {\n try {\n // Convert to uncompressed format (65 bytes)\n return new Uint8Array(\n secp256k1.publicKeyConvert(Buffer.from(publicKey), false),\n );\n } catch {\n return null;\n }\n }\n\n protected performECDH(\n publicKey: Uint8Array,\n privateKey: Uint8Array,\n ): Uint8Array {\n try {\n // Use pre-allocated buffer for output (32 bytes)\n const output = Buffer.alloc(32);\n\n // CRITICAL: Use identity hash to get raw X coordinate\n // Default would apply SHA256 and break compatibility\n secp256k1.ecdh(\n Buffer.from(publicKey),\n Buffer.from(privateKey),\n { hashfn: this.identityHashFn },\n output,\n );\n\n return new Uint8Array(output);\n } catch (error) {\n throw new Error(\n `ECDH failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n protected sha512(data: Uint8Array): Uint8Array {\n // Use Node.js crypto for native performance\n return new Uint8Array(\n createHash(\"sha512\").update(Buffer.from(data)).digest(),\n );\n }\n\n protected hmacSha256(key: Uint8Array, data: Uint8Array): Uint8Array {\n // Use Node.js crypto for native performance\n return new Uint8Array(\n createHmac(\"sha256\", Buffer.from(key)).update(Buffer.from(data)).digest(),\n );\n }\n\n protected async aesEncrypt(\n key: Uint8Array,\n iv: Uint8Array,\n plaintext: Uint8Array,\n ): Promise<Uint8Array> {\n const cipher = createCipheriv(\n \"aes-256-cbc\",\n Buffer.from(key),\n Buffer.from(iv),\n );\n const encrypted = Buffer.concat([\n cipher.update(Buffer.from(plaintext)),\n cipher.final(),\n ]);\n return new Uint8Array(encrypted);\n }\n\n protected async aesDecrypt(\n key: Uint8Array,\n iv: Uint8Array,\n ciphertext: Uint8Array,\n ): Promise<Uint8Array> {\n const decipher = createDecipheriv(\n \"aes-256-cbc\",\n Buffer.from(key),\n Buffer.from(iv),\n );\n const decrypted = Buffer.concat([\n decipher.update(Buffer.from(ciphertext)),\n decipher.final(),\n ]);\n return new Uint8Array(decrypted);\n }\n\n // No Buffer compatibility methods - Uint8Array only public API\n}\n","/**\n * ECIES Constants and Format Specification\n *\n * These constants define the eccrypto-compatible ECIES format used throughout the SDK.\n * Maintaining these exact values ensures backward compatibility with data encrypted\n * using the original eccrypto library.\n */\n\n/**\n * Elliptic curve parameters\n */\nexport const CURVE = {\n /** The elliptic curve used (secp256k1 - same as Bitcoin/Ethereum) */\n name: \"secp256k1\",\n /** Private key length in bytes */\n PRIVATE_KEY_LENGTH: 32,\n /** Compressed public key length in bytes (0x02 or 0x03 prefix + 32 bytes) */\n COMPRESSED_PUBLIC_KEY_LENGTH: 33,\n /** Uncompressed public key length in bytes (0x04 prefix + 64 bytes) */\n UNCOMPRESSED_PUBLIC_KEY_LENGTH: 65,\n /** ECDH shared secret X coordinate length */\n SHARED_SECRET_LENGTH: 32,\n /** Public key prefixes */\n PREFIX: {\n /** Uncompressed public key prefix */\n UNCOMPRESSED: 0x04,\n /** Compressed public key prefix for even Y */\n COMPRESSED_EVEN: 0x02,\n /** Compressed public key prefix for odd Y */\n COMPRESSED_ODD: 0x03,\n },\n /** X coordinate starts at byte 1 (after prefix) */\n X_COORDINATE_OFFSET: 1,\n /** X coordinate ends at byte 33 (1 + 32) */\n X_COORDINATE_END: 33,\n} as const;\n\n/**\n * Symmetric encryption parameters (AES-256-CBC)\n */\nexport const CIPHER = {\n /** Cipher algorithm - must match eccrypto */\n algorithm: \"aes-256-cbc\",\n /** AES key length in bytes */\n KEY_LENGTH: 32,\n /** Initialization vector length in bytes */\n IV_LENGTH: 16,\n /** Block size for AES */\n BLOCK_SIZE: 16,\n} as const;\n\n/**\n * Key derivation function parameters\n */\nexport const KDF = {\n /** Hash algorithm for key derivation - must match eccrypto */\n algorithm: \"sha512\",\n /** Output length of SHA-512 in bytes */\n OUTPUT_LENGTH: 64,\n /** Encryption key slice (first 32 bytes of KDF output) */\n ENCRYPTION_KEY_OFFSET: 0,\n ENCRYPTION_KEY_LENGTH: 32,\n /** MAC key slice (last 32 bytes of KDF output) */\n MAC_KEY_OFFSET: 32,\n MAC_KEY_LENGTH: 32,\n} as const;\n\n/**\n * Message authentication code parameters\n */\nexport const MAC = {\n /** MAC algorithm - must match eccrypto */\n algorithm: \"sha256\",\n /** HMAC-SHA256 output length in bytes */\n LENGTH: 32,\n} as const;\n\n/**\n * ECIES encrypted data format offsets and lengths\n * Format: [iv(16)][ephemPublicKey(65)][ciphertext(variable)][mac(32)]\n */\nexport const FORMAT = {\n /** Offsets for each component in serialized format */\n IV_OFFSET: 0,\n IV_LENGTH: CIPHER.IV_LENGTH,\n\n /** Ephemeral public key (always uncompressed in eccrypto format) */\n EPHEMERAL_KEY_OFFSET: CIPHER.IV_LENGTH,\n EPHEMERAL_KEY_LENGTH: CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,\n\n /** Ciphertext starts after IV and ephemeral key */\n CIPHERTEXT_OFFSET: CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,\n\n /** MAC is always the last 32 bytes */\n MAC_LENGTH: MAC.LENGTH,\n\n /** Minimum size of encrypted data (IV + ephemKey + MAC, no ciphertext) */\n MIN_ENCRYPTED_LENGTH:\n CIPHER.IV_LENGTH + CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH + MAC.LENGTH,\n\n /**\n * Helper to calculate total length of encrypted data\n *\n * @param ciphertextLength - Length of the ciphertext portion\n * @returns Total length including all components\n */\n getTotalLength: (ciphertextLength: number) =>\n CIPHER.IV_LENGTH +\n CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH +\n ciphertextLength +\n MAC.LENGTH,\n} as const;\n\n/**\n * Security constants for data clearing\n */\nexport const SECURITY = {\n /** Overwrite patterns for secure data clearing */\n CLEAR_PATTERNS: {\n ZEROS: 0x00,\n ONES: 0xff,\n /** Pattern multiplier for third pass */\n PATTERN_MULTIPLIER: 7,\n /** Pattern offset for third pass */\n PATTERN_OFFSET: 13,\n },\n} as const;\n\n/**\n * Validation helpers\n */\nexport const VALIDATION = {\n isValidPrivateKey: (key: Uint8Array): boolean =>\n key.length === CURVE.PRIVATE_KEY_LENGTH,\n\n isValidPublicKey: (key: Uint8Array): boolean =>\n key.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH ||\n key.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH,\n\n isCompressedPublicKey: (key: Uint8Array): boolean =>\n key.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH &&\n (key[0] === CURVE.PREFIX.COMPRESSED_EVEN ||\n key[0] === CURVE.PREFIX.COMPRESSED_ODD),\n\n isUncompressedPublicKey: (key: Uint8Array): boolean =>\n key.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH &&\n key[0] === CURVE.PREFIX.UNCOMPRESSED,\n} as const;\n","/**\n * ECIES (Elliptic Curve Integrated Encryption Scheme) Interface\n *\n * @remarks\n * Defines the contract for platform-specific ECIES implementations.\n * All implementations maintain compatibility with the eccrypto format to ensure\n * backward compatibility with existing encrypted data.\n *\n * **Format specification:**\n * `[iv (16 bytes)][ephemPublicKey (65 bytes)][ciphertext (variable)][mac (32 bytes)]`\n *\n * @category Cryptography\n */\n\nimport { CIPHER, CURVE, MAC, FORMAT } from \"./constants\";\n\n/**\n * Represents ECIES encrypted data in eccrypto-compatible format.\n *\n * @remarks\n * This structure maintains backward compatibility with data encrypted using\n * the legacy eccrypto library.\n */\nexport interface ECIESEncrypted {\n /** Initialization vector (16 bytes) */\n iv: Uint8Array;\n /** Ephemeral public key (65 bytes uncompressed) */\n ephemPublicKey: Uint8Array;\n /** Encrypted data */\n ciphertext: Uint8Array;\n /** Message authentication code (32 bytes) */\n mac: Uint8Array;\n}\n\n/**\n * Provides ECIES encryption and decryption operations.\n *\n * @remarks\n * Platform-specific implementations handle the underlying cryptographic primitives\n * while maintaining consistent data format across environments.\n *\n * @category Cryptography\n */\nexport interface ECIESProvider {\n /**\n * Encrypts data using ECIES with secp256k1.\n *\n * @param publicKey - Recipient's public key (65 bytes uncompressed or 33 bytes compressed).\n * Obtain via `vana.server.getIdentity(userAddress).public_key`.\n * @param message - Data to encrypt.\n * @returns Encrypted data structure compatible with eccrypto format.\n * @throws {ECIESError} When public key is invalid.\n * Verify key format matches secp256k1 requirements.\n *\n * @example\n * ```typescript\n * const encrypted = await provider.encrypt(\n * hexToBytes(publicKey),\n * new TextEncoder().encode('sensitive data')\n * );\n * ```\n */\n encrypt(publicKey: Uint8Array, message: Uint8Array): Promise<ECIESEncrypted>;\n\n /**\n * Decrypts ECIES encrypted data.\n *\n * @param privateKey - Recipient's private key (32 bytes).\n * @param encrypted - Encrypted data structure from `encrypt()` or legacy eccrypto.\n * @returns Decrypted message as Uint8Array.\n * @throws {ECIESError} When MAC verification fails.\n * Ensure the private key matches the public key used for encryption.\n *\n * @example\n * ```typescript\n * const decrypted = await provider.decrypt(\n * hexToBytes(privateKey),\n * encrypted\n * );\n * const message = new TextDecoder().decode(decrypted);\n * ```\n */\n decrypt(\n privateKey: Uint8Array,\n encrypted: ECIESEncrypted,\n ): Promise<Uint8Array>;\n}\n\n/**\n * Configures ECIES operation behavior.\n */\nexport interface ECIESOptions {\n /** Use compressed public keys (33 bytes) instead of uncompressed (65 bytes) */\n useCompressed?: boolean;\n}\n\n/**\n * Represents failures in ECIES cryptographic operations.\n *\n * @remarks\n * Provides specific error codes to help identify and recover from\n * different failure scenarios.\n *\n * @category Errors\n */\nexport class ECIESError extends Error {\n constructor(\n message: string,\n public readonly code:\n | \"INVALID_KEY\"\n | \"ENCRYPTION_FAILED\"\n | \"DECRYPTION_FAILED\"\n | \"MAC_MISMATCH\"\n | \"ECDH_FAILED\",\n public override readonly cause?: Error,\n ) {\n super(message);\n this.name = \"ECIESError\";\n }\n}\n\n/**\n * Validates if an object conforms to the ECIESEncrypted structure.\n *\n * @param obj - Object to validate.\n * @returns `true` if object is a valid ECIESEncrypted structure.\n *\n * @example\n * ```typescript\n * if (isECIESEncrypted(data)) {\n * const decrypted = await provider.decrypt(privateKey, data);\n * }\n * ```\n */\nexport function isECIESEncrypted(obj: unknown): obj is ECIESEncrypted {\n if (!obj || typeof obj !== \"object\") return false;\n const enc = obj as Record<string, unknown>;\n\n const isUint8Array = (value: unknown): value is Uint8Array => {\n return (\n value instanceof Uint8Array ||\n (typeof Buffer !== \"undefined\" && Buffer.isBuffer(value))\n );\n };\n\n return (\n isUint8Array(enc.iv) &&\n enc.iv.length === CIPHER.IV_LENGTH &&\n isUint8Array(enc.ephemPublicKey) &&\n (enc.ephemPublicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH ||\n enc.ephemPublicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) &&\n isUint8Array(enc.ciphertext) &&\n enc.ciphertext.length > 0 &&\n isUint8Array(enc.mac) &&\n enc.mac.length === MAC.LENGTH\n );\n}\n\n/**\n * Serializes ECIESEncrypted to hex string for storage or transmission.\n *\n * @param encrypted - Encrypted data structure from `encrypt()`.\n * @returns Hex string representation.\n *\n * @example\n * ```typescript\n * const hexString = serializeECIES(encrypted);\n * // Store hexString in database or send over network\n * ```\n */\nexport function serializeECIES(encrypted: ECIESEncrypted): string {\n const combined = new Uint8Array(\n encrypted.iv.length +\n encrypted.ephemPublicKey.length +\n encrypted.ciphertext.length +\n encrypted.mac.length,\n );\n\n let offset = 0;\n combined.set(encrypted.iv, offset);\n offset += encrypted.iv.length;\n combined.set(encrypted.ephemPublicKey, offset);\n offset += encrypted.ephemPublicKey.length;\n combined.set(encrypted.ciphertext, offset);\n offset += encrypted.ciphertext.length;\n combined.set(encrypted.mac, offset);\n\n return Array.from(combined)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Deserializes hex string to ECIESEncrypted structure.\n *\n * @param hex - Hex string from `serializeECIES()` or storage.\n * @returns ECIESEncrypted structure ready for decryption.\n * @throws {ECIESError} When hex string format is invalid.\n * Verify the hex string is complete and uncorrupted.\n *\n * @example\n * ```typescript\n * const encrypted = deserializeECIES(hexString);\n * const decrypted = await provider.decrypt(privateKey, encrypted);\n * ```\n */\nexport function deserializeECIES(hex: string): ECIESEncrypted {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n\n // Determine ephemPublicKey size based on prefix\n const ephemKeySize =\n bytes[FORMAT.EPHEMERAL_KEY_OFFSET] === CURVE.PREFIX.UNCOMPRESSED\n ? CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH\n : CURVE.COMPRESSED_PUBLIC_KEY_LENGTH;\n\n const minLength = FORMAT.IV_LENGTH + ephemKeySize + MAC.LENGTH + 1; // +1 for at least 1 byte of ciphertext\n if (bytes.length < minLength) {\n throw new ECIESError(\"Invalid ECIES data: too short\", \"DECRYPTION_FAILED\");\n }\n\n return {\n iv: bytes.subarray(FORMAT.IV_OFFSET, FORMAT.IV_OFFSET + FORMAT.IV_LENGTH),\n ephemPublicKey: bytes.subarray(\n FORMAT.EPHEMERAL_KEY_OFFSET,\n FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize,\n ),\n ciphertext: bytes.subarray(\n FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize,\n bytes.length - MAC.LENGTH,\n ),\n mac: bytes.subarray(bytes.length - MAC.LENGTH),\n };\n}\n","/**\n * Utility functions for ECIES operations\n *\n * Provides conversion utilities between different data formats\n * to bridge platform-specific implementations.\n */\n\n/**\n * Converts a hex string to Uint8Array\n *\n * @param hex - Hex string to convert\n * @returns Uint8Array representation of the hex string\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (hex.length % 2 !== 0) {\n throw new Error(\"Hex string must have even length\");\n }\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n return bytes;\n}\n\n/**\n * Converts Uint8Array to hex string\n *\n * @param bytes - Bytes to convert to hex\n * @returns Hex string representation\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Converts a string to Uint8Array using UTF-8 encoding\n *\n * @param str - String to convert\n * @returns UTF-8 encoded bytes\n */\nexport function stringToBytes(str: string): Uint8Array {\n return new TextEncoder().encode(str);\n}\n\n/**\n * Converts Uint8Array to string using UTF-8 decoding\n *\n * @param bytes - Bytes to decode\n * @returns Decoded UTF-8 string\n */\nexport function bytesToString(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Concatenates multiple Uint8Arrays into one\n *\n * @param arrays - Arrays to concatenate\n * @returns Concatenated Uint8Array\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n\n/**\n * Checks if two Uint8Arrays are equal in constant time\n *\n * @param a - First array to compare\n * @param b - Second array to compare\n * @returns `true` if arrays are equal\n */\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return result === 0;\n}\n\n/**\n * Converts Buffer to Uint8Array (for Node.js compatibility layer)\n * In browser, this is a no-op if already Uint8Array\n *\n * @param buffer - Buffer or Uint8Array to convert\n * @returns Uint8Array representation\n */\nexport function bufferToBytes(buffer: Buffer | Uint8Array): Uint8Array {\n if (buffer instanceof Uint8Array) {\n return buffer;\n }\n // Node.js Buffer is a subclass of Uint8Array\n return new Uint8Array(buffer);\n}\n\n/**\n * Converts Uint8Array to Buffer (for Node.js compatibility layer)\n * Only available in Node.js environment\n *\n * @param bytes - Uint8Array to convert to Buffer\n * @returns Buffer representation\n */\nexport function bytesToBuffer(bytes: Uint8Array): Buffer {\n if (typeof Buffer === \"undefined\") {\n throw new Error(\"Buffer is not available in browser environment\");\n }\n return Buffer.from(bytes);\n}\n","import type { ECIESProvider, ECIESEncrypted } from \"./interface\";\nimport { ECIESError, isECIESEncrypted } from \"./interface\";\nimport { CURVE, CIPHER, KDF } from \"./constants\";\nimport { concatBytes, constantTimeEqual } from \"./utils\";\n\n/**\n * Provides shared ECIES encryption logic across platforms using Uint8Array.\n *\n * @remarks\n * Platform implementations extend this class and provide crypto primitives.\n * The base class handles the ECIES protocol flow while maintaining\n * compatibility with the eccrypto data format.\n *\n * **Implementation details:**\n * - KDF: SHA-512(shared_secret) → encKey (32B) || macKey (32B)\n * - Cipher: AES-256-CBC with random 16-byte IV\n * - MAC: HMAC-SHA256(macKey, iv || ephemPublicKey || ciphertext)\n *\n * @category Cryptography\n */\nexport abstract class BaseECIESUint8 implements ECIESProvider {\n // Cache for validated public keys to avoid repeated validation\n private static readonly validatedKeys = new WeakMap<Uint8Array, boolean>();\n\n /**\n * Generates cryptographically secure random bytes.\n *\n * @param length - Number of random bytes to generate.\n * @returns Random bytes array.\n */\n protected abstract generateRandomBytes(length: number): Uint8Array;\n\n /**\n * Verifies a private key is valid for secp256k1.\n *\n * @param privateKey - Private key to verify (32 bytes).\n * @returns `true` if valid private key.\n */\n protected abstract verifyPrivateKey(privateKey: Uint8Array): boolean;\n\n /**\n * Creates a public key from a private key.\n *\n * @param privateKey - Source private key (32 bytes).\n * @param compressed - Generate compressed (33B) or uncompressed (65B) format.\n * @returns Public key or `null` if creation failed.\n */\n protected abstract createPublicKey(\n privateKey: Uint8Array,\n compressed: boolean,\n ): Uint8Array | null;\n\n /**\n * Validates a public key on the secp256k1 curve.\n *\n * @param publicKey - Public key to validate.\n * @returns `true` if valid public key.\n */\n protected abstract validatePublicKey(publicKey: Uint8Array): boolean;\n\n /**\n * Decompresses a compressed public key.\n *\n * @param publicKey - Compressed public key (33 bytes).\n * @returns Uncompressed public key (65 bytes) or `null` if decompression failed.\n */\n protected abstract decompressPublicKey(\n publicKey: Uint8Array,\n ): Uint8Array | null;\n\n /**\n * Performs ECDH key agreement.\n *\n * @param publicKey - Other party's public key.\n * @param privateKey - Your private key.\n * @returns Raw X coordinate of shared point (32 bytes).\n */\n protected abstract performECDH(\n publicKey: Uint8Array,\n privateKey: Uint8Array,\n ): Uint8Array;\n\n /**\n * Computes SHA-512 hash.\n *\n * @param data - Data to hash.\n * @returns SHA-512 hash (64 bytes).\n */\n protected abstract sha512(data: Uint8Array): Uint8Array;\n\n /**\n * Computes HMAC-SHA256 authentication tag.\n *\n * @param key - HMAC key.\n * @param data - Data to authenticate.\n * @returns HMAC-SHA256 (32 bytes).\n */\n protected abstract hmacSha256(key: Uint8Array, data: Uint8Array): Uint8Array;\n\n /**\n * Encrypts data using AES-256-CBC.\n *\n * @param key - Encryption key (32 bytes).\n * @param iv - Initialization vector (16 bytes).\n * @param plaintext - Data to encrypt.\n * @returns Ciphertext with PKCS#7 padding.\n */\n protected abstract aesEncrypt(\n key: Uint8Array,\n iv: Uint8Array,\n plaintext: Uint8Array,\n ): Promise<Uint8Array>;\n\n /**\n * Decrypts data using AES-256-CBC.\n *\n * @param key - Decryption key (32 bytes).\n * @param iv - Initialization vector (16 bytes).\n * @param ciphertext - Data to decrypt.\n * @returns Plaintext with padding removed.\n */\n protected abstract aesDecrypt(\n key: Uint8Array,\n iv: Uint8Array,\n ciphertext: Uint8Array,\n ): Promise<Uint8Array>;\n\n /**\n * Normalizes a public key to uncompressed format.\n *\n * @param publicKey - Public key in any format.\n * @returns Uncompressed public key (65 bytes).\n * @throws {ECIESError} If key format is invalid.\n */\n protected normalizePublicKey(publicKey: Uint8Array): Uint8Array {\n // Check cache first\n if (BaseECIESUint8.validatedKeys.has(publicKey)) {\n return publicKey;\n }\n\n if (publicKey.length === CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH) {\n if (publicKey[0] !== CURVE.PREFIX.UNCOMPRESSED) {\n throw new ECIESError(\n \"Invalid uncompressed public key prefix\",\n \"INVALID_KEY\",\n );\n }\n // Validate and cache\n if (!this.validatePublicKey(publicKey)) {\n throw new ECIESError(\"Invalid public key\", \"INVALID_KEY\");\n }\n BaseECIESUint8.validatedKeys.set(publicKey, true);\n return publicKey;\n }\n\n if (publicKey.length === CURVE.COMPRESSED_PUBLIC_KEY_LENGTH) {\n const decompressed = this.decompressPublicKey(publicKey);\n if (!decompressed) {\n throw new ECIESError(\"Failed to decompress public key\", \"INVALID_KEY\");\n }\n // Cache the decompressed key\n BaseECIESUint8.validatedKeys.set(decompressed, true);\n return decompressed;\n }\n\n throw new ECIESError(\n `Invalid public key length: ${publicKey.length}`,\n \"INVALID_KEY\",\n );\n }\n\n /**\n * Encrypts data using ECIES.\n *\n * @param publicKey - The recipient's public key (compressed or uncompressed)\n * @param message - The data to encrypt\n * @returns Promise resolving to encrypted data structure\n */\n async encrypt(\n publicKey: Uint8Array,\n message: Uint8Array,\n ): Promise<ECIESEncrypted> {\n try {\n // Validate inputs\n if (!(publicKey instanceof Uint8Array)) {\n throw new ECIESError(\"Public key must be a Uint8Array\", \"INVALID_KEY\");\n }\n if (!(message instanceof Uint8Array)) {\n throw new ECIESError(\n \"Message must be a Uint8Array\",\n \"ENCRYPTION_FAILED\",\n );\n }\n if (publicKey.length === 0) {\n throw new ECIESError(\"Public key cannot be empty\", \"INVALID_KEY\");\n }\n\n // Normalize public key to uncompressed format\n const pubKey = this.normalizePublicKey(publicKey);\n\n // Generate ephemeral key pair\n let ephemeralPrivateKey: Uint8Array;\n do {\n ephemeralPrivateKey = this.generateRandomBytes(\n CURVE.PRIVATE_KEY_LENGTH,\n );\n } while (!this.verifyPrivateKey(ephemeralPrivateKey));\n\n const ephemeralPublicKey = this.createPublicKey(\n ephemeralPrivateKey,\n false,\n );\n if (!ephemeralPublicKey) {\n throw new ECIESError(\n \"Failed to generate ephemeral public key\",\n \"ENCRYPTION_FAILED\",\n );\n }\n\n // Perform ECDH to get shared secret (raw X coordinate)\n const sharedSecret = this.performECDH(pubKey, ephemeralPrivateKey);\n\n // Derive keys using SHA-512 (eccrypto-compatible KDF)\n const kdf = this.sha512(sharedSecret);\n const encryptionKey = kdf.slice(\n KDF.ENCRYPTION_KEY_OFFSET,\n KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH,\n );\n const macKey = kdf.slice(\n KDF.MAC_KEY_OFFSET,\n KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH,\n );\n\n // Generate random IV and encrypt\n const iv = this.generateRandomBytes(CIPHER.IV_LENGTH);\n const ciphertext = await this.aesEncrypt(encryptionKey, iv, message);\n\n // Calculate MAC (Encrypt-then-MAC)\n const macData = concatBytes(iv, ephemeralPublicKey, ciphertext);\n const mac = this.hmacSha256(macKey, macData);\n\n // Clear sensitive data\n this.clearBuffer(ephemeralPrivateKey);\n this.clearBuffer(sharedSecret);\n this.clearBuffer(kdf);\n\n return {\n iv,\n ephemPublicKey: ephemeralPublicKey,\n ciphertext,\n mac,\n };\n } catch (error) {\n if (error instanceof ECIESError) throw error;\n throw new ECIESError(\n `Encryption failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"ENCRYPTION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Decrypts ECIES encrypted data.\n *\n * @param privateKey - The recipient's private key (32 bytes)\n * @param encrypted - The encrypted data structure from encrypt()\n * @returns Promise resolving to the original plaintext\n */\n async decrypt(\n privateKey: Uint8Array,\n encrypted: ECIESEncrypted,\n ): Promise<Uint8Array> {\n try {\n // Validate inputs\n if (!(privateKey instanceof Uint8Array)) {\n throw new ECIESError(\"Private key must be a Uint8Array\", \"INVALID_KEY\");\n }\n if (!isECIESEncrypted(encrypted)) {\n throw new ECIESError(\n \"Invalid encrypted data structure\",\n \"DECRYPTION_FAILED\",\n );\n }\n if (privateKey.length !== CURVE.PRIVATE_KEY_LENGTH) {\n throw new ECIESError(\n `Invalid private key length: ${privateKey.length}`,\n \"INVALID_KEY\",\n );\n }\n if (!this.verifyPrivateKey(privateKey)) {\n throw new ECIESError(\"Invalid private key\", \"INVALID_KEY\");\n }\n\n // Normalize ephemeral public key to uncompressed format\n const ephemeralPublicKey = this.normalizePublicKey(\n encrypted.ephemPublicKey,\n );\n\n // Perform ECDH to recover shared secret\n const sharedSecret = this.performECDH(ephemeralPublicKey, privateKey);\n\n // Derive keys using SHA-512 (eccrypto-compatible KDF)\n const kdf = this.sha512(sharedSecret);\n const encryptionKey = kdf.slice(\n KDF.ENCRYPTION_KEY_OFFSET,\n KDF.ENCRYPTION_KEY_OFFSET + KDF.ENCRYPTION_KEY_LENGTH,\n );\n const macKey = kdf.slice(\n KDF.MAC_KEY_OFFSET,\n KDF.MAC_KEY_OFFSET + KDF.MAC_KEY_LENGTH,\n );\n\n // Verify MAC before decryption (Encrypt-then-MAC)\n const macData = concatBytes(\n encrypted.iv,\n encrypted.ephemPublicKey,\n encrypted.ciphertext,\n );\n const expectedMac = this.hmacSha256(macKey, macData);\n\n if (!constantTimeEqual(encrypted.mac, expectedMac)) {\n throw new ECIESError(\"MAC verification failed\", \"MAC_MISMATCH\");\n }\n\n // Decrypt the ciphertext\n const decrypted = await this.aesDecrypt(\n encryptionKey,\n encrypted.iv,\n encrypted.ciphertext,\n );\n\n // Clear sensitive data\n this.clearBuffer(sharedSecret);\n this.clearBuffer(kdf);\n\n return decrypted;\n } catch (error) {\n if (error instanceof ECIESError) throw error;\n throw new ECIESError(\n `Decryption failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"DECRYPTION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Clears sensitive data from memory using multi-pass overwrite.\n *\n * @remarks\n * Uses multiple passes with different patterns to make it harder\n * for JIT compilers to optimize away the operation. While not\n * guaranteed in JavaScript, this is a best-effort approach to\n * clear sensitive data from memory.\n *\n * @param buffer - The buffer to clear\n */\n protected clearBuffer(buffer: Uint8Array): void {\n if (buffer && buffer.length > 0) {\n // Multi-pass overwrite to resist compiler optimization\n buffer.fill(0x00); // Fill with zeros\n buffer.fill(0xff); // Fill with ones\n buffer.fill(0xaa); // Fill with alternating pattern\n buffer.fill(0x00); // Final zero fill\n\n // Additional pattern write to further discourage optimization\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = (i & 0xff) ^ 0x5a; // XOR with pattern\n }\n buffer.fill(0x00); // Final clear\n }\n }\n}\n","/**\n * Node.js implementation of the Vana Platform Adapter\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 { getPGPKeyGenParams } from \"./shared/pgp-utils\";\nimport { wrapCryptoError } from \"./shared/error-utils\";\nimport { streamToUint8Array } from \"./shared/stream-utils\";\nimport { lazyImport } from \"../utils/lazy-import\";\nimport { WalletKeyEncryptionService } from \"../crypto/services/WalletKeyEncryptionService\";\nimport {\n processWalletPrivateKey,\n parseEncryptedDataBuffer,\n} from \"../utils/crypto-utils\";\n\n// Lazy-loaded dependencies to avoid Turbopack TDZ issues\nconst getOpenPGP = lazyImport(() => import(\"openpgp\"));\n\n// Import native ECIES provider and error types\nimport { NodeECIESUint8Provider } from \"../crypto/ecies/node\";\nimport { ECIESError } from \"../crypto/ecies/interface\";\nimport type { ECIESEncrypted } from \"../crypto/ecies\";\n\n/**\n * Node.js implementation of crypto operations using native secp256k1\n */\nclass NodeCryptoAdapter implements VanaCryptoAdapter {\n private eciesProvider = new NodeECIESUint8Provider();\n private walletKeyEncryptionService = new WalletKeyEncryptionService({\n eciesProvider: this.eciesProvider,\n });\n\n async encryptWithPublicKey(\n data: string,\n publicKeyHex: string,\n ): Promise<string> {\n try {\n const publicKey = Buffer.from(publicKeyHex, \"hex\");\n const message = Buffer.from(data, \"utf8\");\n\n const encrypted = await this.eciesProvider.encrypt(publicKey, message);\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 if (error instanceof ECIESError) {\n throw error;\n }\n throw new ECIESError(\n `Encryption failed: ${error instanceof Error ? error.message : String(error)}`,\n \"ENCRYPTION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n async decryptWithPrivateKey(\n encryptedData: string,\n privateKeyHex: string,\n ): Promise<string> {\n try {\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\n const encryptedObj: ECIESEncrypted = {\n iv,\n ephemPublicKey,\n ciphertext,\n mac,\n };\n\n const decrypted = await this.eciesProvider.decrypt(\n privateKeyBuffer,\n encryptedObj,\n );\n return new TextDecoder().decode(decrypted);\n } catch (error) {\n if (error instanceof ECIESError) {\n throw error;\n }\n throw new ECIESError(\n `Decryption failed: ${error instanceof Error ? error.message : String(error)}`,\n \"DECRYPTION_FAILED\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n async generateKeyPair(): Promise<{ publicKey: string; privateKey: string }> {\n try {\n const { randomBytes } = await import(\"crypto\");\n const secp256k1 = await import(\"secp256k1\");\n\n // Generate private key\n let privateKey: Buffer;\n do {\n privateKey = randomBytes(32);\n } while (!secp256k1.privateKeyVerify(privateKey));\n\n // Get compressed public key\n const publicKey = Buffer.from(\n secp256k1.publicKeyCreate(privateKey, true),\n );\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 return await this.walletKeyEncryptionService.encryptWithWalletPublicKey(\n data,\n publicKey,\n );\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 return await this.walletKeyEncryptionService.decryptWithWalletPrivateKey(\n encryptedData,\n privateKey,\n );\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 const openpgp = await getOpenPGP();\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 // In Node.js, the encrypted result is already a Uint8Array\n if (encrypted instanceof Uint8Array) {\n return encrypted;\n }\n\n // If it's a stream (should not happen with format: \"binary\"), read it\n if (\n encrypted &&\n typeof encrypted === \"object\" &&\n \"getReader\" in encrypted\n ) {\n return await streamToUint8Array(\n encrypted as ReadableStream<Uint8Array>,\n );\n }\n\n throw new Error(\"Unexpected encrypted data format\");\n } catch (error) {\n throw wrapCryptoError(\"encrypt with password\", error);\n }\n }\n\n async decryptWithPassword(\n encryptedData: Uint8Array,\n password: string,\n ): Promise<Uint8Array> {\n try {\n const openpgp = await getOpenPGP();\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 wrapCryptoError(\"decrypt with password\", error);\n }\n }\n}\n\n/**\n * Node.js implementation of PGP operations using openpgp with Node-specific configuration\n */\nclass NodePGPAdapter 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 wrapCryptoError(\"PGP encryption\", 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 wrapCryptoError(\"PGP decryption\", 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 * Node.js implementation of HTTP operations using node-fetch or native fetch\n */\nclass NodeHttpAdapter implements VanaHttpAdapter {\n async fetch(url: string, options?: RequestInit): Promise<Response> {\n if (typeof globalThis.fetch !== \"undefined\") {\n return globalThis.fetch(url, options);\n }\n\n throw new Error(\"No fetch implementation available in Node.js environment\");\n }\n}\n\n/**\n * Node.js implementation of cache operations using in-memory Map with TTL\n */\nclass NodeCacheAdapter implements VanaCacheAdapter {\n private cache = new Map<string, { value: string; expires: number }>();\n private readonly defaultTtl = 2 * 60 * 60 * 1000; // 2 hours in milliseconds\n\n get(key: string): string | null {\n const entry = this.cache.get(key);\n if (!entry) {\n return null;\n }\n\n // Check if expired\n if (Date.now() > entry.expires) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.value;\n }\n\n set(key: string, value: string): void {\n this.cache.set(key, {\n value,\n expires: Date.now() + this.defaultTtl,\n });\n }\n\n delete(key: string): void {\n this.cache.delete(key);\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n\n/**\n * Complete Node.js platform adapter implementation\n */\nexport class NodePlatformAdapter implements VanaPlatformAdapter {\n crypto: VanaCryptoAdapter;\n pgp: VanaPGPAdapter;\n http: VanaHttpAdapter;\n cache: VanaCacheAdapter;\n platform: \"node\" = \"node\" as const;\n\n constructor() {\n this.crypto = new NodeCryptoAdapter();\n this.pgp = new NodePGPAdapter();\n this.http = new NodeHttpAdapter();\n this.cache = new NodeCacheAdapter();\n }\n}\n\n/**\n * Default instance export for backwards compatibility\n */\nexport const nodePlatformAdapter: VanaPlatformAdapter =\n new NodePlatformAdapter();\n"],"mappings":";;;;;;;;AAWO,IAAM,sBAAsB;AAAA,EACjC,+BAA+B;AAAA;AAAA,EAC/B,6BAA6B;AAAA;AAC/B;AAWO,SAAS,qBAAqB,SAIlC;AACD,SAAO;AAAA,IACL,MAAM,SAAS,QAAQ;AAAA,IACvB,OAAO,SAAS,SAAS;AAAA,IACzB,YAAY,SAAS;AAAA,EACvB;AACF;AAYO,SAAS,mBAAmB,SAIhC;AACD,QAAM,EAAE,MAAM,OAAO,WAAW,IAAI,qBAAqB,OAAO;AAEhE,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,SAAS,C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EACA;AAAA,EACA,WAAmB;AAAA,EAEnB,cAAc;AACZ,SAAK,SAAS,IAAI,kBAAkB;AACpC,SAAK,MAAM,IAAI,eAAe;AAC9B,SAAK,OAAO,IAAI,gBAAgB;AAChC,SAAK,QAAQ,IAAI,iBAAiB;AAAA,EACpC;AACF;AAKO,IAAM,sBACX,IAAI,oBAAoB;","names":["concatBytes","concatBytes","randomBytes","secp256k1"]}
1
+ {"version":3,"sources":["../src/platform/shared/crypto-utils.ts","../src/platform/shared/pgp-utils.ts","../src/platform/shared/error-utils.ts","../src/platform/shared/stream-utils.ts","../src/utils/lazy-import.ts","../src/platform/node.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 * Shared stream 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 * Convert ReadableStream to Uint8Array\n * Used primarily in Node.js environment where OpenPGP may return streams\n *\n * @param stream The ReadableStream to convert\n * @returns Promise resolving to Uint8Array containing all stream data\n */\nexport async function streamToUint8Array(\n stream: ReadableStream<Uint8Array>,\n): Promise<Uint8Array> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n // Concatenate all chunks\n const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n\n return result;\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 * Node.js implementation of the Vana Platform Adapter\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 { streamToUint8Array } from \"./shared/stream-utils\";\nimport { lazyImport } from \"../utils/lazy-import\";\n\n// Lazy-loaded dependencies to avoid Turbopack TDZ issues\nconst getOpenPGP = lazyImport(() => import(\"openpgp\"));\nconst getEccrypto = lazyImport(() => import(\"eccrypto\"));\n\n/**\n * Node.js implementation of crypto operations using secp256k1\n */\nclass NodeCryptoAdapter implements VanaCryptoAdapter {\n async encryptWithPublicKey(\n data: string,\n publicKeyHex: string,\n ): Promise<string> {\n try {\n const eccrypto = await getEccrypto();\n const publicKey = Buffer.from(publicKeyHex, \"hex\");\n const message = Buffer.from(data, \"utf8\");\n\n const encrypted = await eccrypto.encrypt(publicKey, message);\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 const eccrypto = await getEccrypto();\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 const decrypted = await eccrypto.decrypt(privateKeyBuffer, encryptedObj);\n return decrypted.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 const eccrypto = await getEccrypto();\n const privateKey = eccrypto.generatePrivate();\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 const eccrypto = await getEccrypto();\n\n // Use shared utility to process public key\n const uncompressedKey = processWalletPublicKey(publicKey);\n\n const encrypted = await eccrypto.encrypt(\n uncompressedKey,\n Buffer.from(data),\n );\n\n // Concatenate all components and return as hex (same format as browser)\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 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 const eccrypto = await getEccrypto();\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 const openpgp = await getOpenPGP();\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 // In Node.js, the encrypted result is already a Uint8Array\n if (encrypted instanceof Uint8Array) {\n return encrypted;\n }\n\n // If it's a stream (should not happen with format: \"binary\"), read it\n if (\n encrypted &&\n typeof encrypted === \"object\" &&\n \"getReader\" in encrypted\n ) {\n return await streamToUint8Array(\n encrypted as ReadableStream<Uint8Array>,\n );\n }\n\n throw new Error(\"Unexpected encrypted data format\");\n } catch (error) {\n throw wrapCryptoError(\"encrypt with password\", error);\n }\n }\n\n async decryptWithPassword(\n encryptedData: Uint8Array,\n password: string,\n ): Promise<Uint8Array> {\n try {\n const openpgp = await getOpenPGP();\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 wrapCryptoError(\"decrypt with password\", error);\n }\n }\n}\n\n/**\n * Node.js implementation of PGP operations using openpgp with Node-specific configuration\n */\nclass NodePGPAdapter 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 wrapCryptoError(\"PGP encryption\", 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 wrapCryptoError(\"PGP decryption\", 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 * Node.js implementation of HTTP operations using node-fetch or native fetch\n */\nclass NodeHttpAdapter implements VanaHttpAdapter {\n async fetch(url: string, options?: RequestInit): Promise<Response> {\n if (typeof globalThis.fetch !== \"undefined\") {\n return globalThis.fetch(url, options);\n }\n\n throw new Error(\"No fetch implementation available in Node.js environment\");\n }\n}\n\n/**\n * Node.js implementation of cache operations using in-memory Map with TTL\n */\nclass NodeCacheAdapter implements VanaCacheAdapter {\n private cache = new Map<string, { value: string; expires: number }>();\n private readonly defaultTtl = 2 * 60 * 60 * 1000; // 2 hours in milliseconds\n\n get(key: string): string | null {\n const entry = this.cache.get(key);\n if (!entry) {\n return null;\n }\n\n // Check if expired\n if (Date.now() > entry.expires) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.value;\n }\n\n set(key: string, value: string): void {\n this.cache.set(key, {\n value,\n expires: Date.now() + this.defaultTtl,\n });\n }\n\n delete(key: string): void {\n this.cache.delete(key);\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n\n/**\n * Complete Node.js platform adapter implementation\n */\nexport class NodePlatformAdapter implements VanaPlatformAdapter {\n crypto: VanaCryptoAdapter;\n pgp: VanaPGPAdapter;\n http: VanaHttpAdapter;\n cache: VanaCacheAdapter;\n platform: \"node\" = \"node\" as const;\n\n constructor() {\n this.crypto = new NodeCryptoAdapter();\n this.pgp = new NodePGPAdapter();\n this.http = new NodeHttpAdapter();\n this.cache = new NodeCacheAdapter();\n }\n}\n\n/**\n * Default instance export for backwards compatibility\n */\nexport const nodePlatformAdapter: VanaPlatformAdapter =\n new NodePlatformAdapter();\n"],"mappings":";AAcO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ACX,IAAI,oBAAoB;","names":[]}
@@ -1,5 +1,5 @@
1
- import { V as VanaPlatformAdapter, P as PlatformType } from './browser-Bb8gLWHp.js';
2
- export { B as BrowserPlatformAdapter } from './browser-Bb8gLWHp.js';
1
+ import { V as VanaPlatformAdapter, P as PlatformType } from './browser-DY8XDblx.js';
2
+ export { B as BrowserPlatformAdapter } from './browser-DY8XDblx.js';
3
3
 
4
4
  /**
5
5
  * Browser-only exports for platform adapters