"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileKeyProvider = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const crypto = __importStar(require("crypto"));
const key_provider_1 = require("./key-provider");
// ============================================================
// key-provider-file.ts — Machine-bound encrypted file provider
//
// Stores keys as AES-256-GCM encrypted files
// Encryption key is derived from hostname + username
// So the file is only readable on this machine
// ============================================================
const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 16;
const TAG_LENGTH = 16;
function getKeysDir() {
    return path.join(os.homedir(), '.fivo', 'cell', 'keys');
}
function getKeyPath(id) {
    // Sanitize ID for filename
    const safeId = id.replace(/[^a-zA-Z0-9_-]/g, '_');
    return path.join(getKeysDir(), `${safeId}.enc`);
}
function encrypt(data, key) {
    const iv = crypto.randomBytes(IV_LENGTH);
    const cipher = crypto.createCipheriv(ALGORITHM, key, iv, { authTagLength: TAG_LENGTH });
    const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
    const authTag = cipher.getAuthTag();
    // Format: iv(16) + authTag(16) + encrypted
    return Buffer.concat([iv, authTag, encrypted]);
}
function decrypt(data, key) {
    const iv = data.subarray(0, IV_LENGTH);
    const authTag = data.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH);
    const encrypted = data.subarray(IV_LENGTH + TAG_LENGTH);
    const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, { authTagLength: TAG_LENGTH });
    decipher.setAuthTag(authTag);
    return Buffer.concat([decipher.update(encrypted), decipher.final()]);
}
class FileKeyProvider {
    name = 'file-encrypted';
    isAvailable() {
        try {
            const dir = getKeysDir();
            if (!fs.existsSync(dir))
                fs.mkdirSync(dir, { recursive: true });
            return true;
        }
        catch {
            return false;
        }
    }
    getKey(id) {
        const keyPath = getKeyPath(id);
        if (!fs.existsSync(keyPath))
            return null;
        try {
            const encrypted = fs.readFileSync(keyPath);
            const machineKey = (0, key_provider_1.deriveMachineKey)();
            return decrypt(encrypted, machineKey);
        }
        catch {
            return null;
        }
    }
    setKey(id, key) {
        try {
            const dir = getKeysDir();
            if (!fs.existsSync(dir))
                fs.mkdirSync(dir, { recursive: true });
            const machineKey = (0, key_provider_1.deriveMachineKey)();
            const encrypted = encrypt(key, machineKey);
            fs.writeFileSync(getKeyPath(id), encrypted);
            return true;
        }
        catch {
            return false;
        }
    }
    deleteKey(id) {
        try {
            const keyPath = getKeyPath(id);
            if (fs.existsSync(keyPath))
                fs.unlinkSync(keyPath);
            return true;
        }
        catch {
            return false;
        }
    }
}
exports.FileKeyProvider = FileKeyProvider;
//# sourceMappingURL=key-provider-file.js.map