"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.setEncryptionKey = setEncryptionKey;
exports.getEncryptionKey = getEncryptionKey;
exports.encrypt = encrypt;
exports.decrypt = decrypt;
const crypto = __importStar(require("crypto"));
const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 12;
const TAG_LENGTH = 16;
let _encryptionKey = null;
/**
 * Set the encryption key for OAuth token storage.
 * Called during OAuth initialization from start.ts.
 */
function setEncryptionKey(keyHex) {
    const buf = Buffer.from(keyHex, 'hex');
    if (buf.length !== 32) {
        throw new Error(`OAUTH_ENCRYPTION_KEY must be 32 bytes (64 hex chars), got ${buf.length}`);
    }
    _encryptionKey = buf;
}
/**
 * Get the encryption key. Reads from explicit config first,
 * then falls back to OAUTH_ENCRYPTION_KEY env var.
 */
function getEncryptionKey() {
    if (_encryptionKey)
        return _encryptionKey;
    const envKey = process.env.OAUTH_ENCRYPTION_KEY;
    if (envKey) {
        setEncryptionKey(envKey);
        return _encryptionKey;
    }
    throw new Error('OAuth encryption key not configured. Set OAUTH_ENCRYPTION_KEY or pass auth.oauth.encryptionKey in startup config.');
}
/**
 * Encrypt a plaintext string with AES-256-GCM.
 * Returns base64-encoded string: iv:ciphertext:tag
 */
function encrypt(plaintext) {
    const key = getEncryptionKey();
    const iv = crypto.randomBytes(IV_LENGTH);
    const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
    const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
    const tag = cipher.getAuthTag();
    // Pack as: iv + ciphertext + tag, then base64
    return Buffer.concat([iv, encrypted, tag]).toString('base64');
}
/**
 * Decrypt a base64-encoded AES-256-GCM ciphertext.
 */
function decrypt(encoded) {
    const key = getEncryptionKey();
    const buf = Buffer.from(encoded, 'base64');
    const iv = buf.subarray(0, IV_LENGTH);
    const tag = buf.subarray(buf.length - TAG_LENGTH);
    const ciphertext = buf.subarray(IV_LENGTH, buf.length - TAG_LENGTH);
    const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
    decipher.setAuthTag(tag);
    return decipher.update(ciphertext) + decipher.final('utf8');
}
