"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.invalidateSessionBefore = void 0;
exports.srpServerStep1 = srpServerStep1;
exports.srpCheck = srpCheck;
exports.getCurrentUsername = getCurrentUsername;
exports.clearTextLogin = clearTextLogin;
exports.setLoggedIn = setLoggedIn;
const perm_1 = require("./perm");
const cross_const_1 = require("./cross-const");
const srp = __importStar(require("tssrp6a"));
const srp_1 = require("./srp");
const cross_1 = require("./cross");
const expiringCache_1 = require("./expiringCache");
const node_crypto_1 = require("node:crypto");
const events_1 = __importDefault(require("./events"));
const srp6aNimbusRoutines = new srp.SRPRoutines(new srp.SRPParameters());
async function srpServerStep1(account) {
    if (!account.srp)
        throw cross_const_1.HTTP_NOT_ACCEPTABLE;
    const [salt, verifier] = account.srp.split('|');
    if (!salt || !verifier)
        throw Error("malformed account");
    const srpSession = new srp.SRPServerSession(srp6aNimbusRoutines);
    const srpServer = await srpSession.step1(account.username, BigInt(salt), BigInt(verifier));
    return { srpServer, salt, pubKey: String(srpServer.B) }; // cast to string cause bigint can't be jsonized
}
const cache = (0, expiringCache_1.expiringCache)(60_000);
async function srpCheck(username, password) {
    const account = (0, perm_1.getAccount)(username);
    if (!account?.srp || !password)
        return;
    const k = (0, node_crypto_1.createHash)('sha256').update(username + password + account.srp).digest("hex");
    const good = await cache.try(k, async () => {
        const { srpServer, salt, pubKey } = await srpServerStep1(account);
        const client = await (0, srp_1.srpClientPart)(srp, username, password, salt, pubKey);
        return srpServer.step2(client.A, client.M1).then(() => true, () => false);
    });
    return good ? account : undefined;
}
function getCurrentUsername(ctx) {
    return ctx.state.account?.username || '';
}
async function clearTextLogin(ctx, u, p, via) {
    if (!p)
        return;
    if ((await events_1.default.emitAsync('attemptingLogin', { ctx, username: u, via }))?.isDefaultPrevented())
        return;
    const plugins = await events_1.default.emitAsync('clearTextLogin', { ctx, username: u, password: p, via }); // provide clear password to plugins
    const a = plugins?.some(x => x === true) ? (0, perm_1.getAccount)(u) : await srpCheck(u, p);
    if (!a && u)
        events_1.default.emit('failedLogin', { ctx, username: u, via });
    return a;
}
// centralized log-in state
async function setLoggedIn(ctx, username) {
    const s = ctx.session;
    if (!s)
        return ctx.throw(cross_const_1.HTTP_SERVER_ERROR, 'session');
    delete ctx.state.usernames;
    if (username === false) {
        if (s.username)
            events_1.default.emit('logout', ctx);
        delete ctx.state.account;
        ctx.session = null;
        return;
    }
    delete s.loggingIn; // clear pending SRP handshake state
    const a = ctx.state.account = (0, perm_1.getAccount)(username);
    if (!a)
        return;
    await events_1.default.emitAsync('finalizingLogin', { ctx, username, inputs: { ...ctx.state.params, ...ctx.query } });
    s.username = (0, perm_1.normalizeUsername)(username);
    s.ts = Date.now();
    const k = cross_const_1.ALLOW_SESSION_IP_CHANGE;
    s[k] = k in ctx.query || Boolean(ctx.state.params?.[k]) || undefined; // login APIs will get ctx.state.params, others can rely on ctx.query
    if (!a.expire && a.days_to_live)
        (0, perm_1.updateAccount)(a, { expire: new Date(Date.now() + a.days_to_live * cross_1.DAY) });
    await events_1.default.emitAsync('login', ctx);
}
// since session are currently stored in cookies, we need to store this information
exports.invalidateSessionBefore = new Map();
