"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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
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;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var KeyStorageService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyStorageService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const fs = __importStar(require("node:fs/promises"));
const path = __importStar(require("node:path"));
const crypto = __importStar(require("node:crypto"));
let KeyStorageService = KeyStorageService_1 = class KeyStorageService {
    constructor(configService) {
        this.configService = configService;
        this.logger = new common_1.Logger(KeyStorageService_1.name);
        this.keyBasePath = this.configService.get('SSH_KEYS_PATH', '/secure/keys');
        const secretKey = this.configService.get('SSH_KEY_ENCRYPTION_KEY', 
        // Default 32-byte hex key if not provided
        '0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff');
        if (!secretKey) {
            this.logger.warn('No SSH_KEY_ENCRYPTION_KEY provided, using default key');
        }
        this.encryptionKey = Buffer.from(secretKey, 'hex');
    }
    async storePrivateKey(userId, keyId, privateKey) {
        const keyPath = this.getKeyPath(userId, keyId);
        await fs.mkdir(path.dirname(keyPath), { recursive: true });
        const encryptedKey = this.encryptKey(privateKey);
        await fs.writeFile(keyPath, encryptedKey);
        await fs.chmod(keyPath, 0o600);
        return keyPath;
    }
    async retrievePrivateKey(keyPath) {
        const encryptedKey = await fs.readFile(keyPath);
        return this.decryptKey(encryptedKey);
    }
    async deleteKey(keyPath) {
        try {
            await fs.unlink(keyPath);
            await this.cleanupKeyDirectory(keyPath);
        }
        catch (error) {
            if (error.code !== 'ENOENT') {
                throw error;
            }
        }
    }
    encryptKeyToString(privateKey) {
        const encryptedBuffer = this.encryptKey(privateKey);
        return encryptedBuffer.toString('base64');
    }
    encryptKey(privateKey) {
        const iv = crypto.randomBytes(16);
        const cipher = crypto.createCipheriv('aes-256-gcm', this.encryptionKey, iv);
        const encrypted = Buffer.concat([
            cipher.update(privateKey, 'utf8'),
            cipher.final(),
        ]);
        const authTag = cipher.getAuthTag();
        return Buffer.concat([iv, authTag, encrypted]);
    }
    decryptKey(encryptedData) {
        const iv = encryptedData.subarray(0, 16);
        const authTag = encryptedData.subarray(16, 32);
        const encryptedKey = encryptedData.subarray(32);
        const decipher = crypto.createDecipheriv('aes-256-gcm', this.encryptionKey, iv);
        decipher.setAuthTag(authTag);
        return Buffer.concat([
            decipher.update(encryptedKey),
            decipher.final(),
        ]).toString('utf8');
    }
    decryptKeyFromString(encryptedString) {
        const encryptedBuffer = Buffer.from(encryptedString, 'base64');
        return this.decryptKey(encryptedBuffer);
    }
    getKeyPath(userId, keyId) {
        return path.join(this.keyBasePath, userId, keyId, 'private.key');
    }
    async cleanupKeyDirectory(keyPath) {
        const directory = path.dirname(keyPath);
        const files = await fs.readdir(directory);
        if (files.length === 0) {
            await fs.rmdir(directory);
            await this.cleanupKeyDirectory(directory);
        }
    }
};
exports.KeyStorageService = KeyStorageService;
exports.KeyStorageService = KeyStorageService = KeyStorageService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_1.ConfigService])
], KeyStorageService);
