/**
 * AAuth key provisioning: `neotoma auth keygen --aauth`
 *
 * Generates an EC P-256 key pair for AAuth agent identity signing.
 * Writes the private JWK to `.creds/aauth_agent.private.jwk` and the
 * public JWK to `.creds/aauth_agent.public.jwk`. Optionally uploads
 * the public key to the issuer's JWKS endpoint.
 */
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { randomUUID } from "node:crypto";
import * as jose from "jose";
function defaultOutputDir() {
    return resolve(process.cwd(), ".creds");
}
async function generateKeyPair(kid) {
    const { publicKey, privateKey } = await jose.generateKeyPair("ES256", {
        extractable: true,
    });
    const privateJwk = await jose.exportJWK(privateKey);
    const publicJwk = await jose.exportJWK(publicKey);
    privateJwk.kid = kid;
    privateJwk.alg = "ES256";
    privateJwk.use = "sig";
    publicJwk.kid = kid;
    publicJwk.alg = "ES256";
    publicJwk.use = "sig";
    return { privateJwk, publicJwk };
}
function writeEnvHints(outputDir, sub, iss) {
    const privatePath = resolve(outputDir, "aauth_agent.private.jwk");
    const lines = [
        `# AAuth agent identity (add to .env or export in shell)`,
        `NEOTOMA_AAUTH_PRIVATE_JWK_PATH="${privatePath}"`,
    ];
    if (sub)
        lines.push(`NEOTOMA_AAUTH_SUB="${sub}"`);
    if (iss)
        lines.push(`NEOTOMA_AAUTH_ISS="${iss}"`);
    lines.push("");
    const hintPath = resolve(outputDir, "aauth_env_hints.txt");
    writeFileSync(hintPath, lines.join("\n"), "utf-8");
    process.stderr.write(`  Env hints written to ${hintPath}\n`);
}
export function registerAuthKeygenCommand(authCommand) {
    authCommand
        .command("keygen")
        .description("Generate AAuth key pair for agent identity signing")
        .option("--aauth", "Generate AAuth keys (required flag for safety)")
        .option("--output-dir <dir>", "Directory for key files (default: .creds/)")
        .option("--kid <id>", "Key ID (default: auto-generated UUID)")
        .option("--sub <subject>", "AAuth subject claim (e.g. cursor@you.com)")
        .option("--iss <issuer>", "AAuth issuer claim (e.g. https://you.com)")
        .option("--force", "Overwrite existing key files")
        .action(async (opts) => {
        if (!opts.aauth) {
            process.stderr.write("Error: --aauth flag is required. This confirms you want to generate AAuth signing keys.\n" +
                "Usage: neotoma auth keygen --aauth [--sub <subject>] [--iss <issuer>]\n");
            process.exitCode = 1;
            return;
        }
        const outputDir = opts.outputDir ?? defaultOutputDir();
        const kid = opts.kid ?? randomUUID();
        const privatePath = resolve(outputDir, "aauth_agent.private.jwk");
        const publicPath = resolve(outputDir, "aauth_agent.public.jwk");
        if (!opts.force && existsSync(privatePath)) {
            process.stderr.write(`Error: Private key already exists at ${privatePath}\n` +
                `Use --force to overwrite.\n`);
            process.exitCode = 1;
            return;
        }
        mkdirSync(outputDir, { recursive: true });
        process.stderr.write("Generating EC P-256 key pair for AAuth...\n");
        const { privateJwk, publicJwk } = await generateKeyPair(kid);
        writeFileSync(privatePath, JSON.stringify(privateJwk, null, 2) + "\n", {
            mode: 0o600,
        });
        writeFileSync(publicPath, JSON.stringify(publicJwk, null, 2) + "\n", {
            mode: 0o644,
        });
        const thumbprint = await jose.calculateJwkThumbprint(publicJwk, "sha256");
        process.stderr.write(`\nAAuth key pair generated:\n`);
        process.stderr.write(`  Private: ${privatePath}\n`);
        process.stderr.write(`  Public:  ${publicPath}\n`);
        process.stderr.write(`  kid:     ${kid}\n`);
        process.stderr.write(`  jkt:     ${thumbprint}\n`);
        process.stderr.write(`  alg:     ES256 (EC P-256)\n\n`);
        writeEnvHints(outputDir, opts.sub, opts.iss);
        process.stderr.write(`\nNext steps:\n`);
        process.stderr.write(`  1. Add the env vars from ${resolve(outputDir, "aauth_env_hints.txt")} to your .env\n`);
        process.stderr.write(`  2. Publish ${publicPath} to your JWKS endpoint at <ISS>/.well-known/jwks.json\n`);
        process.stderr.write(`  3. Run 'neotoma mcp proxy --aauth' to start the proxy with AAuth signing\n`);
        if (!opts.sub || !opts.iss) {
            process.stderr.write(`\n  Note: --sub and --iss were not provided. Set NEOTOMA_AAUTH_SUB and\n` +
                `  NEOTOMA_AAUTH_ISS in your .env before using AAuth.\n`);
        }
        const gitignorePath = resolve(outputDir, ".gitignore");
        if (!existsSync(gitignorePath)) {
            writeFileSync(gitignorePath, "*.private.jwk\naauth_env_hints.txt\n");
            process.stderr.write(`  .gitignore created in ${outputDir} to protect private keys\n`);
        }
        else {
            const existing = readFileSync(gitignorePath, "utf-8");
            if (!existing.includes("*.private.jwk")) {
                writeFileSync(gitignorePath, existing.trimEnd() + "\n*.private.jwk\naauth_env_hints.txt\n");
            }
        }
    });
}
//# sourceMappingURL=auth_keygen.js.map