import { randomBytes } from "node:crypto";
import { readFile, writeFile, mkdir, unlink } from "node:fs/promises";
import { dirname } from "node:path";
import { getConfigDir } from "./paths.js";
const KEY_FILENAME = "machine-key";
/**
 * Get the path to the machine key file.
 */
function getMachineKeyPath() {
    return `${getConfigDir()}/${KEY_FILENAME}`;
}
/**
 * Generate a new 32-byte hex machine key.
 */
function generateKey() {
    return randomBytes(32).toString("hex");
}
/**
 * Get or create a stable machine key for this host.
 *
 * On first run, generates a random 64-character hex string and stores it
 * in the config directory. On subsequent runs, returns the stored key.
 *
 * The key is stored separately from auth.json so it persists even when
 * tokens are cleared (logout/re-login).
 */
export async function getMachineKey() {
    const keyPath = getMachineKeyPath();
    // Try to read existing key
    try {
        const content = await readFile(keyPath, "utf-8");
        const key = content.trim();
        if (isValidMachineKey(key)) {
            return key;
        }
        // Invalid key file — regenerate
    }
    catch {
        // File doesn't exist — generate new key
    }
    // Generate and persist new key
    const key = generateKey();
    await mkdir(dirname(keyPath), { recursive: true });
    const mode = process.platform === "win32" ? undefined : 0o600;
    await writeFile(keyPath, key + "\n", { mode });
    return key;
}
/**
 * Delete the stored machine key file.
 * Used during logout to force key regeneration on next login.
 */
export async function deleteMachineKey() {
    try {
        await unlink(getMachineKeyPath());
    }
    catch {
        // Ignore if file doesn't exist
    }
}
/**
 * Validate that a string is a valid machine key (32+ byte hex string = 64+ chars).
 */
export function isValidMachineKey(key) {
    return /^[0-9a-f]{64,}$/.test(key);
}
//# sourceMappingURL=machine-key.js.map