import tweetnacl from 'tweetnacl';
import tweetnaclUtil from 'tweetnacl-util';
import zlib from 'zlib';
import { promisify } from 'util';
const gzip = promisify(zlib.gzip);
const gunzip = promisify(zlib.gunzip);
const { encodeBase64, decodeBase64, encodeUTF8, decodeUTF8 } = tweetnaclUtil;
const COMPRESS_THRESHOLD = 512;
export function generateSessionKey() {
    return tweetnacl.randomBytes(32);
}
export async function encrypt(data, key) {
    const nonce = tweetnacl.randomBytes(24);
    const jsonStr = JSON.stringify(data);
    let message;
    let compressed = false;
    if (jsonStr.length > COMPRESS_THRESHOLD) {
        const compressedBuf = await gzip(Buffer.from(jsonStr, 'utf8'));
        message = new Uint8Array(compressedBuf);
        compressed = true;
    }
    else {
        message = decodeUTF8(jsonStr);
    }
    const encrypted = tweetnacl.secretbox(message, nonce, key);
    const result = {
        n: encodeBase64(nonce),
        c: encodeBase64(encrypted),
    };
    if (compressed)
        result.z = true;
    return result;
}
export async function decrypt(encrypted, key) {
    try {
        const nonce = decodeBase64(encrypted.n);
        const ciphertext = decodeBase64(encrypted.c);
        const decrypted = tweetnacl.secretbox.open(ciphertext, nonce, key);
        if (!decrypted)
            return null;
        if (encrypted.z) {
            const decompressed = await gunzip(Buffer.from(decrypted));
            return JSON.parse(decompressed.toString('utf8'));
        }
        else {
            return JSON.parse(encodeUTF8(decrypted));
        }
    }
    catch {
        return null;
    }
}
export function isEncrypted(msg) {
    return msg !== null && typeof msg === 'object' && typeof msg.n === 'string' && typeof msg.c === 'string';
}
export function encodeKey(key) {
    return encodeBase64(key);
}
export function decodeKey(encodedKey) {
    return decodeBase64(encodedKey);
}
export async function parseMessage(data, sessionKey) {
    try {
        const parsed = JSON.parse(data);
        if (sessionKey && isEncrypted(parsed)) {
            return await decrypt(parsed, sessionKey);
        }
        return parsed;
    }
    catch {
        return null;
    }
}
export async function encryptAndSend(ws, msg, sessionKey) {
    if (sessionKey) {
        const encrypted = await encrypt(msg, sessionKey);
        ws.send(JSON.stringify(encrypted));
    }
    else {
        ws.send(JSON.stringify(msg));
    }
}
//# sourceMappingURL=encryption.js.map