'use client';
/**
 * Web Crypto API utilities for encrypting/decrypting auth credentials
 * Uses AES-GCM with a key derived from device ID
 */ const ALGORITHM = 'AES-GCM';
const KEY_LENGTH = 256;
const IV_LENGTH = 12 // 96 bits for AES-GCM
;
/**
 * Derive a crypto key from a device ID using PBKDF2
 */ async function deriveKey(deviceId) {
    const encoder = new TextEncoder();
    const keyMaterial = await crypto.subtle.importKey('raw', encoder.encode(deviceId), 'PBKDF2', false, [
        'deriveKey'
    ]);
    // Use a fixed salt (could be made dynamic per-user if needed)
    const salt = encoder.encode('brainfish-api-docs-v1');
    return crypto.subtle.deriveKey({
        name: 'PBKDF2',
        salt,
        iterations: 100000,
        hash: 'SHA-256'
    }, keyMaterial, {
        name: ALGORITHM,
        length: KEY_LENGTH
    }, false, [
        'encrypt',
        'decrypt'
    ]);
}
/**
 * Encrypt a string using AES-GCM with device ID as key
 */ export async function encrypt(plaintext, deviceId) {
    const key = await deriveKey(deviceId);
    const encoder = new TextEncoder();
    const data = encoder.encode(plaintext);
    // Generate random IV
    const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
    const encrypted = await crypto.subtle.encrypt({
        name: ALGORITHM,
        iv
    }, key, data);
    // Combine IV + encrypted data and encode as base64
    const combined = new Uint8Array(iv.length + encrypted.byteLength);
    combined.set(iv);
    combined.set(new Uint8Array(encrypted), iv.length);
    return btoa(String.fromCharCode(...combined));
}
/**
 * Decrypt a string using AES-GCM with device ID as key
 */ export async function decrypt(ciphertext, deviceId) {
    const key = await deriveKey(deviceId);
    // Decode base64
    const combined = Uint8Array.from(atob(ciphertext), (c)=>c.charCodeAt(0));
    // Extract IV and encrypted data
    const iv = combined.slice(0, IV_LENGTH);
    const encrypted = combined.slice(IV_LENGTH);
    const decrypted = await crypto.subtle.decrypt({
        name: ALGORITHM,
        iv
    }, key, encrypted);
    const decoder = new TextDecoder();
    return decoder.decode(decrypted);
}
