"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.hasHubToken = hasHubToken;
exports.getHubToken = getHubToken;
exports.getHubTokenStatus = getHubTokenStatus;
exports.setHubToken = setHubToken;
exports.clearHubToken = clearHubToken;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const crypto = __importStar(require("crypto"));
const config_1 = require("./config");
const crypto_at_rest_1 = require("./crypto-at-rest");
/**
 * Per-user GitHub PAT storage for one-click ccweb-hub submissions.
 *
 * Shape on disk (one file per user):
 *   `<DATA_DIR>/hub-auth/<sha1(username)>.json`
 *   { username, tokenEnc, tokenFp }
 *
 * `tokenEnc` is AES-256-GCM encrypted via `crypto-at-rest` with label `"hub"`.
 * The token itself is user-supplied (GitHub fine-grained PAT the user creates
 * themselves), scoped to the ccweb-hub repo's Issues:write permission.  Each
 * user's token is independent — leaking one does not grant access to others.
 *
 * ccweb itself NEVER ships with a token. A bundled token would be extractable
 * from `backend/dist/` by every installed user (CLAUDE.md pitfalls #30).
 */
const AUTH_DIR = path.join(config_1.DATA_DIR, 'hub-auth');
function ensureDir() {
    if (!fs.existsSync(AUTH_DIR))
        fs.mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 });
}
function userFile(username) {
    const hash = crypto.createHash('sha1').update(`ccweb-hub-user:${username}`).digest('hex');
    return path.join(AUTH_DIR, `${hash}.json`);
}
function read(username) {
    try {
        const raw = fs.readFileSync(userFile(username), 'utf-8');
        const parsed = JSON.parse(raw);
        if (typeof parsed.username === 'string' &&
            typeof parsed.tokenEnc === 'string' &&
            typeof parsed.tokenFp === 'string') {
            return { username: parsed.username, tokenEnc: parsed.tokenEnc, tokenFp: parsed.tokenFp };
        }
        return null;
    }
    catch {
        return null;
    }
}
function hasHubToken(username) {
    const auth = read(username);
    return !!(auth && auth.tokenEnc);
}
/** Returns plaintext token (or null if none / wedged by jwtSecret rotation). */
function getHubToken(username) {
    const auth = read(username);
    if (!auth)
        return null;
    const plain = (0, crypto_at_rest_1.decryptSecret)('hub', auth.tokenEnc, auth.tokenFp);
    return plain || null;
}
/** Public-facing status. `needsReset` = token stored but key fingerprint no
 *  longer matches → jwtSecret rotated; UI should prompt the user to re-enter. */
function getHubTokenStatus(username) {
    const auth = read(username);
    if (!auth || !auth.tokenEnc)
        return { configured: false, needsReset: false };
    const plain = (0, crypto_at_rest_1.decryptSecret)('hub', auth.tokenEnc, auth.tokenFp);
    if (plain)
        return { configured: true, needsReset: false };
    return { configured: false, needsReset: true };
}
function setHubToken(username, plainToken) {
    ensureDir();
    const { enc, fp } = (0, crypto_at_rest_1.encryptSecret)('hub', plainToken);
    (0, config_1.atomicWriteSync)(userFile(username), JSON.stringify({ username, tokenEnc: enc, tokenFp: fp }, null, 2));
    try {
        fs.chmodSync(userFile(username), 0o600);
    }
    catch { /* ignore */ }
}
function clearHubToken(username) {
    try {
        fs.unlinkSync(userFile(username));
    }
    catch { /* ignore missing */ }
}
//# sourceMappingURL=hub-auth.js.map