import { FastifyInstance } from "fastify"; import crypto from "crypto"; import bcrypt from "bcryptjs"; import prisma from "../../config/database"; import { requireAuth, requirePermission } from "../../middleware/auth"; import { success, error } from "../../utils/response"; import { encrypt } from "../../utils/encryption"; import { getSystemSettings } from "../../services/system-settings"; import { OTPAuth } from "../../utils/totp"; import * as OTPAuthLib from "otpauth"; import { logAudit } from "../../services/audit"; import { parseBody } from "../../schemas/common"; import { TotpBackupSchema } from "../../schemas/auth.schema"; export default async function totpRoutes( fastify: FastifyInstance, ): Promise { // GET - generate new TOTP secret fastify.get("/setup", { preHandler: requireAuth }, async (request, reply) => { const settings = await getSystemSettings(); const companyName = ( await prisma.company_settings.findFirst({ select: { company_name: true }, }) )?.company_name || settings.smtp_from_name || "System"; const secret = new OTPAuthLib.Secret(); const totp = new OTPAuthLib.TOTP({ issuer: companyName, label: request.authData!.email, secret, algorithm: "SHA1", digits: 6, period: 30, }); return success(reply, { secret: secret.base32, uri: totp.toString(), }); }); // POST - enable TOTP fastify.post( "/enable", { preHandler: requireAuth, bodyLimit: 10240 }, async (request, reply) => { const body = request.body as Record; const { secret, code } = body; if (!secret || !code) { return error(reply, "Secret a kód jsou povinné", 400); } const totp = new OTPAuthLib.TOTP({ secret: OTPAuthLib.Secret.fromBase32(String(secret)), algorithm: "SHA1", digits: 6, period: 30, }); const delta = totp.validate({ token: String(code), window: 1 }); if (delta === null) { return error(reply, "Neplatný TOTP kód", 400); } // Generate 8 backup codes const backupCodesPlain: string[] = []; const backupCodesHashed: string[] = []; for (let i = 0; i < 8; i++) { const code = crypto.randomBytes(4).toString("hex").toUpperCase(); backupCodesPlain.push(code); backupCodesHashed.push(bcrypt.hashSync(code, 10)); } const encryptedSecret = encrypt(String(secret)); await prisma.users.update({ where: { id: request.authData!.userId }, data: { totp_secret: encryptedSecret, totp_enabled: true, totp_backup_codes: JSON.stringify(backupCodesHashed), }, }); await logAudit({ request, authData: request.authData, action: "update", entityType: "user", entityId: request.authData!.userId, description: "2FA aktivováno", }); return success( reply, { backup_codes: backupCodesPlain }, 200, "2FA aktivováno", ); }, ); // PUT - disable TOTP fastify.put( "/disable", { preHandler: requireAuth }, async (request, reply) => { const body = request.body as Record; if (!body.code) { return error(reply, "TOTP kód je povinný pro deaktivaci", 400); } const user = await prisma.users.findUnique({ where: { id: request.authData!.userId }, }); if (!user?.totp_secret) { return error(reply, "2FA není aktivní", 400); } const isValid = OTPAuth.verify(user.totp_secret, String(body.code)); if (!isValid) { return error(reply, "Neplatný TOTP kód", 400); } await prisma.users.update({ where: { id: request.authData!.userId }, data: { totp_secret: null, totp_enabled: false, totp_backup_codes: null, }, }); await logAudit({ request, authData: request.authData, action: "update", entityType: "user", entityId: request.authData!.userId, description: "2FA deaktivováno", }); return success(reply, null, 200, "2FA deaktivováno"); }, ); // GET - TOTP status for current user fastify.get( "/status", { preHandler: requireAuth }, async (request, reply) => { const user = await prisma.users.findUnique({ where: { id: request.authData!.userId }, select: { totp_enabled: true }, }); return success(reply, { totp_enabled: user?.totp_enabled ?? false }); }, ); // GET - check if 2FA is required company-wide fastify.get( "/required", { preHandler: [requireAuth, requirePermission("settings.manage")] }, async (request, reply) => { const settings = await prisma.company_settings.findFirst({ select: { require_2fa: true }, }); return success(reply, { require_2fa: settings?.require_2fa ?? false }); }, ); // POST - toggle mandatory 2FA fastify.post( "/required", { preHandler: [requireAuth, requirePermission("settings.manage")], bodyLimit: 10240, }, async (request, reply) => { const body = request.body as Record; const required = body.required === true || body.required === 1 || body.required === "1"; await prisma.company_settings.updateMany({ data: { require_2fa: required }, }); const message = required ? "2FA je nyní povinné pro všechny uživatele" : "2FA již není povinné"; return success(reply, null, 200, message); }, ); // POST - verify backup code (pre-auth, no requireAuth) fastify.post( "/backup-verify", { bodyLimit: 10240 }, async (request, reply) => { const parsed = parseBody(TotpBackupSchema, request.body); if ("error" in parsed) return error(reply, parsed.error, 400); const { login_token, backup_code: code } = parsed.data; const tokenHash = crypto .createHash("sha256") .update(login_token) .digest("hex"); const storedToken = await prisma.totp_login_tokens.findFirst({ where: { token_hash: tokenHash }, }); if (!storedToken || new Date(storedToken.expires_at) < new Date()) { return error(reply, "Neplatný nebo expirovaný login token", 401); } const user = await prisma.users.findUnique({ where: { id: storedToken.user_id }, include: { roles: true }, }); if (!user || !user.totp_backup_codes) { return error(reply, "Uživatel nenalezen", 401); } const backupCodes: string[] = JSON.parse( user.totp_backup_codes as string, ); let matchIndex = -1; for (let i = 0; i < backupCodes.length; i++) { const isMatch = await bcrypt.compare(String(code), backupCodes[i]); if (isMatch) { matchIndex = i; break; } } if (matchIndex === -1) { return error(reply, "Neplatný záložní kód", 401); } backupCodes.splice(matchIndex, 1); await prisma.users.update({ where: { id: user.id }, data: { totp_backup_codes: JSON.stringify(backupCodes), failed_login_attempts: 0, locked_until: null, last_login: new Date(), }, }); await prisma.totp_login_tokens.delete({ where: { id: storedToken.id } }); // Create tokens (same as /login/totp flow) const { loadAuthData } = await import("../../services/auth"); const authData = await loadAuthData(user.id); if (!authData) { return error(reply, "Chyba načítání uživatele", 500); } const jwt = await import("jsonwebtoken"); const { config } = await import("../../config/env"); const accessToken = jwt.default.sign( { sub: user.id, username: user.username, role: user.roles?.name ?? null, }, config.jwt.secret, { expiresIn: config.jwt.accessTokenExpiry }, ); const refreshTokenRaw = crypto.randomBytes(32).toString("hex"); const refreshTokenHash = crypto .createHash("sha256") .update(refreshTokenRaw) .digest("hex"); await prisma.refresh_tokens.create({ data: { user_id: user.id, token_hash: refreshTokenHash, expires_at: new Date( Date.now() + config.jwt.refreshTokenSessionExpiry * 1000, ), remember_me: false, ip_address: request.ip, user_agent: request.headers["user-agent"] ?? null, }, }); reply.setCookie("refresh_token", refreshTokenRaw, { httpOnly: true, secure: config.isProduction, sameSite: "strict", path: "/api/admin", maxAge: config.jwt.refreshTokenSessionExpiry, }); return success(reply, { access_token: accessToken, user: authData }); }, ); }