"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.keyFingerprint = keyFingerprint;
exports.encryptSecret = encryptSecret;
exports.decryptSecret = decryptSecret;
const crypto = __importStar(require("crypto"));
const config_1 = require("./config");
/**
 * Shared AES-256-GCM encrypt/decrypt for any small secret stored on disk
 * (rsync passwords, GitHub PATs, etc.).
 *
 * Each caller provides a `label` (e.g. `'sync'`, `'hub'`) that namespaces
 * the key derivation — so a secret encrypted for one subsystem cannot be
 * decrypted by another, even on the same ccweb install.  This is defense
 * in depth against a bug in subsystem X leaking the plaintext of Y.
 *
 * The effective key is `SHA-256("ccweb-<label>:" + jwtSecret)`.  Because
 * `jwtSecret` lives in `config.json`, moving a ccweb install to a different
 * machine (different jwtSecret) makes all at-rest secrets unreadable —
 * the right "fail open, force re-entry" behavior.  Each encrypted blob is
 * paired with a 4-byte fingerprint so callers can detect the rotation
 * case and surface "needs re-entry" rather than return empty plaintext.
 */
function getKey(label) {
    const secret = (0, config_1.getConfig)().jwtSecret;
    return crypto.createHash('sha256').update(`ccweb-${label}:${secret}`).digest();
}
function keyFingerprint(label) {
    return getKey(label).subarray(0, 4).toString('hex');
}
function encryptSecret(label, plain) {
    if (!plain)
        return { enc: '', fp: '' };
    const iv = crypto.randomBytes(12);
    const cipher = crypto.createCipheriv('aes-256-gcm', getKey(label), iv);
    const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
    const tag = cipher.getAuthTag();
    return {
        enc: Buffer.concat([iv, tag, enc]).toString('base64'),
        fp: keyFingerprint(label),
    };
}
function decryptSecret(label, blob, expectedFp) {
    if (!blob)
        return '';
    if (expectedFp && expectedFp !== keyFingerprint(label))
        return '';
    try {
        const buf = Buffer.from(blob, 'base64');
        if (buf.length < 28)
            return '';
        const iv = buf.subarray(0, 12);
        const tag = buf.subarray(12, 28);
        const enc = buf.subarray(28);
        const decipher = crypto.createDecipheriv('aes-256-gcm', getKey(label), iv);
        decipher.setAuthTag(tag);
        return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8');
    }
    catch {
        return '';
    }
}
//# sourceMappingURL=crypto-at-rest.js.map