UNPKG

ssr-web-avo-inspector

Version:

Avo Inspector for web with SSR and web workers support

314 lines (313 loc) 15.7 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateKeyPair = generateKeyPair; exports.encryptValue = encryptValue; exports.decryptValue = decryptValue; /* eslint-disable @typescript-eslint/no-explicit-any */ var p256_1 = require("@noble/curves/p256"); /** * ECIES Encryption module for Avo Inspector (Web / Web Worker / SSR). * * Uses globalThis.crypto.subtle for AES-256-GCM (async WebCrypto API). * Handles three runtime contexts: * - Browser: window.crypto.subtle * - Web Worker: globalThis.crypto.subtle (no window object) * - Node.js 18+ SSR: globalThis.crypto.subtle * * Node 18+ is a hard requirement for SSR encryption. * * Copied from js-avo-inspector main branch AvoEncryption.ts and adapted * for the web-avo-inspector structure. */ /** * Converts bytes (Uint8Array) to hex string */ function bytesToHex(bytes) { return Array.from(bytes) .map(function (b) { return b.toString(16).padStart(2, '0'); }) .join(''); } /** * Converts hex string to bytes (Uint8Array) */ function hexToBytes(hex) { var bytes = new Uint8Array(hex.length / 2); for (var i = 0; i < hex.length; i += 2) { bytes[i / 2] = parseInt(hex.substr(i, 2), 16); } return bytes; } /** * Get crypto API - works in browser, Web Worker, and Node.js 18+ environments. * * Resolution order: * 1. globalThis.crypto.subtle (works in all three contexts) * 2. window.crypto.subtle (browser fallback) * 3. global.crypto.subtle (Node.js fallback) * * @throws Error if crypto.subtle is not available */ var getCrypto = function () { // Try globalThis first (works in both Node.js and browsers) if (typeof globalThis !== 'undefined' && globalThis.crypto) { var crypto_1 = globalThis.crypto; if (crypto_1 && crypto_1.subtle) { return crypto_1; } } // Try window (browser) if (typeof window !== 'undefined' && window.crypto) { var crypto_2 = window.crypto; if (crypto_2 && crypto_2.subtle) { return crypto_2; } } // Try global (Node.js) if (typeof global !== 'undefined' && global.crypto) { var crypto_3 = global.crypto; if (crypto_3 && crypto_3.subtle) { return crypto_3; } } // Fallback - should not happen in proper environments var debugInfo = { hasGlobalThis: typeof globalThis !== 'undefined', hasGlobalThisCrypto: typeof globalThis !== 'undefined' && !!globalThis.crypto, hasGlobalThisCryptoSubtle: typeof globalThis !== 'undefined' && !!globalThis.crypto && !!globalThis.crypto.subtle, hasWindow: typeof window !== 'undefined', hasWindowCrypto: typeof window !== 'undefined' && !!window.crypto, hasGlobal: typeof global !== 'undefined', hasGlobalCrypto: typeof global !== 'undefined' && !!global.crypto, hasGlobalCryptoSubtle: typeof global !== 'undefined' && !!global.crypto && !!global.crypto.subtle }; throw new Error('crypto.subtle not available. Debug: ' + JSON.stringify(debugInfo)); }; /** * Generates a new ECC key pair for encryption/decryption. * Uses P-256 (prime256v1 / NIST P-256) curve. * * @returns An object containing the private and public keys as hex strings */ function generateKeyPair() { var privateKeyBytes = p256_1.p256.utils.randomPrivateKey(); var publicKeyBytes = p256_1.p256.getPublicKey(privateKeyBytes, false); var privateKey = bytesToHex(privateKeyBytes).padStart(64, '0'); var publicKey = bytesToHex(publicKeyBytes); return { privateKey: privateKey, publicKey: publicKey }; } /** * Derives a key from shared secret using SHA-256 */ function deriveKey(sharedSecret) { return __awaiter(this, void 0, void 0, function () { var cryptoAPI; return __generator(this, function (_a) { switch (_a.label) { case 0: cryptoAPI = getCrypto(); return [4 /*yield*/, cryptoAPI.subtle.digest('SHA-256', sharedSecret)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); } /** * Safely converts Uint8Array to base64 string. * Uses Buffer in Node.js for efficiency, or chunked conversion in browsers. */ function uint8ArrayToBase64(bytes) { if (typeof Buffer !== 'undefined' && Buffer.from) { return Buffer.from(bytes).toString('base64'); } var CHUNK_SIZE = 8192; var binaryString = ''; for (var i = 0; i < bytes.length; i += CHUNK_SIZE) { var chunk = bytes.slice(i, i + CHUNK_SIZE); binaryString += String.fromCharCode.apply(null, Array.from(chunk)); } return btoa(binaryString); } /** * Encrypts a value using ECC public key encryption (ECIES). * * ECIES uses hybrid encryption (ECDH + AES-256-GCM). * * Wire format: * [Version 0x00 (1B)] [EphemeralPubKey (65B)] [IV (16B)] [AuthTag (16B)] [Ciphertext] * * @param value - The value to encrypt (any type - will be JSON stringified) * @param publicKey - The ECC public key in hex format * @returns Promise resolving to base64-encoded encrypted string */ function encryptValue(value, publicKey) { return __awaiter(this, void 0, void 0, function () { var stringValue, recipientPublicKeyBytes, ephemeralPrivateKeyBytes, ephemeralPublicKeyBytes, sharedSecretPoint, sharedSecret, derivedKeyBuffer, cryptoAPI, keyMaterial, iv, plaintext, encryptedData, encryptedArray, authTagLength, ciphertextLength, ciphertext, authTag, version, resultLength, result, offset, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 4, , 5]); stringValue = value === undefined ? 'null' : JSON.stringify(value); recipientPublicKeyBytes = hexToBytes(publicKey); ephemeralPrivateKeyBytes = p256_1.p256.utils.randomPrivateKey(); ephemeralPublicKeyBytes = p256_1.p256.getPublicKey(ephemeralPrivateKeyBytes, false); sharedSecretPoint = p256_1.p256.getSharedSecret(ephemeralPrivateKeyBytes, recipientPublicKeyBytes); sharedSecret = sharedSecretPoint.slice(-32); return [4 /*yield*/, deriveKey(sharedSecret) // Import key for AES-GCM ]; case 1: derivedKeyBuffer = _a.sent(); cryptoAPI = getCrypto(); return [4 /*yield*/, cryptoAPI.subtle.importKey('raw', derivedKeyBuffer, { name: 'AES-GCM' }, false, ['encrypt']) // Random IV (16 bytes) ]; case 2: keyMaterial = _a.sent(); iv = cryptoAPI.getRandomValues(new Uint8Array(16)); plaintext = new TextEncoder().encode(stringValue); return [4 /*yield*/, cryptoAPI.subtle.encrypt({ name: 'AES-GCM', iv: iv, tagLength: 128 }, keyMaterial, plaintext) // Web Crypto appends auth tag to ciphertext - extract separately ]; case 3: encryptedData = _a.sent(); encryptedArray = new Uint8Array(encryptedData); authTagLength = 16; ciphertextLength = encryptedArray.length - authTagLength; ciphertext = encryptedArray.slice(0, ciphertextLength); authTag = encryptedArray.slice(ciphertextLength); version = new Uint8Array([0x00]); resultLength = 1 + ephemeralPublicKeyBytes.length + 16 + 16 + ciphertext.length; result = new Uint8Array(resultLength); offset = 0; result.set(version, offset); offset += 1; result.set(ephemeralPublicKeyBytes, offset); offset += ephemeralPublicKeyBytes.length; result.set(iv, offset); offset += 16; result.set(authTag, offset); offset += 16; result.set(ciphertext, offset); return [2 /*return*/, uint8ArrayToBase64(result)]; case 4: error_1 = _a.sent(); throw new Error("Failed to encrypt value. Please check that the public key is valid. Error: ".concat(error_1 instanceof Error ? error_1.message : String(error_1))); case 5: return [2 /*return*/]; } }); }); } /** * Decrypts a value that was encrypted with encryptValue. * * @param encryptedValue - The base64-encoded encrypted string * @param privateKey - The ECC private key in hex format * @returns Promise resolving to the original decrypted value (parsed from JSON) */ function decryptValue(encryptedValue, privateKey) { return __awaiter(this, void 0, void 0, function () { var encryptedBuffer, offset, version, keyHeader, pubKeySize, minRequired, ephemeralPublicKey, iv, authTag, ciphertext, recipientPrivateKeyBytes, sharedSecretPoint, sharedSecret, derivedKeyBuffer, cryptoAPI, keyMaterial, combinedLength, data, decryptedBuffer, decoder, stringValue, error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 4, , 5]); encryptedBuffer = typeof Buffer !== 'undefined' && Buffer.from ? new Uint8Array(Buffer.from(encryptedValue, 'base64')) : (function () { var binaryString = atob(encryptedValue); var buf = new Uint8Array(binaryString.length); for (var i = 0; i < binaryString.length; i++) { buf[i] = binaryString.charCodeAt(i); } return buf; })(); if (encryptedBuffer.length < 67) { throw new Error('Invalid encrypted data: payload too short'); } offset = 0; version = encryptedBuffer[offset]; offset += 1; if (version !== 0x00) { throw new Error("Unsupported encryption version: ".concat(version)); } keyHeader = encryptedBuffer[offset]; pubKeySize = keyHeader === 0x02 || keyHeader === 0x03 ? 33 : 65; minRequired = 1 + pubKeySize + 16 + 16 + 1; if (encryptedBuffer.length < minRequired) { throw new Error("Invalid encrypted data: expected at least ".concat(minRequired, " bytes, got ").concat(encryptedBuffer.length)); } ephemeralPublicKey = encryptedBuffer.slice(offset, offset + pubKeySize); offset += pubKeySize; iv = encryptedBuffer.slice(offset, offset + 16); offset += 16; authTag = encryptedBuffer.slice(offset, offset + 16); offset += 16; ciphertext = encryptedBuffer.slice(offset); recipientPrivateKeyBytes = hexToBytes(privateKey); sharedSecretPoint = p256_1.p256.getSharedSecret(recipientPrivateKeyBytes, ephemeralPublicKey); sharedSecret = sharedSecretPoint.slice(-32); return [4 /*yield*/, deriveKey(sharedSecret) // Import key for AES-GCM decrypt ]; case 1: derivedKeyBuffer = _a.sent(); cryptoAPI = getCrypto(); return [4 /*yield*/, cryptoAPI.subtle.importKey('raw', derivedKeyBuffer, { name: 'AES-GCM' }, false, ['decrypt']) // Web Crypto expects ciphertext + authTag concatenated ]; case 2: keyMaterial = _a.sent(); combinedLength = ciphertext.length + authTag.length; data = new Uint8Array(combinedLength); data.set(ciphertext, 0); data.set(authTag, ciphertext.length); return [4 /*yield*/, cryptoAPI.subtle.decrypt({ name: 'AES-GCM', iv: iv, tagLength: 128 }, keyMaterial, data)]; case 3: decryptedBuffer = _a.sent(); decoder = new TextDecoder(); stringValue = decoder.decode(decryptedBuffer); return [2 /*return*/, JSON.parse(stringValue)]; case 4: error_2 = _a.sent(); throw new Error("Failed to decrypt value. Please check that the private key is valid and matches the public key used for encryption. Error: ".concat(error_2 instanceof Error ? error_2.message : String(error_2))); case 5: return [2 /*return*/]; } }); }); }