Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

feat(2FA): create API routes for users

Rudy B.7c51e1ce4a8e
diff --git a/src/app/api/2fa/disable/route.ts b/src/app/api/2fa/disable/route.ts
new file mode 100644
index 000000000..566a0d592
--- /dev/null
+++ b/src/app/api/2fa/disable/route.ts
@@ -0,0 +1,104 @@
+import { z } from 'zod';
+import prisma from '@/lib/prisma';
+import { parseRequest } from '@/lib/request';
+import { badRequest, forbidden, json } from '@/lib/response';
+import { decryptSecret } from '@/lib/two-factor/crypto';
+import { checkRateLimit, recordFailedAttempt, resetRateLimit } from '@/lib/two-factor/rate-limit';
+import { isOtpReplayed, markOtpUsed } from '@/lib/two-factor/replay-prevention';
+import { verifyTotp } from '@/lib/two-factor/totp';
+import { checkPassword } from '@/lib/password';
+import { getUser } from '@/queries/prisma/user';
+
+export async function POST(request: Request) {
+ const schema = z.object({
+ password: z.string(),
+ token: z.string().length(6),
+ });
+
+ const { auth, body, error } = await parseRequest(request, schema);
+
+ if (error) {
+ return error();
+ }
+
+ const userId = auth.user.id;
+ const { password, token } = body;
+
+ // Globally required
+ const globalSetting = await prisma.client.appSetting.findUnique({
+ where: { key: 'twoFactorRequiredGlobal' },
+ });
+ const isGlobalRequired = globalSetting?.value === 'true';
+
+ // Required for this user
+ const userRecord = await prisma.client.user.findUnique({
+ where: { id: userId },
+ select: { twoFactorRequired: true },
+ });
+ const isUserRequired = userRecord?.twoFactorRequired ?? false;
+
+ // Required for this user's teams
+ const userTeams = await prisma.client.teamUser.findMany({ where: { userId } });
+ const teamIds = userTeams.map(t => t.teamId);
+ const teamsWithRequirement = teamIds.length
+ ? await prisma.client.team.findMany({
+ where: { id: { in: teamIds }, twoFactorRequired: true },
+ })
+ : [];
+ const isTeamRequired = teamsWithRequirement.length > 0;
+
+ // Cannot disable 2FA if required
+ if (isGlobalRequired || isUserRequired || isTeamRequired) {
+ return forbidden({
+ code: 'two-factor-error-disable-not-allowed',
+ message: '2FA is required and cannot be disabled',
+ });
+ }
+
+ // Verify password
+ const userWithPw = await getUser(userId, { includePassword: true });
+ if (!userWithPw || !checkPassword(password, userWithPw.password)) {
+ return badRequest({
+ code: 'two-factor-error-incorrect-password',
+ message: 'Incorrect password',
+ });
+ }
+
+ // Verify if 2FA is enabled
+ const twoFactor = await prisma.client.twoFactorAuth.findUnique({ where: { userId } });
+ if (!twoFactor?.isEnabled) {
+ return badRequest({ code: 'two-factor-error-not-enabled', message: '2FA is not enabled' });
+ }
+
+ // Verify rate limit
+ const rateCheck = await checkRateLimit(userId);
+ if (!rateCheck.allowed) {
+ return badRequest({
+ code: 'two-factor-error-too-many-attempts',
+ message: 'Too many failed attempts',
+ lockedUntil: rateCheck.lockedUntil,
+ });
+ }
+
+ // Prevent OTP replay
+ if (await isOtpReplayed(userId, token)) {
+ return badRequest({ code: 'two-factor-error-code-used', message: 'Code already used' });
+ }
+
+ // Verify TOTP
+ const secret = decryptSecret(twoFactor.secret);
+ if (!(await verifyTotp(token, secret))) {
+ await recordFailedAttempt(userId);
+ return badRequest({
+ code: 'two-factor-error-invalid-code',
+ message: 'Invalid verification code',
+ });
+ }
+
+ await markOtpUsed(userId, token);
+ await prisma.client.twoFactorAuth.delete({ where: { userId } });
+ await prisma.client.twoFactorBackupCode.deleteMany({ where: { userId } });
+ await resetRateLimit(userId);
+
+ return json({ ok: true });
+}
diff --git a/src/app/api/2fa/setup/cancel/route.ts b/src/app/api/2fa/setup/cancel/route.ts
new file mode 100644
index 000000000..76df6cb68
--- /dev/null
+++ b/src/app/api/2fa/setup/cancel/route.ts
@@ -0,0 +1,19 @@
+import prisma from '@/lib/prisma';
+import { parseRequest } from '@/lib/request';
+import { json } from '@/lib/response';
+
+export async function POST(request: Request) {
+ const { auth, error } = await parseRequest(request);
+
+ if (error) {
+ return error();
+ }
+
+ const userId = auth.user.id;
+
+ await prisma.client.twoFactorAuth.deleteMany({
+ where: { userId, isEnabled: false },
+ });
+
+ return json({ ok: true });
+}
diff --git a/src/app/api/2fa/setup/confirm/route.ts b/src/app/api/2fa/setup/confirm/route.ts
new file mode 100644
index 000000000..6c202b4fb
--- /dev/null
+++ b/src/app/api/2fa/setup/confirm/route.ts
@@ -0,0 +1,67 @@
+import { z } from 'zod';
+import prisma from '@/lib/prisma';
+import { parseRequest } from '@/lib/request';
+import { badRequest, json, unauthorized } from '@/lib/response';
+import { generateBackupCodes } from '@/lib/two-factor/backup-codes';
+import { decryptSecret } from '@/lib/two-factor/crypto';
+import { checkRateLimit, recordFailedAttempt, resetRateLimit } from '@/lib/two-factor/rate-limit';
+import { isOtpReplayed, markOtpUsed } from '@/lib/two-factor/replay-prevention';
+import { verifyTotp } from '@/lib/two-factor/totp';
+
+export async function POST(request: Request) {
+ const schema = z.object({ token: z.string().length(6) });
+
+ const { auth, body, error } = await parseRequest(request, schema);
+
+ if (error) {
+ return error();
+ }
+
+ const userId = auth.user.id;
+ const { token } = body;
+
+ const twoFactor = await prisma.client.twoFactorAuth.findUnique({ where: { userId } });
+
+ // Verify if 2FA is waiting for setup
+ if (!twoFactor || twoFactor.isEnabled) {
+ return badRequest({ message: 'No pending 2FA setup found' });
+ }
+
+ // Verify rate limit
+ const rateCheck = await checkRateLimit(userId);
+ if (!rateCheck.allowed) {
+ return badRequest({
+ code: 'rate-limited',
+ message: 'Too many failed attempts',
+ lockedUntil: rateCheck.lockedUntil,
+ });
+ }
+
+ // Prevent OTP replay
+ if (await isOtpReplayed(userId, token)) {
+ return badRequest({ code: 'otp-replayed', message: 'Code already used' });
+ }
+
+ // Verify TOTP
+ const secret = decryptSecret(twoFactor.secret);
+ if (!(await verifyTotp(token, secret))) {
+ await recordFailedAttempt(userId);
+ return badRequest({
+ code: 'two-factor-error-invalid-code',
+ message: 'Invalid verification code',
+ });
+ }
+
+ await prisma.client.twoFactorAuth.update({ where: { userId }, data: { isEnabled: true } });
+ await markOtpUsed(userId, token);
+ await resetRateLimit(userId);
+
+ const { plaintext, hashed } = await generateBackupCodes();
+
+ await prisma.client.twoFactorBackupCode.deleteMany({ where: { userId } });
+ await prisma.client.twoFactorBackupCode.createMany({
+ data: hashed.map(codeHash => ({ userId, codeHash })),
+ });
+
+ return json({ backupCodes: plaintext });
+}
diff --git a/src/app/api/2fa/setup/initiate/route.ts b/src/app/api/2fa/setup/initiate/route.ts
new file mode 100644
index 000000000..d55c2f7e6
--- /dev/null
+++ b/src/app/api/2fa/setup/initiate/route.ts
@@ -0,0 +1,38 @@
+import { parseRequest } from '@/lib/request';
+import { badRequest, json } from '@/lib/response';
+import { encryptSecret } from '@/lib/two-factor/crypto';
+import {
+ generateOtpAuthUri,
+ generateQrCodeDataUrl,
+ generateTotpSecret,
+} from '@/lib/two-factor/totp';
+import prisma from '@/lib/prisma';
+import { getUser } from '@/queries/prisma/user';
+
+export async function POST(request: Request) {
+ const { auth, error } = await parseRequest(request);
+
+ if (error) {
+ return error();
+ }
+
+ const userId = auth.user.id;
+ const user = await getUser(userId);
+
+ if (!user) {
+ return badRequest({ message: 'User not found' });
+ }
+
+ const secret = generateTotpSecret();
+ const encryptedSecret = encryptSecret(secret);
+ const otpAuthUri = generateOtpAuthUri(secret, user.username);
+ const qrCodeDataUrl = await generateQrCodeDataUrl(otpAuthUri);
+
+ await prisma.client.twoFactorAuth.upsert({
+ where: { userId },
+ update: { secret: encryptedSecret, isEnabled: false },
+ create: { userId, secret: encryptedSecret, isEnabled: false },
+ });
+
+ return json({ qrCodeDataUrl, manualKey: secret });
+}
diff --git a/src/app/api/2fa/status/route.ts b/src/app/api/2fa/status/route.ts
new file mode 100644
index 000000000..4da943af8
--- /dev/null
+++ b/src/app/api/2fa/status/route.ts
@@ -0,0 +1,44 @@
+import prisma from '@/lib/prisma';
+import { parseRequest } from '@/lib/request';
+import { json } from '@/lib/response';
+
+export async function GET(request: Request) {
+ const { auth, error } = await parseRequest(request);
+
+ if (error) {
+ return error();
+ }
+
+ const userId = auth.user.id;
+
+ const twoFactor = await prisma.client.twoFactorAuth.findUnique({ where: { userId } });
+ const isEnabled = twoFactor?.isEnabled ?? false;
+
+ // Globally required
+ const globalSetting = await prisma.client.appSetting.findUnique({
+ where: { key: 'twoFactorRequiredGlobal' },
+ });
+ const isGlobalRequired = globalSetting?.value === 'true';
+ if (isGlobalRequired) return json({ isEnabled, isRequired: true, requiredReason: 'global' });
+
+ // Required for this user
+ const userRecord = await prisma.client.user.findUnique({
+ where: { id: userId },
+ select: { twoFactorRequired: true },
+ });
+ const isUserRequired = userRecord?.twoFactorRequired ?? false;
+ if (isUserRequired) return json({ isEnabled, isRequired: true, requiredReason: 'user' });
+
+ // Required for this user's teams
+ const userTeams = await prisma.client.teamUser.findMany({ where: { userId } });
+ const teamIds = userTeams.map(t => t.teamId);
+ const teamsWithRequirement = teamIds.length
+ ? await prisma.client.team.findMany({
+ where: { id: { in: teamIds }, twoFactorRequired: true },
+ })
+ : [];
+ const isTeamRequired = teamsWithRequirement.length > 0;
+ if (isTeamRequired) return json({ isEnabled, isRequired: true, requiredReason: 'team' });
+
+ return json({ isEnabled, isRequired: false, requiredReason: null });
+}
diff --git a/src/app/api/2fa/verify/route.ts b/src/app/api/2fa/verify/route.ts
new file mode 100644
index 000000000..76d108d0e
--- /dev/null
+++ b/src/app/api/2fa/verify/route.ts
@@ -0,0 +1,116 @@
+import { z } from 'zod';
+import prisma from '@/lib/prisma';
+import { getBearerToken, saveAuth } from '@/lib/auth';
+import { ROLES } from '@/lib/constants';
+import { secret } from '@/lib/crypto';
+import { createSecureToken, parseSecureToken } from '@/lib/jwt';
+import { parseRequest } from '@/lib/request';
+import { badRequest, json, unauthorized } from '@/lib/response';
+import { verifyBackupCode } from '@/lib/two-factor/backup-codes';
+import { decryptSecret } from '@/lib/two-factor/crypto';
+import { checkRateLimit, recordFailedAttempt, resetRateLimit } from '@/lib/two-factor/rate-limit';
+import { isOtpReplayed, markOtpUsed } from '@/lib/two-factor/replay-prevention';
+import { verifyTotp } from '@/lib/two-factor/totp';
+import { getAllUserTeams, getUser } from '@/queries/prisma';
+import redis from '@/lib/redis';
+
+export async function POST(request: Request) {
+ const schema = z.union([
+ z.object({ token: z.string().length(6), backupCode: z.undefined() }),
+ z.object({ backupCode: z.string().min(1), token: z.undefined() }),
+ ]);
+
+ // Validate partial auth token — skip normal session auth
+ const rawToken = getBearerToken(request);
+ if (!rawToken) {
+ return unauthorized({ code: 'missing-token' });
+ }
+
+ const payload = parseSecureToken(rawToken, secret()) as any;
+ if (!payload || payload.type !== 'partial-auth' || !payload.userId) {
+ return unauthorized({ code: 'invalid-partial-token' });
+ }
+
+ const { body, error } = await parseRequest(request, schema, { skipAuth: true });
+ if (error) {
+ return error();
+ }
+
+ const userId = payload.userId as string;
+ const user = await getUser(userId);
+
+ if (!user) {
+ return unauthorized();
+ }
+
+ const twoFactor = await prisma.client.twoFactorAuth.findUnique({ where: { userId } });
+
+ if (!twoFactor?.isEnabled) {
+ return badRequest({ message: '2FA not enabled for this user' });
+ }
+
+ const rateCheck = await checkRateLimit(userId);
+ if (!rateCheck.allowed) {
+ return Response.json(
+ {
+ error: {
+ code: 'rate-limited',
+ message: 'Too many failed attempts',
+ lockedUntil: rateCheck.lockedUntil,
+ },
+ },
+ { status: 429 },
+ );
+ }
+
+ if (body.backupCode) {
+ const unusedCodes = await prisma.client.twoFactorBackupCode.findMany({
+ where: { userId, used: false },
+ });
+ const hashes = unusedCodes.map(c => c.codeHash);
+ const matchIndex = await verifyBackupCode(body.backupCode, hashes);
+
+ if (matchIndex === null) {
+ await recordFailedAttempt(userId);
+ return badRequest({ code: 'invalid-backup-code', message: 'Invalid backup code' });
+ }
+
+ await prisma.client.twoFactorBackupCode.update({
+ where: { id: unusedCodes[matchIndex].id },
+ data: { used: true },
+ });
+ await resetRateLimit(userId);
+ } else {
+ const { token } = body;
+
+ if (await isOtpReplayed(userId, token)) {
+ return badRequest({ code: 'otp-replayed', message: 'Code already used' });
+ }
+
+ const decryptedSecret = decryptSecret(twoFactor.secret);
+
+ if (!(await verifyTotp(token, decryptedSecret))) {
+ await recordFailedAttempt(userId);
+ return badRequest({ code: 'invalid-code', message: 'Invalid verification code' });
+ }
+
+ await markOtpUsed(userId, token);
+ await resetRateLimit(userId);
+ }
+
+ const { id, role, createdAt, username } = user;
+
+ let fullToken: string;
+ if (redis.enabled) {
+ fullToken = await saveAuth({ userId: id, role });
+ } else {
+ fullToken = createSecureToken({ userId: id, role }, secret());
+ }
+
+ const teams = await getAllUserTeams(id);
+
+ return json({
+ token: fullToken,
+ user: { id, username, role, createdAt, isAdmin: role === ROLES.admin, teams },
+ });
+}
diff --git a/src/queries/prisma/user.ts b/src/queries/prisma/user.ts
index 467ea1e02..0de5a71b7 100644
--- a/src/queries/prisma/user.ts
+++ b/src/queries/prisma/user.ts
@@ -26,6 +26,7 @@ async function findUser(criteria: Prisma.UserFindUniqueArgs, options: GetUserOpt
password: includePassword,
role: true,
createdAt: true,
+ twoFactorRequired: true,
},
});
}