style: run prettier on entire codebase

This commit is contained in:
BOHA
2026-03-24 19:59:14 +01:00
parent 872be42107
commit 3c167cf5c4
148 changed files with 26740 additions and 13990 deletions

View File

@@ -1,25 +1,27 @@
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 { 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';
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 { 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<void> {
export default async function totpRoutes(
fastify: FastifyInstance,
): Promise<void> {
// GET - generate new TOTP secret
fastify.get('/setup', { preHandler: requireAuth }, async (request, reply) => {
fastify.get("/setup", { preHandler: requireAuth }, async (request, reply) => {
const secret = new OTPAuthLib.Secret();
const totp = new OTPAuthLib.TOTP({
issuer: 'BOHA Automation',
issuer: "BOHA Automation",
label: request.authData!.email,
secret,
algorithm: 'SHA1',
algorithm: "SHA1",
digits: 6,
period: 30,
});
@@ -31,206 +33,273 @@ export default async function totpRoutes(fastify: FastifyInstance): Promise<void
});
// POST - enable TOTP
fastify.post('/enable', { preHandler: requireAuth, bodyLimit: 10240 }, async (request, reply) => {
const body = request.body as Record<string, unknown>;
const { secret, code } = body;
fastify.post(
"/enable",
{ preHandler: requireAuth, bodyLimit: 10240 },
async (request, reply) => {
const body = request.body as Record<string, unknown>;
const { secret, code } = body;
if (!secret || !code) {
return error(reply, 'Secret a kód jsou povinné', 400);
}
if (!secret || !code) {
return error(reply, "Secret a kód jsou povinné", 400);
}
// Verify the code first
const totp = new OTPAuthLib.TOTP({
secret: OTPAuthLib.Secret.fromBase32(String(secret)),
algorithm: 'SHA1',
digits: 6,
period: 30,
});
// Verify the code first
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);
}
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));
}
// 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));
}
// Encrypt and store
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),
},
});
// Encrypt and store
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');
});
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<string, unknown>;
fastify.put(
"/disable",
{ preHandler: requireAuth },
async (request, reply) => {
const body = request.body as Record<string, unknown>;
if (!body.code) {
return error(reply, 'TOTP kód je povinný pro deaktivaci', 400);
}
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 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);
}
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 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');
});
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 },
});
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 });
});
return success(reply, { totp_enabled: user?.totp_enabled ?? false });
},
);
// GET - check if 2FA is required company-wide
fastify.get('/required', { preHandler: [requireAuth, requirePermission('settings.security')] }, async (request, reply) => {
const settings = await prisma.company_settings.findFirst({
select: { require_2fa: true },
});
fastify.get(
"/required",
{ preHandler: [requireAuth, requirePermission("settings.security")] },
async (request, reply) => {
const settings = await prisma.company_settings.findFirst({
select: { require_2fa: true },
});
return success(reply, { require_2fa: settings?.require_2fa ?? false });
});
return success(reply, { require_2fa: settings?.require_2fa ?? false });
},
);
// POST - toggle mandatory 2FA
fastify.post('/required', { preHandler: [requireAuth, requirePermission('settings.security')], bodyLimit: 10240 }, async (request, reply) => {
const body = request.body as Record<string, unknown>;
fastify.post(
"/required",
{
preHandler: [requireAuth, requirePermission("settings.security")],
bodyLimit: 10240,
},
async (request, reply) => {
const body = request.body as Record<string, unknown>;
const required = body.required === true || body.required === 1 || body.required === '1';
await prisma.company_settings.updateMany({
data: { require_2fa: required },
});
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é';
const message = required
? "2FA je nyní povinné pro všechny uživatele"
: "2FA již není povinné";
return success(reply, null, 200, message);
});
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;
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 tokenHash = crypto
.createHash("sha256")
.update(login_token)
.digest("hex");
const storedToken = await prisma.totp_login_tokens.findFirst({
where: { token_hash: tokenHash },
});
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 (!storedToken || new Date(storedToken.expires_at) < new Date()) {
return error(reply, "Neplatný nebo expirovaný login token", 401);
}
}
if (matchIndex === -1) {
return error(reply, 'Neplatný záložní kód', 401);
}
const user = await prisma.users.findUnique({
where: { id: storedToken.user_id },
include: { roles: true },
});
// Remove used backup code
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(),
},
});
if (!user || !user.totp_backup_codes) {
return error(reply, "Uživatel nenalezen", 401);
}
// Delete used login token
await prisma.totp_login_tokens.delete({ where: { id: storedToken.id } });
const backupCodes: string[] = JSON.parse(
user.totp_backup_codes as string,
);
let matchIndex = -1;
// 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);
}
for (let i = 0; i < backupCodes.length; i++) {
const isMatch = await bcrypt.compare(String(code), backupCodes[i]);
if (isMatch) {
matchIndex = i;
break;
}
}
const jwt = await import('jsonwebtoken');
const { config } = await import('../../config/env');
if (matchIndex === -1) {
return error(reply, "Neplatný záložní kód", 401);
}
const accessToken = jwt.default.sign(
{ sub: user.id, username: user.username, role: user.roles?.name ?? null },
config.jwt.secret,
{ expiresIn: config.jwt.accessTokenExpiry },
);
// Remove used backup code
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(),
},
});
const refreshTokenRaw = crypto.randomBytes(32).toString('hex');
const refreshTokenHash = crypto.createHash('sha256').update(refreshTokenRaw).digest('hex');
// Delete used login token
await prisma.totp_login_tokens.delete({ where: { id: storedToken.id } });
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,
},
});
// 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);
}
reply.setCookie('refresh_token', refreshTokenRaw, {
httpOnly: true,
secure: config.isProduction,
sameSite: 'strict',
path: '/api/admin',
maxAge: config.jwt.refreshTokenSessionExpiry,
});
const jwt = await import("jsonwebtoken");
const { config } = await import("../../config/env");
return success(reply, { access_token: accessToken, user: authData });
});
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 });
},
);
}