import { f as defineAdminEventHandler, W as requireAdminAuth, a5 as isMfaEnabledGlobally, c as createError, q as readBody, ag as findAdminUserById, a6 as getAdminMfaState, ax as findRecoveryCodeMatch, ap as updateRecoveryHashes, ai as verifyTotp, ad as logAuditEventAsync, t as getAdminActor, ay as touchMfaVerifiedAt, a3 as tryGetTenantContext, a4 as getDefaultTenantId, ao as generateAdminJWTWithMfa } 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 stepUp_post = defineAdminEventHandler("admin:auth:mfa:step-up", async (event) => {
  var _a;
  await requireAdminAuth(event);
  if (!isMfaEnabledGlobally()) {
    throw createError({
      statusCode: 403,
      statusMessage: "Forbidden",
      message: "MFA is disabled by site configuration"
    });
  }
  const ctxUser = event.context.adminUser;
  if (!ctxUser) {
    throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
  }
  const body = await readBody(event);
  const code = body == null ? void 0 : body.code;
  const useRecovery = Boolean(body == null ? void 0 : body.useRecovery);
  if (!code) {
    throw createError({
      statusCode: 400,
      statusMessage: "Bad Request",
      message: "code is required"
    });
  }
  const adminUser = await findAdminUserById(ctxUser.id);
  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"
    });
  }
  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) {
    logAuditEventAsync({
      action: "mfa.step_up_failed",
      actor: getAdminActor(event),
      target: { entityType: "admin_user", entityId: adminUser.id, displayName: adminUser.username },
      outcome: "failed",
      metadata: { method: useRecovery ? "recovery" : "totp" }
    });
    throw createError({
      statusCode: 401,
      statusMessage: "Unauthorized",
      message: "Invalid MFA code"
    });
  }
  await touchMfaVerifiedAt(adminUser.id);
  const tenant = tryGetTenantContext(event);
  const tenantId = (_a = tenant == null ? void 0 : tenant.id) != null ? _a : await getDefaultTenantId();
  const token = generateAdminJWTWithMfa(
    {
      id: adminUser.id,
      username: adminUser.username,
      email: adminUser.email,
      role: adminUser.role,
      tid: tenantId
    },
    { factor: "mfa", baseAmr: ["pwd"] }
  );
  logAuditEventAsync({
    action: usedRecovery ? "mfa.recovery_used" : "mfa.step_up_verified",
    actor: getAdminActor(event),
    target: { entityType: "admin_user", entityId: adminUser.id, displayName: adminUser.username },
    outcome: "success",
    metadata: usedRecovery ? { phase: "step_up", remaining_recovery_codes: state.recoveryHashes.length - 1 } : { phase: "step_up" }
  });
  return {
    success: true,
    data: {
      token,
      recoveryCodesRemaining: usedRecovery ? state.recoveryHashes.length - 1 : state.recoveryHashes.length
    }
  };
});

export { stepUp_post as default };
//# sourceMappingURL=step-up.post.mjs.map
