import { f as defineAdminEventHandler, $ as getAuthRequestContext, q as readBody, c as createError, ak as verifyMfaChallenge, a2 as emitAdminLoginFailed, ag as findAdminUserById, a6 as getAdminMfaState, ax as findRecoveryCodeMatch, ap as updateRecoveryHashes, ai as verifyTotp, ad as logAuditEventAsync, ay as touchMfaVerifiedAt, ao as generateAdminJWTWithMfa, ab as emitAdminAfterLogin } from '../../../../../nitro/nitro.mjs';
import 'node:crypto';
import 'jsonwebtoken';
import 'node:fs';
import 'node:module';
import 'node:path';
import 'node:url';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'pino';
import 'drizzle-orm/better-sqlite3';
import 'drizzle-orm/node-postgres';
import 'drizzle-orm/mysql2';
import 'better-sqlite3';
import 'pg';
import 'mysql2/promise';
import 'drizzle-orm';
import 'fs';
import 'path';
import 'prom-client';
import 'bcryptjs';
import '@node-rs/argon2';
import 'node:async_hooks';
import 'crypto';
import 'node:dns';
import 'node:util';
import 'node:net';
import 'fs/promises';
import 'url';
import 'semver';

const verify_post = defineAdminEventHandler("admin:auth:mfa:verify", async (event) => {
  var _a;
  const reqCtx = getAuthRequestContext(event);
  const body = await readBody(event);
  const challengeToken = body == null ? void 0 : body.challengeToken;
  const code = body == null ? void 0 : body.code;
  const useRecovery = Boolean(body == null ? void 0 : body.useRecovery);
  if (!challengeToken || !code) {
    throw createError({
      statusCode: 400,
      statusMessage: "Bad Request",
      message: "challengeToken and code are required"
    });
  }
  const challenge = verifyMfaChallenge(challengeToken);
  if (!challenge) {
    await emitAdminLoginFailed("<challenge>", "mfa_challenge_expired", reqCtx);
    throw createError({
      statusCode: 401,
      statusMessage: "Unauthorized",
      message: "Challenge token is invalid or expired"
    });
  }
  if (challenge.purpose !== "login") {
    throw createError({
      statusCode: 400,
      statusMessage: "Bad Request",
      message: "Use enrollment flow for this challenge"
    });
  }
  const adminUser = await findAdminUserById(challenge.sub);
  if (!adminUser) {
    throw createError({
      statusCode: 401,
      statusMessage: "Unauthorized",
      message: "User not found"
    });
  }
  const state = await getAdminMfaState(adminUser.id);
  if (!state || !state.enabled || !state.secret) {
    throw createError({
      statusCode: 400,
      statusMessage: "Bad Request",
      message: "MFA is not enabled for this account"
    });
  }
  let valid = false;
  let usedRecovery = false;
  if (useRecovery) {
    const matched = findRecoveryCodeMatch(code, state.recoveryHashes);
    if (matched) {
      valid = true;
      usedRecovery = true;
      const remaining = state.recoveryHashes.filter((h) => h !== matched);
      await updateRecoveryHashes(adminUser.id, remaining);
    }
  } else {
    valid = verifyTotp(state.secret, code.trim());
  }
  if (!valid) {
    await emitAdminLoginFailed(adminUser.email, "mfa_invalid_code", reqCtx);
    logAuditEventAsync({
      action: "mfa.failed",
      actor: {
        type: "admin",
        id: adminUser.id,
        displayName: adminUser.username,
        email: adminUser.email,
        role: adminUser.role
      },
      target: { entityType: "admin_user", entityId: adminUser.id, displayName: adminUser.username },
      ip: reqCtx.ip,
      userAgent: reqCtx.userAgent,
      outcome: "failed",
      metadata: { method: useRecovery ? "recovery" : "totp" }
    });
    throw createError({
      statusCode: 401,
      statusMessage: "Unauthorized",
      message: "Invalid MFA code"
    });
  }
  await touchMfaVerifiedAt(adminUser.id);
  const token = generateAdminJWTWithMfa(
    {
      id: adminUser.id,
      username: adminUser.username,
      email: adminUser.email,
      role: adminUser.role,
      tid: challenge.tid
    },
    {
      factor: "mfa",
      baseAmr: ((_a = challenge.baseAmr) == null ? void 0 : _a.length) ? challenge.baseAmr : ["pwd"]
    }
  );
  await emitAdminAfterLogin(
    adminUser.id,
    adminUser.email,
    adminUser.username,
    adminUser.role,
    reqCtx
  );
  logAuditEventAsync({
    action: usedRecovery ? "mfa.recovery_used" : "mfa.verified",
    actor: {
      type: "admin",
      id: adminUser.id,
      displayName: adminUser.username,
      email: adminUser.email,
      role: adminUser.role
    },
    target: { entityType: "admin_user", entityId: adminUser.id, displayName: adminUser.username },
    ip: reqCtx.ip,
    userAgent: reqCtx.userAgent,
    outcome: "success",
    metadata: usedRecovery ? { remaining_recovery_codes: state.recoveryHashes.length - 1 } : void 0
  });
  return {
    success: true,
    data: {
      token,
      user: {
        id: adminUser.id,
        username: adminUser.username,
        email: adminUser.email,
        firstName: adminUser.firstName,
        lastName: adminUser.lastName,
        role: adminUser.role
      },
      recoveryCodesRemaining: usedRecovery ? state.recoveryHashes.length - 1 : state.recoveryHashes.length
    }
  };
});

export { verify_post as default };
//# sourceMappingURL=verify.post.mjs.map
