"use strict";
/**
 * Self-signed TLS certificate generator for localhost.
 *
 * Generates a self-signed certificate for 127.0.0.1/localhost on first run
 * and caches it to disk so the user only needs to trust it once.
 *
 * Uses Node.js built-in crypto to generate RSA key + self-signed X.509 cert.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLocalhostTls = getLocalhostTls;
const fs_1 = require("fs");
const path_1 = require("path");
const os_1 = require("os");
const child_process_1 = require("child_process");
const CERT_DIR = (0, path_1.join)((0, os_1.homedir)(), '.signdocsbrasil-assinador');
const KEY_PATH = (0, path_1.join)(CERT_DIR, 'localhost-key.pem');
const CERT_PATH = (0, path_1.join)(CERT_DIR, 'localhost-cert.pem');
/**
 * Get or generate TLS credentials for localhost.
 * Returns { key, cert } PEM strings ready for https.createServer().
 */
function getLocalhostTls() {
    // Return cached certs if they exist
    if ((0, fs_1.existsSync)(KEY_PATH) && (0, fs_1.existsSync)(CERT_PATH)) {
        return {
            key: (0, fs_1.readFileSync)(KEY_PATH, 'utf-8'),
            cert: (0, fs_1.readFileSync)(CERT_PATH, 'utf-8'),
        };
    }
    console.log('Generating self-signed TLS certificate for localhost...');
    // Ensure directory exists
    if (!(0, fs_1.existsSync)(CERT_DIR)) {
        (0, fs_1.mkdirSync)(CERT_DIR, { recursive: true });
    }
    // Use openssl to generate a self-signed cert (available on all platforms)
    try {
        (0, child_process_1.execSync)([
            'openssl', 'req', '-x509',
            '-newkey', 'rsa:2048',
            '-keyout', KEY_PATH,
            '-out', CERT_PATH,
            '-days', '3650',
            '-nodes',
            '-subj', '/CN=localhost',
            '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1',
        ].join(' '), { stdio: 'pipe' });
        console.log(`Certificate saved to ${CERT_DIR}`);
    }
    catch (e) {
        // Fallback: try without -addext (older openssl)
        try {
            (0, child_process_1.execSync)([
                'openssl', 'req', '-x509',
                '-newkey', 'rsa:2048',
                '-keyout', KEY_PATH,
                '-out', CERT_PATH,
                '-days', '3650',
                '-nodes',
                '-subj', '/CN=localhost',
            ].join(' '), { stdio: 'pipe' });
            console.log(`Certificate saved to ${CERT_DIR} (without SAN)`);
        }
        catch {
            throw new Error('Failed to generate TLS certificate. Ensure openssl is installed.\n' +
                'On Windows: install OpenSSL from https://slproweb.com/products/Win32OpenSSL.html\n' +
                'On macOS: brew install openssl\n' +
                'On Linux: sudo apt install openssl (or equivalent)');
        }
    }
    return {
        key: (0, fs_1.readFileSync)(KEY_PATH, 'utf-8'),
        cert: (0, fs_1.readFileSync)(CERT_PATH, 'utf-8'),
    };
}
