import { f as defineAdminEventHandler, a5 as isMfaEnabledGlobally, c as createError, q as readBody, ak as verifyMfaChallenge, W as requireAdminAuth, ag as findAdminUserById, a6 as getAdminMfaState, ai as verifyTotp, ad as logAuditEventAsync, t as getAdminActor, al as generateRecoveryCodes, am as hashRecoveryCodes, an as activateMfa, a4 as getDefaultTenantId, ao as generateAdminJWTWithMfa, $ as getAuthRequestContext, ab as emitAdminAfterLogin, a3 as tryGetTenantContext } 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 enable_post = defineAdminEventHandler("admin:auth:mfa:enable", async (event) => {
  var _a, _b;
  if (!isMfaEnabledGlobally()) {
    throw createError({
      statusCode: 403,
      statusMessage: "Forbidden",
      message: "MFA is disabled by site configuration"
    });
  }
  const body = await readBody(event);
  const code = body == null ? void 0 : body.code;
  const challengeToken = body == null ? void 0 : body.challengeToken;
  if (!code) {
    throw createError({
      statusCode: 400,
      statusMessage: "Bad Request",
      message: "code is required"
    });
  }
  let adminUserId;
  let viaChallenge = false;
  let challengeTenantId = null;
  let challengeBaseAmr = ["pwd"];
  if (challengeToken) {
    const challenge = verifyMfaChallenge(challengeToken);
    if (!challenge) {
      throw createError({
        statusCode: 401,
        statusMessage: "Unauthorized",
        message: "Challenge token is invalid or expired"
      });
    }
    if (challenge.purpose !== "enroll") {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Challenge is not for enrollment"
      });
    }
    adminUserId = challenge.sub;
    challengeTenantId = challenge.tid;
    challengeBaseAmr = ((_a = challenge.baseAmr) == null ? void 0 : _a.length) ? challenge.baseAmr : ["pwd"];
    viaChallenge = true;
  } else {
    await requireAdminAuth(event);
    const ctxUser = event.context.adminUser;
    if (!ctxUser) {
      throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
    }
    adminUserId = ctxUser.id;
  }
  const adminUser = await findAdminUserById(adminUserId);
  if (!adminUser) {
    throw createError({
      statusCode: 401,
      statusMessage: "Unauthorized",
      message: "User not found"
    });
  }
  const state = await getAdminMfaState(adminUser.id);
  if (!state || !state.pendingSecret) {
    throw createError({
      statusCode: 400,
      statusMessage: "Bad Request",
      message: "No pending MFA enrollment. Call /mfa/setup first."
    });
  }
  if (state.enabled) {
    throw createError({
      statusCode: 409,
      statusMessage: "Conflict",
      message: "MFA is already enabled"
    });
  }
  if (!verifyTotp(state.pendingSecret, code.trim())) {
    logAuditEventAsync({
      action: "mfa.failed",
      actor: viaChallenge ? {
        type: "admin",
        id: adminUser.id,
        displayName: adminUser.username,
        email: adminUser.email,
        role: adminUser.role
      } : getAdminActor(event),
      target: { entityType: "admin_user", entityId: adminUser.id, displayName: adminUser.username },
      outcome: "failed",
      metadata: { phase: "enrollment" }
    });
    throw createError({
      statusCode: 401,
      statusMessage: "Unauthorized",
      message: "Invalid TOTP code"
    });
  }
  const recoveryCodes = generateRecoveryCodes();
  const hashes = hashRecoveryCodes(recoveryCodes);
  await activateMfa(adminUser.id, state.pendingSecret, hashes);
  logAuditEventAsync({
    action: "mfa.enabled",
    actor: viaChallenge ? {
      type: "admin",
      id: adminUser.id,
      displayName: adminUser.username,
      email: adminUser.email,
      role: adminUser.role
    } : getAdminActor(event),
    target: { entityType: "admin_user", entityId: adminUser.id, displayName: adminUser.username },
    outcome: "success"
  });
  if (viaChallenge) {
    const tenantId2 = challengeTenantId != null ? challengeTenantId : await getDefaultTenantId();
    const token2 = generateAdminJWTWithMfa(
      {
        id: adminUser.id,
        username: adminUser.username,
        email: adminUser.email,
        role: adminUser.role,
        tid: tenantId2
      },
      { factor: "mfa", baseAmr: challengeBaseAmr }
    );
    const reqCtx = getAuthRequestContext(event);
    await emitAdminAfterLogin(
      adminUser.id,
      adminUser.email,
      adminUser.username,
      adminUser.role,
      reqCtx
    );
    return {
      success: true,
      data: {
        token: token2,
        recoveryCodes,
        user: {
          id: adminUser.id,
          username: adminUser.username,
          email: adminUser.email,
          firstName: adminUser.firstName,
          lastName: adminUser.lastName,
          role: adminUser.role
        }
      }
    };
  }
  const tenant = tryGetTenantContext(event);
  const tenantId = (_b = tenant == null ? void 0 : tenant.id) != null ? _b : await getDefaultTenantId();
  const token = generateAdminJWTWithMfa(
    {
      id: adminUser.id,
      username: adminUser.username,
      email: adminUser.email,
      role: adminUser.role,
      tid: tenantId
    },
    { factor: "mfa", baseAmr: ["pwd"] }
  );
  return {
    success: true,
    data: {
      token,
      recoveryCodes
    }
  };
});

export { enable_post as default };
//# sourceMappingURL=enable.post.mjs.map
