@opendatalabs/vana-sdk 0.1.0-alpha.05e94f6 → 0.1.0-alpha.1bbb6d4

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.
@@ -220,6 +220,10 @@ interface VanaPlatformAdapter {
220
220
  *
221
221
  * This implementation uses browser-compatible libraries and configurations
222
222
  * to provide crypto, PGP, and HTTP functionality without Node.js dependencies.
223
+ *
224
+ * WARNING: Dependencies that access globals during init
225
+ * MUST be dynamically imported to support Turbopack.
226
+ * See: https://github.com/vercel/next.js/issues/82632
223
227
  */
224
228
 
225
229
  /**
package/dist/browser.d.ts CHANGED
@@ -1 +1 @@
1
- export { B as BrowserPlatformAdapter } from './browser-cRpdLQ3-.js';
1
+ export { B as BrowserPlatformAdapter } from './browser-DY8XDblx.js';
package/dist/browser.js CHANGED
@@ -2,9 +2,6 @@ var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
4
 
5
- // src/platform/browser.ts
6
- import * as openpgp from "openpgp";
7
-
8
5
  // src/platform/shared/crypto-utils.ts
9
6
  function processWalletPublicKey(publicKey) {
10
7
  const publicKeyHex = publicKey.startsWith("0x") ? publicKey.slice(2) : publicKey;
@@ -56,7 +53,22 @@ function wrapCryptoError(operation, error) {
56
53
  return new Error(`${operation} failed: ${message}`);
57
54
  }
58
55
 
56
+ // src/utils/lazy-import.ts
57
+ function lazyImport(importFn) {
58
+ let cached = null;
59
+ return () => {
60
+ if (!cached) {
61
+ cached = importFn().catch((err) => {
62
+ cached = null;
63
+ throw new Error("Failed to load module", { cause: err });
64
+ });
65
+ }
66
+ return cached;
67
+ };
68
+ }
69
+
59
70
  // src/platform/browser.ts
71
+ var getOpenPGP = lazyImport(() => import("openpgp"));
60
72
  var BrowserCryptoAdapter = class {
61
73
  async encryptWithPublicKey(data, publicKeyHex) {
62
74
  try {
@@ -145,11 +157,11 @@ var BrowserCryptoAdapter = class {
145
157
  }
146
158
  async encryptWithPassword(data, password) {
147
159
  try {
148
- const openpgp2 = await import("openpgp");
149
- const message = await openpgp2.createMessage({
160
+ const openpgp = await getOpenPGP();
161
+ const message = await openpgp.createMessage({
150
162
  binary: data
151
163
  });
152
- const encrypted = await openpgp2.encrypt({
164
+ const encrypted = await openpgp.encrypt({
153
165
  message,
154
166
  passwords: [password],
155
167
  format: "binary"
@@ -163,11 +175,11 @@ var BrowserCryptoAdapter = class {
163
175
  }
164
176
  async decryptWithPassword(encryptedData, password) {
165
177
  try {
166
- const openpgp2 = await import("openpgp");
167
- const message = await openpgp2.readMessage({
178
+ const openpgp = await getOpenPGP();
179
+ const message = await openpgp.readMessage({
168
180
  binaryMessage: encryptedData
169
181
  });
170
- const { data: decrypted } = await openpgp2.decrypt({
182
+ const { data: decrypted } = await openpgp.decrypt({
171
183
  message,
172
184
  passwords: [password],
173
185
  format: "binary"
@@ -181,6 +193,7 @@ var BrowserCryptoAdapter = class {
181
193
  var BrowserPGPAdapter = class {
182
194
  async encrypt(data, publicKeyArmored) {
183
195
  try {
196
+ const openpgp = await getOpenPGP();
184
197
  const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
185
198
  const encrypted = await openpgp.encrypt({
186
199
  message: await openpgp.createMessage({ text: data }),
@@ -196,6 +209,7 @@ var BrowserPGPAdapter = class {
196
209
  }
197
210
  async decrypt(encryptedData, privateKeyArmored) {
198
211
  try {
212
+ const openpgp = await getOpenPGP();
199
213
  const privateKey = await openpgp.readPrivateKey({
200
214
  armoredKey: privateKeyArmored
201
215
  });
@@ -213,6 +227,7 @@ var BrowserPGPAdapter = class {
213
227
  }
214
228
  async generateKeyPair(options) {
215
229
  try {
230
+ const openpgp = await getOpenPGP();
216
231
  const keyGenParams = getPGPKeyGenParams(options);
217
232
  const { privateKey, publicKey } = await openpgp.generateKey(keyGenParams);
218
233
  return { publicKey, privateKey };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/platform/browser.ts","../src/platform/shared/crypto-utils.ts","../src/platform/shared/pgp-utils.ts","../src/platform/shared/error-utils.ts"],"sourcesContent":["/**\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 * 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"],"mappings":";;;;;AAOA,YAAY,aAAa;;;ACOlB,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,gBAAgB,MAAM,IAAI,GAAG;AAAA,IACzC,KAAK,gBAAgB,MAAM,GAAG;AAAA,EAChC;AACF;;;AC5CO,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,MAA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AAAA,EAEA,IAAI,KAAa,OAAqB;AACpC,QAAI;AACF,UAAI,OAAO,mBAAmB,aAAa;AACzC,uBAAe,QAAQ,KAAK,SAAS,KAAK,KAAK;AAAA,MACjD;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AAAA,EAEA,OAAO,KAAmB;AACxB,QAAI;AACF,UAAI,OAAO,mBAAmB,aAAa;AACzC,uBAAe,WAAW,KAAK,SAAS,GAAG;AAAA,MAC7C;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AAAA,EAEA,QAAc;AACZ,QAAI;AACF,UAAI,OAAO,mBAAmB,aAAa;AACzC;AAAA,MACF;AAEA,YAAM,OAAO,OAAO,KAAK,cAAc;AACvC,iBAAW,OAAO,MAAM;AACtB,YAAI,IAAI,WAAW,KAAK,MAAM,GAAG;AAC/B,yBAAe,WAAW,GAAG;AAAA,QAC/B;AAAA,MACF;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAKO,IAAM,yBAAN,MAA4D;AAAA,EAOjE,cAAc;AANd;AACA;AACA;AACA;AACA,oCAAsB;AAGpB,SAAK,SAAS,IAAI,qBAAqB;AACvC,SAAK,MAAM,IAAI,kBAAkB;AACjC,SAAK,OAAO,IAAI,mBAAmB;AACnC,SAAK,QAAQ,IAAI,oBAAoB;AAAA,EACvC;AACF;AAKO,IAAM,yBACX,IAAI,uBAAuB;","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"],"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"],"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,gBAAgB,MAAM,IAAI,GAAG;AAAA,IACzC,KAAK,gBAAgB,MAAM,GAAG;AAAA,EAChC;AACF;;;AC5CO,IAAM,sBAAsB;AAAA,EACjC,+BAA+B;AA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/B,yBAAe,WAAW,GAAG;AAAA,QAC/B;AAAA,MACF;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAKO,IAAM,yBAAN,MAA4D;AAAA,EAOjE,cAAc;AANd;AACA;AACA;AACA;AACA,oCAAsB;AAGpB,SAAK,SAAS,IAAI,qBAAqB;AACvC,SAAK,MAAM,IAAI,kBAAkB;AACjC,SAAK,OAAO,IAAI,mBAAmB;AACnC,SAAK,QAAQ,IAAI,oBAAoB;AAAA,EACvC;AACF;AAKO,IAAM,yBACX,IAAI,uBAAuB;","names":[]}
@@ -157,6 +157,14 @@ declare class StorageError extends Error {
157
157
  });
158
158
  }
159
159
 
160
+ /**
161
+ * Base interface for types that need to be compatible with Record<string, unknown>
162
+ *
163
+ * @category Permissions
164
+ */
165
+ interface RecordCompatible {
166
+ [key: string]: unknown;
167
+ }
160
168
  /**
161
169
  * Represents on-chain permission grant data without expensive off-chain resolution.
162
170
  *
@@ -355,7 +363,7 @@ interface PermissionGrantMessage {
355
363
  *
356
364
  * @category Permissions
357
365
  */
358
- interface PermissionInputMessage {
366
+ interface PermissionInputMessage extends RecordCompatible {
359
367
  /** Nonce */
360
368
  nonce: bigint;
361
369
  /** Grantee ID */
@@ -370,7 +378,7 @@ interface PermissionInputMessage {
370
378
  *
371
379
  * @category Permissions
372
380
  */
373
- interface RevokePermissionInput {
381
+ interface RevokePermissionInput extends RecordCompatible {
374
382
  /** Nonce */
375
383
  nonce: bigint;
376
384
  /** Permission ID to revoke */
@@ -451,9 +459,7 @@ interface GrantFile {
451
459
  *
452
460
  * @category Permissions
453
461
  */
454
- interface PermissionGrantTypedData {
455
- /** EIP-712 domain */
456
- domain: PermissionGrantDomain;
462
+ interface PermissionGrantTypedData extends GenericTypedData {
457
463
  /** EIP-712 types */
458
464
  types: {
459
465
  Permission: Array<{
@@ -471,7 +477,7 @@ interface PermissionGrantTypedData {
471
477
  *
472
478
  * @category Permissions
473
479
  */
474
- interface GenericTypedData {
480
+ interface GenericTypedData extends RecordCompatible {
475
481
  /** EIP-712 domain */
476
482
  domain: PermissionGrantDomain;
477
483
  /** EIP-712 types */
@@ -665,7 +671,7 @@ interface UntrustServerParams {
665
671
  *
666
672
  * @category Permissions
667
673
  */
668
- interface AddAndTrustServerInput {
674
+ interface AddAndTrustServerInput extends RecordCompatible {
669
675
  /** User nonce */
670
676
  nonce: bigint;
671
677
  /** Server address */
@@ -681,7 +687,7 @@ interface AddAndTrustServerInput {
681
687
  * @category Permissions
682
688
  * @deprecated Use AddAndTrustServerInput instead
683
689
  */
684
- interface TrustServerInput {
690
+ interface TrustServerInput extends RecordCompatible {
685
691
  /** User nonce */
686
692
  nonce: bigint;
687
693
  /** Server ID (numeric) */
@@ -692,7 +698,7 @@ interface TrustServerInput {
692
698
  *
693
699
  * @category Permissions
694
700
  */
695
- interface UntrustServerInput {
701
+ interface UntrustServerInput extends RecordCompatible {
696
702
  /** User nonce */
697
703
  nonce: bigint;
698
704
  /** Server ID (numeric) */
@@ -703,9 +709,7 @@ interface UntrustServerInput {
703
709
  *
704
710
  * @category Permissions
705
711
  */
706
- interface AddAndTrustServerTypedData {
707
- /** EIP-712 domain */
708
- domain: PermissionGrantDomain;
712
+ interface AddAndTrustServerTypedData extends GenericTypedData {
709
713
  /** EIP-712 types */
710
714
  types: {
711
715
  AddServer: Array<{
@@ -724,9 +728,7 @@ interface AddAndTrustServerTypedData {
724
728
  * @category Permissions
725
729
  * @deprecated Use AddAndTrustServerTypedData instead
726
730
  */
727
- interface TrustServerTypedData {
728
- /** EIP-712 domain */
729
- domain: PermissionGrantDomain;
731
+ interface TrustServerTypedData extends GenericTypedData {
730
732
  /** EIP-712 types */
731
733
  types: {
732
734
  TrustServer: Array<{
@@ -744,9 +746,7 @@ interface TrustServerTypedData {
744
746
  *
745
747
  * @category Permissions
746
748
  */
747
- interface UntrustServerTypedData {
748
- /** EIP-712 domain */
749
- domain: PermissionGrantDomain;
749
+ interface UntrustServerTypedData extends GenericTypedData {
750
750
  /** EIP-712 types */
751
751
  types: {
752
752
  UntrustServer: Array<{
@@ -903,7 +903,7 @@ interface RegisterGranteeParams {
903
903
  *
904
904
  * @category Permissions
905
905
  */
906
- interface RegisterGranteeInput extends Record<string, unknown> {
906
+ interface RegisterGranteeInput extends RecordCompatible {
907
907
  /** User nonce */
908
908
  nonce: bigint;
909
909
  /** Grantee owner address */
@@ -918,9 +918,7 @@ interface RegisterGranteeInput extends Record<string, unknown> {
918
918
  *
919
919
  * @category Permissions
920
920
  */
921
- interface RegisterGranteeTypedData {
922
- /** EIP-712 domain */
923
- domain: PermissionGrantDomain;
921
+ interface RegisterGranteeTypedData extends GenericTypedData {
924
922
  /** EIP-712 types */
925
923
  types: {
926
924
  RegisterGrantee: Array<{
@@ -33814,66 +33812,6 @@ declare class DataController {
33814
33812
  * for specific files by ID.
33815
33813
  */
33816
33814
  getFileById(fileId: number): Promise<UserFile$1>;
33817
- /**
33818
- * Uploads an encrypted file to storage and registers it on the blockchain.
33819
- *
33820
- * @deprecated Since v2.0.0 - Use vana.data.upload() instead for the high-level API with automatic encryption
33821
- *
33822
- * Migration guide:
33823
- * ```typescript
33824
- * // Old way (deprecated):
33825
- * const encrypted = await encryptBlob(data, key);
33826
- * const result = await vana.data.uploadEncryptedFile(encrypted, filename);
33827
- *
33828
- * // New way:
33829
- * const result = await vana.data.upload({
33830
- * content: data,
33831
- * filename: filename,
33832
- * encrypt: true // Handles encryption automatically
33833
- * });
33834
- * ```
33835
- * @param encryptedFile - The encrypted file blob to upload
33836
- * @param filename - Optional filename for the upload
33837
- * @param providerName - Optional storage provider to use
33838
- * @returns Promise resolving to upload result with file ID and storage URL
33839
- *
33840
- * This method handles the complete flow of:
33841
- * 1. Uploading the encrypted file to the specified storage provider
33842
- * 2. Registering the file URL on the DataRegistry contract via relayer
33843
- * 3. Returning the assigned file ID and storage URL
33844
- */
33845
- uploadEncryptedFile(encryptedFile: Blob, filename?: string, providerName?: string): Promise<UploadEncryptedFileResult>;
33846
- /**
33847
- * Uploads an encrypted file to storage and registers it on the blockchain with a schema.
33848
- *
33849
- * @deprecated Since v2.0.0 - Use vana.data.upload() instead for the high-level API with automatic encryption and schema validation
33850
- *
33851
- * Migration guide:
33852
- * ```typescript
33853
- * // Old way (deprecated):
33854
- * const encrypted = await encryptBlob(data, key);
33855
- * const result = await vana.data.uploadEncryptedFileWithSchema(encrypted, schemaId, filename);
33856
- *
33857
- * // New way:
33858
- * const result = await vana.data.upload({
33859
- * content: data,
33860
- * filename: filename,
33861
- * schemaId: schemaId, // Automatic validation
33862
- * encrypt: true
33863
- * });
33864
- * ```
33865
- * @param encryptedFile - The encrypted file blob to upload
33866
- * @param schemaId - The schema ID to associate with the file
33867
- * @param filename - Optional filename for the upload
33868
- * @param providerName - Optional storage provider to use
33869
- * @returns Promise resolving to upload result with file ID and storage URL
33870
- *
33871
- * This method handles the complete flow of:
33872
- * 1. Uploading the encrypted file to the specified storage provider
33873
- * 2. Registering the file URL on the DataRegistry contract with a schema ID
33874
- * 3. Returning the assigned file ID and storage URL
33875
- */
33876
- uploadEncryptedFileWithSchema(encryptedFile: Blob, schemaId: number, filename?: string, providerName?: string): Promise<UploadEncryptedFileResult>;
33877
33815
  /**
33878
33816
  * Registers a file URL directly on the blockchain with a schema ID.
33879
33817
  *
@@ -33939,64 +33877,6 @@ declare class DataController {
33939
33877
  fileId: number;
33940
33878
  transactionHash: string;
33941
33879
  }>;
33942
- /**
33943
- * Adds a new schema to the DataRefinerRegistry.
33944
- *
33945
- * @deprecated Since v2.0.0 - Use vana.schemas.create() instead for the high-level API with automatic IPFS upload
33946
- *
33947
- * Migration guide:
33948
- * ```typescript
33949
- * // Old way (deprecated):
33950
- * const result = await vana.data.addSchema({
33951
- * name: "UserProfile",
33952
- * type: "JSON",
33953
- * definitionUrl: "ipfs://..."
33954
- * });
33955
- *
33956
- * // New way:
33957
- * const result = await vana.schemas.create({
33958
- * name: "UserProfile",
33959
- * type: "JSON",
33960
- * definition: schemaObject // Automatically uploads to IPFS
33961
- * });
33962
- * ```
33963
- * @param params - Schema parameters including name, type, and definition URL
33964
- * @returns Promise resolving to the new schema ID and transaction hash
33965
- */
33966
- addSchema(params: AddSchemaParams): Promise<AddSchemaResult>;
33967
- /**
33968
- * Retrieves a schema by its ID.
33969
- *
33970
- * @deprecated Since v2.0.0 - Use vana.schemas.get() instead
33971
- *
33972
- * Migration guide:
33973
- * ```typescript
33974
- * // Old way (deprecated):
33975
- * const schema = await vana.data.getSchema(schemaId);
33976
- *
33977
- * // New way:
33978
- * const schema = await vana.schemas.get(schemaId);
33979
- * ```
33980
- * @param schemaId - The schema ID to retrieve
33981
- * @returns Promise resolving to the schema information
33982
- */
33983
- getSchema(schemaId: number): Promise<Schema>;
33984
- /**
33985
- * Gets the total number of schemas in the registry.
33986
- *
33987
- * @deprecated Since v2.0.0 - Use vana.schemas.count() instead
33988
- *
33989
- * Migration guide:
33990
- * ```typescript
33991
- * // Old way (deprecated):
33992
- * const count = await vana.data.getSchemasCount();
33993
- *
33994
- * // New way:
33995
- * const count = await vana.schemas.count();
33996
- * ```
33997
- * @returns Promise resolving to the total schema count
33998
- */
33999
- getSchemasCount(): Promise<number>;
34000
33880
  /**
34001
33881
  * Adds a new refiner to the DataRefinerRegistry.
34002
33882
  *
@@ -34055,12 +33935,12 @@ declare class DataController {
34055
33935
  * This method only handles the storage upload and returns the file URL.
34056
33936
  *
34057
33937
  * @param content - The content to upload (string, Blob, Buffer, or object - objects will be JSON stringified)
34058
- * @param filename - Filename for the uploaded file
33938
+ * @param filename - Optional filename for the uploaded file (defaults to timestamp-based name)
34059
33939
  * @param encrypt - Optional flag to encrypt the content before upload
34060
33940
  * @param providerName - Optional specific storage provider to use
34061
- * @returns Promise resolving to the storage file URL
33941
+ * @returns Promise resolving to the storage upload result with url, size, and contentType
34062
33942
  */
34063
- uploadToStorage(content: string | Blob | Buffer | object, filename: string, encrypt?: boolean, providerName?: string): Promise<string>;
33943
+ uploadToStorage(content: string | Blob | Buffer | object, filename?: string, encrypt?: boolean, providerName?: string): Promise<StorageUploadResult>;
34064
33944
  /**
34065
33945
  * Adds a permission for a party to access an existing file.
34066
33946
  *
@@ -36459,6 +36339,10 @@ declare class CircuitBreaker {
36459
36339
  *
36460
36340
  * This implementation uses browser-compatible libraries and configurations
36461
36341
  * to provide crypto, PGP, and HTTP functionality without Node.js dependencies.
36342
+ *
36343
+ * WARNING: Dependencies that access globals during init
36344
+ * MUST be dynamically imported to support Turbopack.
36345
+ * See: https://github.com/vercel/next.js/issues/82632
36462
36346
  */
36463
36347
 
36464
36348
  /**