/**
 * Bridge 面板登录认证服务
 *
 * 管理面板登录凭据与会话，凭据读取自 ~/.aws-bridge/config.json，
 * panelUsername/panelPassword 字段均不配置时默认 root/root。
 *
 * 会话使用服务端内存存储 + HttpOnly Cookie 实现，无需外部依赖。
 */
import { randomUUID } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { logger } from "../utils/logger.js";
const SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24 小时
const SESSION_CLEANUP_INTERVAL_MS = 60 * 60 * 1000; // 每小时清理一次
const sessions = new Map();
let cleanupTimer = null;
function startCleanupTimer() {
    if (cleanupTimer)
        return;
    cleanupTimer = setInterval(() => {
        const now = Date.now();
        let expired = 0;
        for (const [token, session] of sessions) {
            if (now - session.lastUsedAt > SESSION_TTL_MS) {
                sessions.delete(token);
                expired++;
            }
        }
        if (expired > 0) {
            logger.info(`[panel-auth] 已清理 ${expired} 个过期面板会话`);
        }
    }, SESSION_CLEANUP_INTERVAL_MS);
    cleanupTimer.unref();
}
/** 生成一个新会话并返回会话 token */
export function createSession() {
    startCleanupTimer();
    const token = randomUUID();
    const now = Date.now();
    sessions.set(token, { token, createdAt: now, lastUsedAt: now });
    return token;
}
/** 校验会话 token 是否有效；通过后更新最后使用时间 */
export function validateSession(token) {
    if (!token)
        return false;
    const session = sessions.get(token);
    if (!session)
        return false;
    const now = Date.now();
    if (now - session.lastUsedAt > SESSION_TTL_MS) {
        sessions.delete(token);
        return false;
    }
    session.lastUsedAt = now;
    return true;
}
/** 销毁指定会话（登出） */
export function destroySession(token) {
    sessions.delete(token);
}
let cachedCredentials = null;
function getConfigFilePath() {
    return path.join(os.homedir(), ".aws-bridge", "config.json");
}
function readCredentialsFromConfig() {
    const configPath = getConfigFilePath();
    if (!existsSync(configPath))
        return null;
    try {
        const raw = readFileSync(configPath, "utf-8");
        const parsed = JSON.parse(raw);
        const username = String(parsed.panelUsername || "").trim();
        const password = String(parsed.panelPassword || "").trim();
        if (username && password) {
            return { username, password };
        }
    }
    catch {
        // 配置不可读时回退到默认值
    }
    return null;
}
/** 获取面板登录凭据，未配置时返回默认值 root/root */
export function getPanelCredentials() {
    if (cachedCredentials)
        return cachedCredentials;
    const fromConfig = readCredentialsFromConfig();
    if (fromConfig) {
        cachedCredentials = fromConfig;
        return fromConfig;
    }
    cachedCredentials = { username: "root", password: "root" };
    return cachedCredentials;
}
/** 校验用户名密码 */
export function validateCredentials(username, password) {
    const creds = getPanelCredentials();
    return username === creds.username && password === creds.password;
}
/** 清除凭据缓存（配置文件变更后调用） */
export function clearCredentialsCache() {
    cachedCredentials = null;
}
