/** * Secure Completion Client * Main client class for encrypted communication with NOMYO router * * Port of Python's SecureCompletionClient with full API compatibility */ import { ClientConfig } from '../types/client'; import { KeyManager } from './crypto/keys'; import { AESEncryption } from './crypto/encryption'; import { RSAOperations } from './crypto/rsa'; import { createHttpClient, HttpClient } from './http/client'; import { createSecureMemory, SecureByteContext } from './memory/secure'; import { SecurityError, APIConnectionError, APIError, AuthenticationError, InvalidRequestError, RateLimitError, ServerError, ForbiddenError, ServiceUnavailableError, } from '../errors'; import { arrayBufferToBase64, base64ToArrayBuffer, stringToArrayBuffer, arrayBufferToString, } from './crypto/utils'; const VALID_SECURITY_TIERS = ['standard', 'high', 'maximum'] as const; function generateUUID(): string { if (typeof crypto !== 'undefined' && typeof (crypto as Crypto & { randomUUID?: () => string }).randomUUID === 'function') { return (crypto as Crypto & { randomUUID: () => string }).randomUUID(); } // Node.js fallback try { const nodeCrypto = require('crypto') as { randomUUID?: () => string }; if (nodeCrypto.randomUUID) { return nodeCrypto.randomUUID(); } } catch (_e) { /* not in Node.js */ } // Last-resort fallback (not RFC-compliant but collision-resistant enough) const bytes = new Uint8Array(16); if (typeof crypto !== 'undefined' && crypto.getRandomValues) { crypto.getRandomValues(bytes); } bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; const hex = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join(''); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } export class SecureCompletionClient { private routerUrl: string; private allowHttp: boolean; private secureMemory: boolean; private keyManager: KeyManager; private aes: AESEncryption; private rsa: RSAOperations; private httpClient: HttpClient; private secureMemoryImpl = createSecureMemory(); private readonly keySize: 2048 | 4096; constructor(config: ClientConfig = { routerUrl: 'https://api.nomyo.ai:12434' }) { const { routerUrl = 'https://api.nomyo.ai:12434', allowHttp = false, secureMemory = true, keySize = 4096, } = config; this.keySize = keySize; this.routerUrl = routerUrl.replace(/\/$/, ''); this.allowHttp = allowHttp; this.secureMemory = secureMemory; // Validate HTTPS for security if (!this.routerUrl.startsWith('https://')) { if (!allowHttp) { console.warn( '⚠️ WARNING: Using HTTP instead of HTTPS. ' + 'This is INSECURE and should only be used for local development. ' + 'Man-in-the-middle attacks are possible!' ); } else { console.log('HTTP mode enabled for local development (INSECURE)'); } } // Initialize components this.keyManager = new KeyManager(); this.aes = new AESEncryption(); this.rsa = new RSAOperations(); this.httpClient = createHttpClient(); // Log memory protection info const protectionInfo = this.secureMemoryImpl.getProtectionInfo(); console.log(`Memory protection: ${protectionInfo.method} (${protectionInfo.details})`); } /** * Generate RSA key pair */ async generateKeys(options: { saveToFile?: boolean; keyDir?: string; password?: string; } = {}): Promise { await this.keyManager.generateKeys({ keySize: this.keySize, ...options, }); } /** * Load existing keys from files (Node.js only) */ async loadKeys( privateKeyPath: string, publicKeyPath?: string, password?: string ): Promise { await this.keyManager.loadKeys( { privateKeyPath, publicKeyPath }, password ); } /** * Ensure keys are loaded, generate if necessary */ private async ensureKeys(): Promise { if (this.keyManager.hasKeys()) { return; } // Try to load keys from default location (Node.js only) if (typeof window === 'undefined') { try { const fs = require('fs').promises as { access: (p: string) => Promise }; const path = require('path') as { join: (...p: string[]) => string }; const privateKeyPath = path.join('client_keys', 'private_key.pem'); const publicKeyPath = path.join('client_keys', 'public_key.pem'); await fs.access(privateKeyPath); await fs.access(publicKeyPath); await this.loadKeys(privateKeyPath, publicKeyPath); console.log('Loaded existing keys from client_keys/'); return; } catch (_error) { console.log('No existing keys found, generating new keys...'); } } await this.generateKeys({ saveToFile: typeof window === 'undefined', keyDir: 'client_keys', }); } /** * Fetch server's public key from /pki/public_key endpoint */ async fetchServerPublicKey(): Promise { console.log("Fetching server's public key..."); if (!this.routerUrl.startsWith('https://')) { if (!this.allowHttp) { throw new SecurityError( 'Server public key must be fetched over HTTPS to prevent MITM attacks. ' + 'For local development, initialize with allowHttp=true: ' + 'new SecureChatCompletion({ baseUrl: "http://localhost:12434", allowHttp: true })' ); } else { console.warn('Fetching key over HTTP (local development mode)'); } } const url = `${this.routerUrl}/pki/public_key`; try { const response = await this.httpClient.get(url, { timeout: 60000 }); if (response.statusCode === 200) { const serverPublicKey = arrayBufferToString(response.body); // Validate it's a valid PEM key try { await this.rsa.importPublicKey(serverPublicKey); } catch (_error) { throw new Error('Server returned invalid public key format'); } if (this.routerUrl.startsWith('https://')) { console.log("Server's public key fetched securely over HTTPS"); } else { console.warn("Server's public key fetched over HTTP (INSECURE)"); } return serverPublicKey; } else { throw new Error(`Failed to fetch server's public key: HTTP ${response.statusCode}`); } } catch (error) { if (error instanceof SecurityError) { throw error; } if (error instanceof Error) { throw new APIConnectionError(`Failed to fetch server's public key: ${error.message}`); } throw error; } } /** * Encrypt a payload using hybrid encryption (AES-256-GCM + RSA-OAEP). * * The encrypted package format matches the Python server's expected format: * - ciphertext: AES-GCM ciphertext WITHOUT auth tag * - nonce: 12-byte GCM nonce * - tag: 16-byte GCM auth tag (split from Web Crypto output) * - encrypted_aes_key: AES key encrypted with server's RSA public key */ async encryptPayload(payload: object): Promise { console.log('Encrypting payload...'); if (!payload || typeof payload !== 'object') { throw new Error('Payload must be an object'); } await this.ensureKeys(); const payloadJson = JSON.stringify(payload); const payloadBytes = stringToArrayBuffer(payloadJson); const MAX_PAYLOAD_SIZE = 10 * 1024 * 1024; // 10MB if (payloadBytes.byteLength > MAX_PAYLOAD_SIZE) { throw new Error(`Payload too large: ${payloadBytes.byteLength} bytes (max: ${MAX_PAYLOAD_SIZE})`); } console.log(`Payload size: ${payloadBytes.byteLength} bytes`); if (this.secureMemory) { const context = new SecureByteContext(payloadBytes, true); return await context.use(async (protectedPayload) => { return await this.performEncryption(protectedPayload); }); } else { return await this.performEncryption(payloadBytes); } } /** * Perform the actual encryption. * * Web Crypto AES-GCM encrypt returns ciphertext || tag (last 16 bytes). * We split the tag out to match Python's cryptography library format * which sends ciphertext and tag as separate fields. */ private async performEncryption(payloadBytes: ArrayBuffer): Promise { const aesKey = await this.aes.generateKey(); const aesKeyBytes = await this.aes.exportKey(aesKey); const aesContext = new SecureByteContext(aesKeyBytes, this.secureMemory); return await aesContext.use(async (protectedAesKey) => { const { ciphertext, nonce } = await this.aes.encrypt(payloadBytes, aesKey); // Web Crypto appends 16-byte GCM auth tag to ciphertext. // Split it to match Python's format (separate ciphertext and tag fields). const TAG_LENGTH = 16; const ciphertextBytes = new Uint8Array(ciphertext); const ciphertextOnly = ciphertextBytes.slice(0, ciphertextBytes.length - TAG_LENGTH); const tag = ciphertextBytes.slice(ciphertextBytes.length - TAG_LENGTH); const serverPublicKeyPem = await this.fetchServerPublicKey(); const serverPublicKey = await this.rsa.importPublicKey(serverPublicKeyPem); const encryptedAesKey = await this.rsa.encryptKey(protectedAesKey, serverPublicKey); const encryptedPackage = { version: '1.0', algorithm: 'hybrid-aes256-rsa4096', encrypted_payload: { ciphertext: arrayBufferToBase64(ciphertextOnly.buffer), nonce: arrayBufferToBase64(nonce), tag: arrayBufferToBase64(tag.buffer), }, encrypted_aes_key: arrayBufferToBase64(encryptedAesKey), key_algorithm: 'RSA-OAEP-SHA256', payload_algorithm: 'AES-256-GCM', }; const packageJson = JSON.stringify(encryptedPackage); const packageBytes = stringToArrayBuffer(packageJson); console.log(`Encrypted package size: ${packageBytes.byteLength} bytes`); return packageBytes; }); } /** * Decrypt a response from the secure endpoint. * * The server (Python) sends ciphertext and tag as separate fields. * Web Crypto AES-GCM decrypt expects ciphertext || tag concatenated. */ async decryptResponse(encryptedResponse: ArrayBuffer, payloadId: string): Promise> { console.log('Decrypting response...'); if (!encryptedResponse || encryptedResponse.byteLength === 0) { throw new Error('Empty encrypted response'); } let packageData: Record; try { const packageJson = arrayBufferToString(encryptedResponse); packageData = JSON.parse(packageJson) as Record; } catch (_error) { throw new Error('Invalid encrypted package format: malformed JSON'); } // Validate top-level structure const requiredFields = ['version', 'algorithm', 'encrypted_payload', 'encrypted_aes_key']; for (const field of requiredFields) { if (!(field in packageData)) { throw new Error(`Missing required field in encrypted package: ${field}`); } } const encryptedPayload = packageData.encrypted_payload as Record; if (typeof encryptedPayload !== 'object' || encryptedPayload === null) { throw new Error('Invalid encrypted_payload: must be an object'); } // All three fields required to match Python server format const payloadRequired = ['ciphertext', 'nonce', 'tag']; for (const field of payloadRequired) { if (!(field in encryptedPayload)) { throw new Error(`Missing field in encrypted_payload: ${field}`); } } try { const encryptedAesKey = base64ToArrayBuffer(packageData.encrypted_aes_key as string); const privateKey = this.keyManager.getPrivateKey(); const aesKeyBytes = await this.rsa.decryptKey(encryptedAesKey, privateKey); const aesContext = new SecureByteContext(aesKeyBytes, this.secureMemory); const response = await aesContext.use(async (protectedAesKey) => { const aesKey = await this.aes.importKey(protectedAesKey); const ciphertext = base64ToArrayBuffer(encryptedPayload.ciphertext as string); const nonce = base64ToArrayBuffer(encryptedPayload.nonce as string); const tag = base64ToArrayBuffer(encryptedPayload.tag as string); // Concatenate ciphertext + tag for Web Crypto (expects them joined) const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength); combined.set(new Uint8Array(ciphertext), 0); combined.set(new Uint8Array(tag), ciphertext.byteLength); const plaintext = await this.aes.decrypt(combined.buffer, nonce, aesKey); const plaintextContext = new SecureByteContext(plaintext, this.secureMemory); return await plaintextContext.use(async (protectedPlaintext) => { const responseJson = arrayBufferToString(protectedPlaintext); return JSON.parse(responseJson) as Record; }); }); // Add metadata const metadata = (response._metadata as Record) ?? {}; response._metadata = { ...metadata, payload_id: payloadId, processed_at: packageData.processed_at, is_encrypted: true, encryption_algorithm: packageData.algorithm, }; console.log('Response decrypted successfully'); return response; } catch (error) { // Don't leak specific decryption errors (timing attacks) throw new SecurityError('Decryption failed: integrity check or authentication failed'); } } /** * Send a secure chat completion request to the router. * * @param securityTier Optional routing tier: "standard" | "high" | "maximum" */ async sendSecureRequest( payload: object, payloadId: string, apiKey?: string, securityTier?: string ): Promise> { console.log('Sending secure chat completion request...'); // Validate security tier if (securityTier !== undefined) { if (!(VALID_SECURITY_TIERS as readonly string[]).includes(securityTier)) { throw new Error( `Invalid securityTier: '${securityTier}'. ` + `Must be one of: ${VALID_SECURITY_TIERS.join(', ')}` ); } } await this.ensureKeys(); const encryptedPayload = await this.encryptPayload(payload); const publicKeyPem = await this.keyManager.getPublicKeyPEM(); const headers: Record = { 'X-Payload-ID': payloadId, 'X-Public-Key': encodeURIComponent(publicKeyPem), 'Content-Type': 'application/octet-stream', }; if (apiKey) { headers['Authorization'] = `Bearer ${apiKey}`; } if (securityTier) { headers['X-Security-Tier'] = securityTier; } const url = `${this.routerUrl}/v1/chat/secure_completion`; console.log(`Target URL: ${url}`); let response: { statusCode: number; body: ArrayBuffer }; try { response = await this.httpClient.post(url, { headers, body: encryptedPayload, timeout: 60000, }); } catch (error) { if (error instanceof Error) { if (error.message === 'Request timeout') { throw new APIConnectionError('Connection to server timed out'); } throw new APIConnectionError(`Failed to connect to router: ${error.message}`); } throw error; } console.log(`HTTP Status: ${response.statusCode}`); if (response.statusCode === 200) { return await this.decryptResponse(response.body, payloadId); } // Map HTTP error status codes to typed errors throw this.buildErrorFromResponse(response); } /** * Build a typed error from an HTTP error response */ private buildErrorFromResponse(response: { statusCode: number; body: ArrayBuffer }): Error { let errorData: Record = {}; try { const errorJson = arrayBufferToString(response.body); errorData = JSON.parse(errorJson) as Record; } catch (_e) { // Ignore JSON parse errors } const detail = (errorData.detail as string | undefined) ?? 'Unknown error'; switch (response.statusCode) { case 400: return new InvalidRequestError(`Bad request: ${detail}`, 400, errorData); case 401: return new AuthenticationError( `Invalid API key or authentication failed: ${detail}`, 401, errorData ); case 403: return new ForbiddenError( `Forbidden: ${detail}`, 403, errorData ); case 404: return new APIError(`Endpoint not found: ${detail}`, 404, errorData); case 429: return new RateLimitError(`Rate limit exceeded: ${detail}`, 429, errorData); case 500: return new ServerError(`Server error: ${detail}`, 500, errorData); case 503: return new ServiceUnavailableError( `Service unavailable: ${detail}`, 503, errorData ); default: return new APIError( `Unexpected status code: ${response.statusCode} ${detail}`, response.statusCode, errorData ); } } /** * Validate RSA key size (minimum 2048 bits) */ validateRsaKeySize(key: CryptoKey, keyType: 'private' | 'public' = 'private'): void { const algorithm = key.algorithm as RsaHashedKeyAlgorithm; const MIN_KEY_SIZE = 2048; if (algorithm.modulusLength < MIN_KEY_SIZE) { throw new Error( `Key size ${algorithm.modulusLength} is too small. ` + `Minimum recommended size is ${MIN_KEY_SIZE} bits.` ); } console.log(`Valid ${algorithm.modulusLength}-bit RSA ${keyType} key`); } } export { generateUUID };