Merge pull request #4205 from boutterudy/feat-2FA

feat(login): add 2FA
This commit is contained in:
Mike Cao authored and GitHub committed 2026-07-23 11:45:20 -07:00
commit 36bd9d33b8
50 files changed
+2606 -184

No files matched your search

+18 -2
View File
@@ -5,7 +5,14 @@ import { useEffect } from 'react';
import { MobileNav } from '@/app/(main)/MobileNav';
import { SideNav } from '@/app/(main)/SideNav';
import { TopNav } from '@/app/(main)/TopNav';
import { useConfig, useLoginQuery, useNavigation, useTeamQuery } from '@/components/hooks';
import {
useConfig,
useLoginQuery,
useNavigation,
useTeamQuery,
useTwoFactorStatusQuery,
} from '@/components/hooks';
import { TwoFactorSetupModal } from '@/components/modals/TwoFactorSetupModal';
import { LAST_TEAM_CONFIG } from '@/lib/constants';
import { removeItem, setItem } from '@/lib/storage';
import { UpdateNotice } from './UpdateNotice';
@@ -15,6 +22,8 @@ export function App({ children }) {
const config = useConfig();
const { pathname, router, teamId } = useNavigation();
const { isLoading: isTeamLoading, error: teamError } = useTeamQuery(teamId);
const { data: twoFactorStatus } = useTwoFactorStatusQuery(!!user);
const needsTwoFactorSetup = !!(twoFactorStatus?.isRequired && !twoFactorStatus?.isEnabled);
useEffect(() => {
if (teamId) {
@@ -64,8 +73,15 @@ export function App({ children }) {
</Column>
<Column overflowX="hidden" minHeight="0" position="relative">
<TopNav />
<Column alignItems="center">{children}</Column>
<Column
alignItems="center"
aria-hidden={needsTwoFactorSetup || undefined}
style={needsTwoFactorSetup ? { pointerEvents: 'none' } : undefined}
>
{children}
</Column>
</Column>
{needsTwoFactorSetup && <TwoFactorSetupModal required={true} />}
<UpdateNotice user={user} config={config} />
{process.env.NODE_ENV === 'production' && !pathname.includes('/share/') && (
<Script src={`${process.env.basePath || ''}/telemetry.js`} />
+9 -1
View File
@@ -3,7 +3,9 @@ import { IconLabel } from '@/components/common/IconLabel';
import Link from '@/components/common/Link';
import { NavMenu } from '@/components/common/NavMenu';
import { useMessages, useNavigation } from '@/components/hooks';
import { ArrowLeft, Globe, User, Users } from '@/components/icons';
import { ArrowLeft, Globe, ShieldCheck, User, Users } from '@/components/icons';
import { Column, Focusable, Row, Tooltip, TooltipTrigger } from '@umami/react-zen';
import Link from '@/components/common/Link';
export function AdminNav({ onItemClick }: { onItemClick?: () => void }) {
const { t, labels } = useMessages();
@@ -31,6 +33,12 @@ export function AdminNav({ onItemClick }: { onItemClick?: () => void }) {
path: '/admin/teams',
icon: <Users />,
},
{
id: 'security',
label: t(labels.security),
path: '/admin/security',
icon: <ShieldCheck />,
},
],
},
];
@@ -0,0 +1,47 @@
'use client';
import { Column, Row, Switch, Text } from '@umami/react-zen';
import { PageHeader } from '@/components/common/PageHeader';
import { Panel } from '@/components/common/Panel';
import { useMessages, useUpdateQuery, useTwoFactorStatusQuery } from '@/components/hooks';
import { useQueryClient } from '@tanstack/react-query';
export function AdminSecurityPage() {
const { t, labels, messages } = useMessages();
const { data: status, isLoading } = useTwoFactorStatusQuery(true);
const { mutateAsync: setGlobal } = useUpdateQuery('/admin/2fa/global');
const queryClient = useQueryClient();
const isGlobalRequired = status?.requiredReason === 'global' || false;
const handleToggle = async (value: boolean) => {
await setGlobal({ required: value });
queryClient.invalidateQueries({ queryKey: ['2fa-status'] });
};
if (isLoading) return null;
return (
<Column gap="6" margin="2">
<PageHeader title={t(labels.security)} />
<Panel>
<Column gap="4">
<Column gap="1">
<Text weight="bold">{t(labels.twoFactorAuth)}</Text>
<Text>{t(messages.twoFactorAdminGlobalDescription)}</Text>
</Column>
<Row alignItems="center" gap="3">
<Switch isSelected={isGlobalRequired} onChange={handleToggle} />
<Text>{t(labels.twoFactorRequireGlobal)}</Text>
</Row>
{isGlobalRequired && (
<Text size="sm" color="muted">
{t(messages.twoFactorOverrideNote)}
</Text>
)}
</Column>
</Panel>
</Column>
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from 'next';
import { AdminSecurityPage } from './AdminSecurityPage';
export default function () {
return <AdminSecurityPage />;
}
export const metadata: Metadata = {
title: 'Security',
};
@@ -1,6 +1,7 @@
import { Column, Tab, TabList, TabPanel, Tabs } from '@umami/react-zen';
import { useMessages } from '@/components/hooks';
import { UserEditForm } from './UserEditForm';
import { UserTwoFactorSettings } from './UserTwoFactorSettings';
import { UserWebsites } from './UserWebsites';
export function UserSettings({ userId }: { userId: string }) {
@@ -12,6 +13,7 @@ export function UserSettings({ userId }: { userId: string }) {
<TabList>
<Tab id="details">{t(labels.details)}</Tab>
<Tab id="websites">{t(labels.websites)}</Tab>
<Tab id="security">{t(labels.security)}</Tab>
</TabList>
<TabPanel id="details" style={{ width: 500 }}>
<UserEditForm userId={userId} />
@@ -19,6 +21,9 @@ export function UserSettings({ userId }: { userId: string }) {
<TabPanel id="websites">
<UserWebsites userId={userId} />
</TabPanel>
<TabPanel id="security" style={{ width: 500 }}>
<UserTwoFactorSettings userId={userId} />
</TabPanel>
</Tabs>
</Column>
);
@@ -0,0 +1,59 @@
'use client';
import { Column, Row, Switch, Text, Tooltip, TooltipTrigger } from '@umami/react-zen';
import { Badge } from '@/components/common/Badge';
import {
useMessages,
useUpdateQuery,
useTwoFactorStatusQuery,
useUserQuery,
useTwoFactorUserStatusQuery,
} from '@/components/hooks';
import { useQueryClient } from '@tanstack/react-query';
export function UserTwoFactorSettings({ userId }: { userId: string }) {
const { t, labels, messages } = useMessages();
const queryClient = useQueryClient();
const { data: globalStatus } = useTwoFactorStatusQuery(true);
const isGlobalRequired = globalStatus?.requiredReason === 'global';
const { data: userTfaData } = useTwoFactorUserStatusQuery(userId);
const { data: userData } = useUserQuery(userId);
const { mutateAsync: setUserRequired } = useUpdateQuery(`/admin/users/${userId}/2fa`);
const twoFactorEnabled = !!(userTfaData as any)?.isEnabled;
const twoFactorRequired = !!(userData as any)?.twoFactorRequired;
const handleToggle = async (value: boolean) => {
await setUserRequired({ required: value });
queryClient.invalidateQueries({ queryKey: ['users', { userId }] });
};
return (
<Column gap="4">
<Row alignItems="center" gap="3">
<Text weight="bold">{t(labels.twoFactorAuth)}</Text>
<Badge variant={twoFactorEnabled ? 'good' : 'gray'}>
{twoFactorEnabled ? t(labels.twoFactorActive) : t(labels.twoFactorStatusNotConfigured)}
</Badge>
</Row>
<Text size="sm" color="muted">
{t(messages.twoFactorRequireUserDescription)}
</Text>
<TooltipTrigger isDisabled={!isGlobalRequired}>
<Row alignItems="center" gap="3">
<Switch
isSelected={isGlobalRequired || twoFactorRequired}
isDisabled={isGlobalRequired}
onChange={handleToggle}
/>
<Text>{t(labels.twoFactorRequireUser)}</Text>
</Row>
<Tooltip>{t(labels.twoFactorGlobalActiveTooltip)}</Tooltip>
</TooltipTrigger>
</Column>
);
}
+7 -1
View File
@@ -2,7 +2,7 @@ import { Column, Focusable, Row, Text, Tooltip, TooltipTrigger } from '@umami/re
import { IconLabel } from '@/components/common/IconLabel';
import Link from '@/components/common/Link';
import { useMessages, useNavigation } from '@/components/hooks';
import { ArrowLeft, Settings2, UserCircle, Users } from '@/components/icons';
import { ArrowLeft, Settings2, ShieldCheck, UserCircle, Users } from '@/components/icons';
export function SettingsNav({
isCollapsed,
@@ -41,6 +41,12 @@ export function SettingsNav({
path: renderUrl('/settings/teams'),
icon: <Users />,
},
{
id: 'security',
label: t(labels.security),
path: renderUrl('/settings/security'),
icon: <ShieldCheck />,
},
],
},
];
@@ -0,0 +1,94 @@
'use client';
import { Column, Row, Switch, Text, Tooltip, TooltipTrigger } from '@umami/react-zen';
import { useState } from 'react';
import { Badge } from '@/components/common/Badge';
import { PageBody } from '@/components/common/PageBody';
import { PageHeader } from '@/components/common/PageHeader';
import { Panel } from '@/components/common/Panel';
import { useMessages, useTwoFactorStatusQuery } from '@/components/hooks';
import { TwoFactorDisableModal } from '@/components/modals/TwoFactorDisableModal';
import { TwoFactorSetupModal } from '@/components/modals/TwoFactorSetupModal';
import { useQueryClient } from '@tanstack/react-query';
export function UserSecurityPage() {
const { t, labels, messages } = useMessages();
const { data: status, isLoading } = useTwoFactorStatusQuery(true);
const queryClient = useQueryClient();
const [showSetup, setShowSetup] = useState(false);
const [showDisable, setShowDisable] = useState(false);
const isEnabled = status?.isEnabled ?? false;
const isRequired = status?.isRequired ?? false;
const handleToggle = (value: boolean) => {
if (value) {
setShowSetup(true);
} else {
setShowDisable(true);
}
};
const handleSetupClose = () => {
setShowSetup(false);
queryClient.invalidateQueries({ queryKey: ['2fa-status'] });
};
const handleDisableSuccess = () => {
setShowDisable(false);
queryClient.invalidateQueries({ queryKey: ['2fa-status'] });
};
if (isLoading) return null;
return (
<PageBody>
<Column gap="6">
<PageHeader title={t(labels.security)} />
<Panel>
<Column gap="4">
<Row alignItems="center" gap="3">
<Text weight="bold">{t(labels.twoFactorAuth)}</Text>
{isEnabled ? (
<Badge variant="good">{t(labels.twoFactorActive)}</Badge>
) : (
<Badge variant="gray">{t(labels.twoFactorStatusNotConfigured)}</Badge>
)}
</Row>
{isEnabled ? (
<Text>{t(messages.twoFactorActiveDescription)}</Text>
) : (
<Text>{t(messages.twoFactorUserDescription)}</Text>
)}
<TooltipTrigger isDisabled={!(isEnabled && isRequired)}>
<Row alignItems="center" gap="3">
<Switch
isSelected={isEnabled}
isDisabled={isEnabled && isRequired}
onChange={handleToggle}
/>
<Text>{t(labels.twoFactorEnable)}</Text>
</Row>
<Tooltip>{t(messages.twoFactorRequiredMessage)}</Tooltip>
</TooltipTrigger>
{isEnabled && isRequired && (
<Text size="sm" color="muted">
{t(messages.twoFactorRequiredMessage)}
</Text>
)}
</Column>
</Panel>
</Column>
{showSetup && <TwoFactorSetupModal required={false} onClose={handleSetupClose} />}
{showDisable && (
<TwoFactorDisableModal
onClose={() => setShowDisable(false)}
onSuccess={handleDisableSuccess}
/>
)}
</PageBody>
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from 'next';
import { UserSecurityPage } from './UserSecurityPage';
export default function () {
return <UserSecurityPage />;
}
export const metadata: Metadata = {
title: 'Security',
};
@@ -9,6 +9,7 @@ import { TeamsMemberAddButton } from '../TeamsMemberAddButton';
import { TeamEditForm } from './TeamEditForm';
import { TeamManage } from './TeamManage';
import { TeamMembersDataTable } from './TeamMembersDataTable';
import { TeamTwoFactorSettings } from './TeamTwoFactorSettings';
export function TeamSettings({ teamId }: { teamId: string }) {
const team: any = useTeam();
@@ -45,6 +46,11 @@ export function TeamSettings({ teamId }: { teamId: string }) {
</Row>
<TeamMembersDataTable teamId={teamId} allowEdit={canEdit} />
</Panel>
{isAdmin && (
<Panel>
<TeamTwoFactorSettings teamId={teamId} />
</Panel>
)}
{isTeamOwner && (
<Panel>
<TeamManage teamId={teamId} />
@@ -0,0 +1,49 @@
'use client';
import { Column, Row, Switch, Text, Tooltip, TooltipTrigger } from '@umami/react-zen';
import {
useMessages,
useUpdateQuery,
useTwoFactorStatusQuery,
useTeamQuery,
} from '@/components/hooks';
import { useQueryClient } from '@tanstack/react-query';
export function TeamTwoFactorSettings({ teamId }: { teamId: string }) {
const { t, labels, messages } = useMessages();
const queryClient = useQueryClient();
const { data: globalStatus } = useTwoFactorStatusQuery(true);
const isGlobalRequired = globalStatus?.requiredReason === 'global';
const { data: teamData } = useTeamQuery(teamId);
const { mutateAsync: setTeamRequired } = useUpdateQuery(`/admin/teams/${teamId}/2fa`);
const twoFactorRequired = !!(teamData as any)?.twoFactorRequired;
const handleToggle = async (value: boolean) => {
await setTeamRequired({ required: value });
queryClient.invalidateQueries({ queryKey: ['teams', { teamId }] });
};
return (
<Column gap="4">
<Text weight="bold">{t(labels.twoFactorAuth)}</Text>
<TooltipTrigger isDisabled={!isGlobalRequired}>
<Row alignItems="center" gap="3">
<Switch
isSelected={isGlobalRequired || twoFactorRequired}
isDisabled={isGlobalRequired}
onChange={handleToggle}
/>
<Text>{t(labels.twoFactorRequireTeam)}</Text>
</Row>
<Tooltip>{t(labels.twoFactorGlobalActiveTooltip)}</Tooltip>
</TooltipTrigger>
<Text size="sm" color="muted">
{t(messages.twoFactorRequireTeamDescription)}
</Text>
</Column>
);
}
+112
View File
@@ -0,0 +1,112 @@
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 Response.json(
{
error: {
code: 'two-factor-error-too-many-attempts',
message: 'Too many failed attempts',
lockedUntil: rateCheck.lockedUntil,
},
},
{ status: 429 },
);
}
// 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))) {
const { lockedUntil } = await recordFailedAttempt(userId);
return badRequest({
code: 'two-factor-error-invalid-code',
message: 'Invalid verification code',
...(lockedUntil && { lockedUntil }),
});
}
await prisma.transaction(async tx => {
await markOtpUsed(userId, token, tx);
await tx.twoFactorAuth.delete({ where: { userId } });
await tx.twoFactorBackupCode.deleteMany({ where: { userId } });
});
await resetRateLimit(userId);
return json({ ok: true });
}
+19
View File
@@ -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 });
}
+78
View File
@@ -0,0 +1,78 @@
import { z } from 'zod';
import prisma from '@/lib/prisma';
import { parseRequest } from '@/lib/request';
import { badRequest, json } 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({
code: 'two-factor-error-no-pending-setup',
message: 'No pending 2FA setup found',
});
}
// Verify rate limit
const rateCheck = await checkRateLimit(userId);
if (!rateCheck.allowed) {
return Response.json(
{
error: {
code: 'two-factor-error-too-many-attempts',
message: 'Too many failed attempts',
lockedUntil: rateCheck.lockedUntil,
},
},
{ status: 429 },
);
}
// 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))) {
const { lockedUntil } = await recordFailedAttempt(userId);
return badRequest({
code: 'two-factor-error-invalid-code',
message: 'Invalid verification code',
...(lockedUntil && { lockedUntil }),
});
}
const { plaintext, hashed } = await generateBackupCodes();
await prisma.transaction(async tx => {
await tx.twoFactorAuth.update({ where: { userId }, data: { isEnabled: true } });
await tx.twoFactorBackupCode.deleteMany({ where: { userId } });
await tx.twoFactorBackupCode.createMany({
data: hashed.map(codeHash => ({ userId, codeHash })),
});
await markOtpUsed(userId, token, tx);
});
await resetRateLimit(userId);
return json({ backupCodes: plaintext });
}
+51
View File
@@ -0,0 +1,51 @@
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 existing = await prisma.client.twoFactorAuth.findUnique({ where: { userId } });
if (existing?.isEnabled) {
return badRequest({
code: 'two-factor-error-already-enabled',
message: '2FA is already enabled',
});
}
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 },
});
/*
`manualKey` is intentionally plaintext as the user needs it once for manual entry.
The encrypted copy in DB is what matters for long-term storage.
*/
return json({ qrCodeDataUrl, manualKey: secret });
}
+44
View File
@@ -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 });
}
+136
View File
@@ -0,0 +1,136 @@
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() }),
]);
const rawToken = getBearerToken(request);
if (!rawToken) {
return unauthorized({ code: 'two-factor-error-missing-token' });
}
const payload = parseSecureToken(rawToken, secret()) as any;
if (!payload || payload.type !== 'partial-auth' || !payload.userId) {
return unauthorized({ code: 'two-factor-error-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({
code: 'two-factor-error-not-enabled',
message: '2FA not enabled for this user',
});
}
const rateCheck = await checkRateLimit(userId);
if (!rateCheck.allowed) {
return Response.json(
{
error: {
code: 'two-factor-error-too-many-attempts',
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) {
const { lockedUntil } = await recordFailedAttempt(userId);
return badRequest({
code: 'two-factor-error-invalid-backup-code',
message: 'Invalid backup code',
...(lockedUntil && { lockedUntil }),
});
}
const consumed = await prisma.client.twoFactorBackupCode.updateMany({
where: { id: unusedCodes[matchIndex].id, used: false },
data: { used: true },
});
if (consumed.count === 0) {
const { lockedUntil } = await recordFailedAttempt(userId);
return badRequest({
code: 'two-factor-error-invalid-backup-code',
message: 'Invalid backup code',
...(lockedUntil && { lockedUntil }),
});
}
await resetRateLimit(userId);
} else {
const { token } = body;
if (await isOtpReplayed(userId, token)) {
return badRequest({ code: 'two-factor-error-code-used', message: 'Code already used' });
}
const decryptedSecret = decryptSecret(twoFactor.secret);
if (!(await verifyTotp(token, decryptedSecret))) {
const { lockedUntil } = await recordFailedAttempt(userId);
return badRequest({
code: 'two-factor-error-invalid-code',
message: 'Invalid verification code',
...(lockedUntil && { lockedUntil }),
});
}
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 },
});
}
+29
View File
@@ -0,0 +1,29 @@
import { z } from 'zod';
import prisma from '@/lib/prisma';
import { parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { canEnforceTwoFactorAuthForEveryone } from '@/permissions';
export async function POST(request: Request) {
const schema = z.object({ required: z.boolean() });
const { auth, body, error } = await parseRequest(request, schema);
if (error) {
return error();
}
if (!(await canEnforceTwoFactorAuthForEveryone(auth))) {
return unauthorized();
}
const { required } = body;
await prisma.client.appSetting.upsert({
where: { key: 'twoFactorRequiredGlobal' },
update: { value: String(required) },
create: { key: 'twoFactorRequiredGlobal', value: String(required) },
});
return json({ ok: true, required });
}
@@ -0,0 +1,29 @@
import { z } from 'zod';
import prisma from '@/lib/prisma';
import { parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { canEnforceTwoFactorAuthForTeam } from '@/permissions';
export async function POST(request: Request, { params }: { params: Promise<{ teamId: string }> }) {
const schema = z.object({ required: z.boolean() });
const { auth, body, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { teamId } = await params;
if (!(await canEnforceTwoFactorAuthForTeam(auth, teamId))) {
return unauthorized();
}
const { required } = body;
await prisma.client.team.update({
where: { id: teamId },
data: { twoFactorRequired: required },
});
return json({ ok: true, teamId, twoFactorRequired: required });
}
@@ -0,0 +1,45 @@
import { z } from 'zod';
import prisma from '@/lib/prisma';
import { parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { updateUser } from '@/queries/prisma/user';
import { canEnforceTwoFactorAuthForUser } from '@/permissions';
export async function GET(request: Request, { params }: { params: Promise<{ userId: string }> }) {
const { auth, error } = await parseRequest(request);
if (error) {
return error();
}
if (!(await canEnforceTwoFactorAuthForUser(auth))) {
return unauthorized();
}
const { userId } = await params;
const twoFactor = await prisma.client.twoFactorAuth.findUnique({ where: { userId } });
return json({ isEnabled: twoFactor?.isEnabled ?? false });
}
export async function POST(request: Request, { params }: { params: Promise<{ userId: string }> }) {
const schema = z.object({ required: z.boolean() });
const { auth, body, error } = await parseRequest(request, schema);
if (error) {
return error();
}
if (!(await canEnforceTwoFactorAuthForUser(auth))) {
return unauthorized();
}
const { userId } = await params;
const { required } = body;
const user = await updateUser(userId, { twoFactorRequired: required });
return json({ ok: true, userId: user.id, twoFactorRequired: required });
}
+9
View File
@@ -4,6 +4,7 @@ import { ROLES } from '@/lib/constants';
import { hash, secret } from '@/lib/crypto';
import { createSecureToken } from '@/lib/jwt';
import { checkPassword } from '@/lib/password';
import prisma from '@/lib/prisma';
import redis from '@/lib/redis';
import { parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
@@ -31,6 +32,14 @@ export async function POST(request: Request) {
const { id, role, createdAt } = user;
// Check if 2FA is enabled for this user
const twoFactor = await prisma.client.twoFactorAuth.findUnique({ where: { userId: id } });
if (twoFactor?.isEnabled) {
const partialToken = createSecureToken({ userId: id, type: 'partial-auth' }, secret(), {
expiresIn: '5m',
});
return json({ requiresTwoFactor: true, partialToken });
}
// Bind token to password hash so a password change invalidates old tokens.
const pwd = hash(user.password);
+8 -3
View File
@@ -22,9 +22,14 @@ export function LoginForm() {
const handleSubmit = async (data: any) => {
await mutateAsync(data, {
onSuccess: async ({ token, user }) => {
setClientAuthToken(token);
setUser(user);
onSuccess: async (response: any) => {
if (response.requiresTwoFactor) {
sessionStorage.setItem('umami.partial-token', response.partialToken);
router.push('/login/two-factor');
return;
}
setClientAuthToken(response.token);
setUser(response.user);
router.push('/');
},
});
+11 -2
View File
@@ -4,8 +4,9 @@ import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { useLoginQuery } from '@/components/hooks';
import { LoginForm } from './LoginForm';
import { PropsWithChildren } from 'react';
export function LoginPage() {
export function LoginPageWrapper({ children }: PropsWithChildren) {
const { user, isLoading } = useLoginQuery();
const router = useRouter();
@@ -27,7 +28,15 @@ export function LoginPage() {
backgroundColor="surface-raised"
style={{ paddingTop: '15vh' }}
>
<LoginForm />
{children}
</Column>
);
}
export function LoginPage() {
return (
<LoginPageWrapper>
<LoginForm />
</LoginPageWrapper>
);
}
@@ -0,0 +1,142 @@
'use client';
import {
Button,
Column,
Form,
FormButtons,
FormField,
FormSubmitButton,
Heading,
Icon,
Text,
TextField,
} from '@umami/react-zen';
import { useRouter } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { OtpInput } from '@/components/common/OtpInput';
import { useMessages, useTwoFactorVerifyMutation } from '@/components/hooks';
import { Logo } from '@/components/svg';
import { setClientAuthToken } from '@/lib/client';
import { setUser } from '@/store/app';
export function LoginTwoFactorPage() {
const { t, labels, messages, getErrorMessage } = useMessages();
const router = useRouter();
const { mutateAsync, isPending } = useTwoFactorVerifyMutation();
const partialTokenRef = useRef<string | null>(null);
const [useBackup, setUseBackup] = useState(false);
const [otpValue, setOtpValue] = useState('');
const [lockUntil, setLockUntil] = useState<Date | null>(null);
const [error, setError] = useState<string | null>(null);
// Redirect to the login page when no token
useEffect(() => {
const token = sessionStorage.getItem('umami.partial-token');
if (!token) {
router.replace('/login');
return;
}
sessionStorage.removeItem('umami.partial-token');
partialTokenRef.current = token;
}, [router]);
// Keep the locked state until the time is up
useEffect(() => {
if (!lockUntil) return;
const interval = setInterval(() => {
if (new Date() >= lockUntil) {
setLockUntil(null);
}
}, 1000);
return () => clearInterval(interval);
}, [lockUntil]);
const submitVerification = async (token?: string, backupCode?: string) => {
const partialToken = partialTokenRef.current;
if (!partialToken) {
router.replace('/login');
return;
}
setError(null);
try {
const data = await mutateAsync({ partialToken, token, backupCode });
setClientAuthToken(data.token);
setUser(data.user);
router.push('/');
} catch (err: any) {
if (err.lockedUntil) {
setLockUntil(new Date(err.lockedUntil));
}
setError(getErrorMessage(err));
}
};
const handleSubmit = async (data: any) => {
await submitVerification(
useBackup ? undefined : otpValue,
useBackup ? data.backupCode : undefined,
);
};
const lockMessage = lockUntil
? t(messages.twoFactorLockedMessage, {
time: lockUntil.toLocaleTimeString(),
})
: null;
return (
<Column justifyContent="center" alignItems="center" gap="6">
<Icon size="lg">
<Logo />
</Icon>
<Heading>umami</Heading>
<Column gap="4" style={{ minWidth: 300 }}>
<Heading size="xl">{t(labels.twoFactorLogin)}</Heading>
<Text>{t(messages.twoFactorLoginDescription)}</Text>
{!!lockUntil && lockMessage && (
<Text style={{ color: 'var(--color-danger, red)' }}>{lockMessage}</Text>
)}
<Form onSubmit={handleSubmit} error={error ?? undefined} style={{ minWidth: 300 }}>
{!useBackup ? (
<Column gap="2">
<Text weight="bold">{t(labels.twoFactorEnterCode)}</Text>
<OtpInput
value={otpValue}
onChange={val => {
setOtpValue(val);
if (error) setError(null);
}}
onComplete={val => submitVerification(val)}
disabled={!!lockUntil || isPending}
/>
</Column>
) : (
<FormField label={t(labels.twoFactorBackupCode)} name="backupCode">
<TextField autoComplete="off" />
</FormField>
)}
<FormButtons>
<FormSubmitButton
variant="primary"
style={{ flex: 1 }}
isDisabled={
!!lockUntil || isPending || (!useBackup && (otpValue.length !== 6 || !!error))
}
>
{t(labels.twoFactorVerify)}
</FormSubmitButton>
</FormButtons>
</Form>
<Button variant="quiet" onPress={() => setUseBackup(v => !v)}>
{useBackup ? t(labels.twoFactorLogin) : t(labels.twoFactorUseBackup)}
</Button>
</Column>
</Column>
);
}
+19
View File
@@ -0,0 +1,19 @@
import type { Metadata } from 'next';
import { LoginTwoFactorPage } from './LoginTwoFactorPage';
import { LoginPageWrapper } from '@/app/login/LoginPage';
export default async function () {
if (process.env.DISABLE_LOGIN || process.env.CLOUD_MODE) {
return null;
}
return (
<LoginPageWrapper>
<LoginTwoFactorPage />
</LoginPageWrapper>
);
}
export const metadata: Metadata = {
title: 'Two-factor authentication',
};
+94
View File
@@ -0,0 +1,94 @@
'use client';
import { useRef, ClipboardEvent, KeyboardEvent } from 'react';
import { Row, TextField } from '@umami/react-zen';
interface OtpInputProps {
value: string;
onChange: (value: string) => void;
onComplete?: (value: string) => void;
disabled?: boolean;
}
const LENGTH = 6;
const focusInput = (el: HTMLDivElement | null) => el?.querySelector('input')?.focus();
export function OtpInput({ value, onChange, onComplete, disabled }: OtpInputProps) {
const digits = Array.from({ length: LENGTH }, (_, i) => value?.[i] ?? '');
const refs = useRef<(HTMLDivElement | null)[]>([]);
const update = (index: number, char: string) => {
const next = digits.slice();
next[index] = char;
const newVal = next.join('');
onChange(newVal);
if (newVal.length === LENGTH) {
onComplete?.(newVal);
}
};
const handleInput = (index: number, raw: string) => {
const char = raw.replace(/\D/g, '').slice(-1);
if (!char) return;
update(index, char);
if (index < LENGTH - 1) {
focusInput(refs.current[index + 1]);
}
};
const handleKeyDown = (index: number, e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Backspace') {
if (digits[index]) {
update(index, '');
} else if (index > 0) {
update(index - 1, '');
focusInput(refs.current[index - 1]);
}
} else if (e.key === 'ArrowLeft' && index > 0) {
focusInput(refs.current[index - 1]);
} else if (e.key === 'ArrowRight' && index < LENGTH - 1) {
focusInput(refs.current[index + 1]);
}
};
const handlePaste = (e: ClipboardEvent<HTMLInputElement>) => {
e.preventDefault();
const pasted = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, LENGTH);
const next = Array.from({ length: LENGTH }, (_, i) => pasted[i] ?? '');
const newVal = next.join('');
onChange(newVal);
if (newVal.length === LENGTH) {
onComplete?.(newVal);
focusInput(refs.current[LENGTH - 1]);
} else {
focusInput(refs.current[pasted.length]);
}
};
return (
<Row gap="2">
{digits.map((digit, i) => (
<div
key={i}
ref={el => {
refs.current[i] = el;
}}
>
<TextField
value={digit}
onChange={char => handleInput(i, char)}
onKeyDown={e => handleKeyDown(i, e)}
onPaste={handlePaste}
isDisabled={disabled}
inputMode="numeric"
maxLength={1}
autoComplete="one-time-code"
aria-label={`Digit ${i + 1}`}
placeholder="0"
style={{ width: 32 }}
/>
</div>
))}
</Row>
);
}
+3
View File
@@ -24,6 +24,9 @@ export * from './queries/useLinkQuery';
export * from './queries/useLinkSharesQuery';
export * from './queries/useLinksQuery';
export * from './queries/useLoginQuery';
export * from './queries/useTwoFactorStatusQuery';
export * from './queries/useTwoFactorUserStatus';
export * from './queries/useTwoFactorVerifyMutation';
export * from './queries/usePixelQuery';
export * from './queries/usePixelSharesQuery';
export * from './queries/usePixelsQuery';
@@ -0,0 +1,13 @@
import { useApi } from '../useApi';
export function useTwoFactorStatusQuery(enabled: boolean) {
const { get, useQuery } = useApi();
return useQuery({
queryKey: ['2fa-status'],
queryFn: () => get('/2fa/status'),
enabled,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
});
}
@@ -0,0 +1,12 @@
import { useApi } from '../useApi';
export function useTwoFactorUserStatusQuery(userId: string) {
const { get, useQuery } = useApi();
return useQuery({
queryKey: ['user-2fa-status', userId],
queryFn: () => get(`/admin/users/${userId}/2fa`),
refetchOnWindowFocus: true,
refetchOnReconnect: true,
});
}
@@ -0,0 +1,29 @@
import { httpPost } from '@/lib/fetch';
import { useApi } from '../useApi';
interface TwoFactorVerifyParams {
partialToken: string;
token?: string;
backupCode?: string;
}
export function useTwoFactorVerifyMutation() {
const { useMutation } = useApi();
const basePath = process.env.basePath || '';
return useMutation({
mutationFn: async ({ partialToken, token, backupCode }: TwoFactorVerifyParams) => {
const body = backupCode ? { backupCode } : { token };
const res = await httpPost(`${basePath}/api/2fa/verify`, body, {
Authorization: `Bearer ${partialToken}`,
});
if (!res.ok) {
const { message, code, lockedUntil } = res?.data?.error || {};
throw Object.assign(new Error(message), { code, status: res.status, lockedUntil });
}
return res.data as { token: string; user: any };
},
});
}
+58
View File
@@ -395,6 +395,36 @@ export const labels: Record<string, string> = {
duration: 'label.duration',
recorded: 'label.recorded',
upgrade: 'label.upgrade',
security: 'label.security',
close: 'label.close',
twoFactorAuth: 'label.two-factor-auth',
twoFactorSetupTitle: 'label.two-factor-setup-title',
twoFactorStep1: 'label.two-factor-step1',
twoFactorStep2: 'label.two-factor-step2',
twoFactorScanQr: 'label.two-factor-scan-qr',
twoFactorCantScan: 'label.two-factor-cant-scan',
twoFactorManualEntry: 'label.two-factor-manual-entry',
twoFactorCopyCode: 'label.two-factor-copy-code',
twoFactorCodeCopied: 'label.two-factor-code-copied',
twoFactorGetCode: 'label.two-factor-get-code',
twoFactorEnterCode: 'label.two-factor-enter-code',
twoFactorUseBackup: 'label.two-factor-use-backup',
twoFactorSaveBackupCodes: 'label.two-factor-save-backup-codes',
twoFactorDownloadCodes: 'label.two-factor-download-codes',
twoFactorSavedCodes: 'label.two-factor-saved-codes',
twoFactorBackupFileTitle: 'label.two-factor-backup-file-title',
twoFactorSuccessTitle: 'label.two-factor-success-title',
twoFactorEnable: 'label.two-factor-enable',
twoFactorDisable: 'label.two-factor-disable',
twoFactorDisableTitle: 'label.two-factor-disable-title',
twoFactorStatusNotConfigured: 'label.two-factor-status-not-configured',
twoFactorActive: 'label.two-factor-active',
twoFactorRequireGlobal: 'label.two-factor-require-global',
twoFactorRequireUser: 'label.two-factor-require-user',
twoFactorRequireTeam: 'label.two-factor-require-team',
twoFactorGlobalActiveTooltip: 'label.two-factor-global-active-tooltip',
twoFactorVerify: 'label.two-factor-verify',
twoFactorLogin: 'label.two-factor-login',
};
export const messages: Record<string, string> = {
@@ -445,5 +475,33 @@ export const messages: Record<string, string> = {
notFound: 'message.not-found',
serverError: 'message.sever-error',
upgradeRequired: 'message.upgrade-required',
twoFactorSetupDescription: 'message.two-factor-setup-description',
twoFactorSetupRequiredDescription: 'message.two-factor-setup-required-description',
twoFactorStep1Description: 'message.two-factor-step1-description',
twoFactorStep2Description: 'message.two-factor-step2-description',
twoFactorEnabledDescription: 'message.two-factor-enabled-description',
twoFactorBackupDescription: 'message.two-factor-backup-description',
twoFactorBackupCodesOnce: 'message.two-factor-backup-codes-once',
twoFactorLoginDescription: 'message.two-factor-login-description',
twoFactorDisableDescription: 'message.two-factor-disable-description',
twoFactorRequiredMessage: 'message.two-factor-required-message',
twoFactorOverrideNote: 'message.two-factor-override-note',
twoFactorAdminGlobalDescription: 'message.two-factor-admin-global-description',
twoFactorRequireUserDescription: 'message.two-factor-require-user-description',
twoFactorRequireTeamDescription: 'message.two-factor-require-team-description',
twoFactorUserDescription: 'message.two-factor-user-description',
twoFactorLockedMessage: 'message.two-factor-locked-message',
twoFactorActiveDescription: 'message.two-factor-active-description',
twoFactorErrorInvalidCode: 'message.two-factor-error-invalid-code',
twoFactorErrorMissingToken: 'message.two-factor-error-missing-token',
twoFactorErrorInvalidPartialToken: 'message.two-factor-error-invalid-partial-token',
twoFactorErrorInvalidBackupCode: 'message.two-factor-error-invalid-backup-code',
twoFactorErrorCodeUsed: 'message.two-factor-error-code-used',
twoFactorErrorTooManyAttempts: 'message.two-factor-error-too-many-attempts',
twoFactorErrorDisableNotAllowed: 'message.two-factor-error-disable-not-allowed',
twoFactorErrorIncorrectPassword: 'message.two-factor-error-incorrect-password',
twoFactorErrorAlreadyEnabled: 'message.two-factor-error-already-enabled',
twoFactorErrorNotEnabled: 'message.two-factor-error-not-enabled',
twoFactorErrorNoPendingSetup: 'message.two-factor-error-no-pending-setup',
replayMinDurationDescription: 'message.replay-min-duration-description',
};
@@ -0,0 +1,64 @@
'use client';
import { Button, Column, Dialog, Modal, Row, Text } from '@umami/react-zen';
import { Form, FormButtons, FormField, FormSubmitButton, PasswordField } from '@umami/react-zen';
import { useState } from 'react';
import { OtpInput } from '@/components/common/OtpInput';
import { useMessages, useUpdateQuery } from '@/components/hooks';
interface TwoFactorDisableModalProps {
onClose: () => void;
onSuccess: () => void;
}
export function TwoFactorDisableModal({ onClose, onSuccess }: TwoFactorDisableModalProps) {
const { t, labels, messages, getErrorMessage } = useMessages();
const [otpValue, setOtpValue] = useState('');
const { mutateAsync: disable, error, isPending, reset } = useUpdateQuery('/2fa/disable');
const handleSubmit = async (data: any) => {
await disable({ password: data.password, token: otpValue }, { onSuccess }).catch(() => {});
};
const resetError = () => {
if (error) reset();
};
return (
<Modal isOpen={true} onOpenChange={onClose}>
<Dialog title={t(labels.twoFactorDisableTitle)} style={{ width: 420 }}>
{({ close }) => (
<Column gap="4">
<Text>{t(messages.twoFactorDisableDescription)}</Text>
<Form onSubmit={handleSubmit} error={getErrorMessage(error)}>
<FormField label={t(labels.password)} name="password">
<PasswordField autoComplete="current-password" onChange={resetError} />
</FormField>
<Column gap="1">
<Text size="sm">{t(labels.twoFactorEnterCode)}</Text>
<OtpInput
value={otpValue}
onChange={val => {
setOtpValue(val);
resetError();
}}
disabled={isPending}
/>
</Column>
<FormButtons>
<Button variant="outline" onPress={close} isDisabled={isPending}>
{t(labels.cancel)}
</Button>
<FormSubmitButton
variant="danger"
isDisabled={isPending || otpValue.length !== 6 || !!error}
>
{t(labels.twoFactorDisable)}
</FormSubmitButton>
</FormButtons>
</Form>
</Column>
)}
</Dialog>
</Modal>
);
}
@@ -0,0 +1,9 @@
.twoFactorSetupModal {
width: 700px;
max-width: 95vw;
}
.qrCodeImage {
width: 33%;
aspect-ratio: 1;
}
@@ -0,0 +1,211 @@
'use client';
import {
AlertBanner,
Box,
Button,
Code,
Column,
Dialog,
Icon,
Image,
Modal,
Row,
Tag,
TagGroup,
Text,
} from '@umami/react-zen';
import { useQueryClient } from '@tanstack/react-query';
import { ReactNode, useEffect, useState } from 'react';
import { OtpInput } from '@/components/common/OtpInput';
import { useMessages, useUpdateQuery } from '@/components/hooks';
import { TwoFactorSuccessModal } from './TwoFactorSuccessModal';
import styles from './TwoFactorSetupModal.module.css';
import { LucideCopy } from 'lucide-react';
function Step({
tag,
title,
details,
children,
}: {
tag: string;
title: string;
details: string;
children: ReactNode;
}) {
return (
<Column gap="5">
<Column gap="3">
<Row gap="3" alignItems="center">
<TagGroup>
<Tag variant="primary">{tag}</Tag>
</TagGroup>
<Text weight="bold">{title}</Text>
</Row>
<Text>{details}</Text>
</Column>
{children}
</Column>
);
}
interface TwoFactorSetupModalProps {
required: boolean;
onClose?: () => void;
}
export function TwoFactorSetupModal({ required, onClose }: TwoFactorSetupModalProps) {
const { t, labels, messages } = useMessages();
const [qrCodeDataUrl, setQrCodeDataUrl] = useState<string | null>(null);
const [manualKey, setManualKey] = useState<string | null>(null);
const [otpValue, setOtpValue] = useState('');
const [copied, setCopied] = useState(false);
const [error, setError] = useState<string | null>(null);
const [backupCodes, setBackupCodes] = useState<string[] | null>(null);
const queryClient = useQueryClient();
const { mutate: initiate } = useUpdateQuery('/2fa/setup/initiate');
const { mutateAsync: confirm, isPending: isConfirming } = useUpdateQuery('/2fa/setup/confirm');
const { mutate: cancel } = useUpdateQuery('/2fa/setup/cancel');
useEffect(() => {
initiate(
{},
{
onSuccess: (data: any) => {
setQrCodeDataUrl(data.qrCodeDataUrl);
setManualKey(data.manualKey);
},
onError: () => setError(t(messages.error)),
},
);
}, []);
const handleConfirm = async (value?: string) => {
const token = value ?? otpValue;
if (token.length !== 6) return;
setError(null);
try {
const data: any = await confirm({ token });
setBackupCodes(data.backupCodes);
} catch (err: any) {
setError(err.message || t(messages.error));
}
};
const handleCancel = async () => {
cancel({});
onClose?.();
};
const handleCopy = () => {
if (manualKey) {
navigator.clipboard.writeText(manualKey);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
};
if (backupCodes) {
return (
<TwoFactorSuccessModal
backupCodes={backupCodes}
onClose={() => {
queryClient.invalidateQueries({ queryKey: ['2fa-status'] });
onClose?.();
}}
/>
);
}
const preventDismiss = required ? () => {} : undefined;
return (
<Modal isOpen={true} onOpenChange={preventDismiss}>
<Dialog title={t(labels.twoFactorSetupTitle)} className={styles.twoFactorSetupModal}>
{({ close }) => (
<Column gap="9">
<Text>
{required && t(messages.twoFactorSetupRequiredDescription) + ' '}
{t(messages.twoFactorSetupDescription)}
</Text>
{/* Step 1 - Scan QR Code */}
<Step
tag={t(labels.twoFactorStep1)}
title={t(labels.twoFactorScanQr)}
details={t(messages.twoFactorStep1Description)}
>
<Box padding="2" shadow="lg" borderRadius="lg" border width="fit">
<Row alignItems="center" gap="2">
{qrCodeDataUrl && (
<Image
src={qrCodeDataUrl}
alt="QR code"
className={styles.qrCodeImage}
borderRadius="lg"
/>
)}
<Column>
<Text weight="bold">{t(labels.twoFactorCantScan)}</Text>
<Column gap="2">
<Text size="sm">{t(labels.twoFactorManualEntry)}</Text>
<Code>{manualKey}</Code>
<div>
<Button variant="outline" onPress={handleCopy}>
<Icon size="sm">
<LucideCopy />
</Icon>
{copied ? t(labels.twoFactorCodeCopied) : t(labels.twoFactorCopyCode)}
</Button>
</div>
</Column>
</Column>
</Row>
</Box>
</Step>
{/* Step 2 - Enter Verification Code */}
<Step
tag={t(labels.twoFactorStep2)}
title={t(labels.twoFactorGetCode)}
details={t(messages.twoFactorStep2Description)}
>
<Column gap="3.5">
<Text size="sm" weight="bold">
{t(labels.twoFactorEnterCode)}
</Text>
<OtpInput
value={otpValue}
onChange={val => {
setOtpValue(val);
if (error) setError(null);
}}
onComplete={handleConfirm}
disabled={isConfirming}
/>
</Column>
</Step>
{error && <AlertBanner variant="error" title={t(messages.error)} description={error} />}
<Row gap="2" justifyContent="flex-end">
{!required && (
<Button variant="outline" onPress={handleCancel} isDisabled={isConfirming}>
{t(labels.cancel)}
</Button>
)}
<Button
variant="primary"
onPress={() => handleConfirm()}
isDisabled={otpValue.length !== 6 || isConfirming || !!error}
>
{t(labels.confirm)}
</Button>
</Row>
</Column>
)}
</Dialog>
</Modal>
);
}
@@ -0,0 +1,18 @@
.dialog {
width: 620px;
max-width: 95vw;
}
.codesGrid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
padding: 12px;
background: var(--surface-sunken);
border-radius: 8px;
}
.code {
font-family: monospace;
font-size: 0.9rem;
}
@@ -0,0 +1,80 @@
'use client';
import { Button, Column, Dialog, Modal, Row, Text } from '@umami/react-zen';
import { useState } from 'react';
import { useMessages } from '@/components/hooks';
import styles from './TwoFactorSuccessModal.module.css';
interface TwoFactorSuccessModalProps {
backupCodes: string[];
onClose: () => void;
}
export function TwoFactorSuccessModal({ backupCodes, onClose }: TwoFactorSuccessModalProps) {
const { t, labels, messages } = useMessages();
const [saved, setSaved] = useState(false);
const handleDownload = () => {
const content = [
t(labels.twoFactorBackupFileTitle),
t(messages.twoFactorBackupCodesOnce),
'',
...backupCodes,
].join('\n');
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'umami-backup-codes.txt';
a.click();
URL.revokeObjectURL(url);
};
return (
<Modal isOpen={true}>
<Dialog title={t(labels.twoFactorSuccessTitle)} className={styles.dialog}>
{() => (
<Column gap="5">
<Text>{t(messages.twoFactorEnabledDescription)}</Text>
<Column gap="2">
<Text weight="bold">{t(labels.twoFactorSaveBackupCodes)}</Text>
<Text>{t(messages.twoFactorBackupDescription)}</Text>
<div className={styles.codesGrid}>
{backupCodes.map((code, i) => (
<code key={i} className={styles.code}>
{code}
</code>
))}
</div>
<Row>
<Button variant="outline" onPress={handleDownload}>
{t(labels.twoFactorDownloadCodes)}
</Button>
</Row>
</Column>
<Row gap="2" alignItems="center">
<input
type="checkbox"
id="saved-codes"
checked={saved}
onChange={e => setSaved(e.target.checked)}
/>
<label htmlFor="saved-codes">
<Text>{t(labels.twoFactorSavedCodes)}</Text>
</label>
</Row>
<Row justifyContent="flex-end">
<Button variant="primary" onPress={onClose} isDisabled={!saved}>
{t(labels.close)}
</Button>
</Row>
</Column>
)}
</Dialog>
</Modal>
);
}
+31
View File
@@ -0,0 +1,31 @@
import { randomBytes } from 'crypto';
import bcrypt from 'bcryptjs';
const BACKUP_CODE_COUNT = 10;
const BCRYPT_ROUNDS = 10;
export async function generateBackupCodes(): Promise<{
plaintext: Array<string>;
hashed: Array<string>;
}> {
const plaintext = Array.from(
{ length: BACKUP_CODE_COUNT },
() =>
randomBytes(8).toString('hex').toUpperCase() +
'-' +
randomBytes(8).toString('hex').toUpperCase(),
);
const hashed = await Promise.all(plaintext.map(code => bcrypt.hash(code, BCRYPT_ROUNDS)));
return { plaintext, hashed };
}
export async function verifyBackupCode(
inputCode: string,
storedHashes: Array<string>,
): Promise<number | null> {
for (let i = 0; i < storedHashes.length; i++) {
const match = await bcrypt.compare(inputCode.toUpperCase(), storedHashes[i]);
if (match) return i;
}
return null;
}
+35
View File
@@ -0,0 +1,35 @@
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
const ALGORITHM = 'aes-256-gcm';
/** Loads and validates the 256-bit encryption key from TWO_FACTOR_ENCRYPTION_KEY. */
function getKey(): Buffer {
const hex = process.env.TWO_FACTOR_ENCRYPTION_KEY;
if (!hex || hex.length !== 64 || !/^[0-9a-fA-F]{64}$/.test(hex)) {
throw new Error('TWO_FACTOR_ENCRYPTION_KEY is missing or invalid');
}
return Buffer.from(hex, 'hex');
}
/** Encrypts a TOTP secret using AES-256-GCM. Returns `ciphertext:iv:authTag` as hex. */
export function encryptSecret(plaintext: string): string {
const key = getKey();
const iv = randomBytes(12);
const cipher = createCipheriv(ALGORITHM, key, iv);
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
const authTag = cipher.getAuthTag();
return `${encrypted.toString('hex')}:${iv.toString('hex')}:${authTag.toString('hex')}`;
}
/** Decrypts a TOTP secret previously encrypted by {@link encryptSecret}. */
export function decryptSecret(stored: string): string {
const key = getKey();
const [ciphertextHex, ivHex, authTagHex] = stored.split(':');
const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(ivHex, 'hex'));
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
const decrypted = Buffer.concat([
decipher.update(Buffer.from(ciphertextHex, 'hex')),
decipher.final(),
]);
return decrypted.toString('utf8');
}
+57
View File
@@ -0,0 +1,57 @@
import { Prisma } from '@/generated/prisma/client';
import prisma from '@/lib/prisma';
const MAX_ATTEMPTS = 5;
const LOCKOUT_MINUTES = 15;
const MAX_RETRIES = 3;
export async function checkRateLimit(
userId: string,
): Promise<{ allowed: boolean; lockedUntil?: Date }> {
const record = await prisma.client.twoFactorRateLimit.findUnique({ where: { userId } });
if (!record) return { allowed: true };
if (record.lockedUntil && record.lockedUntil > new Date()) {
return { allowed: false, lockedUntil: record.lockedUntil };
}
return { allowed: true };
}
export async function recordFailedAttempt(userId: string): Promise<{ lockedUntil?: Date }> {
let retries = 0;
while (retries < MAX_RETRIES) {
try {
/*
prisma.transaction accepts `any` to support both batch and callback forms,
so TypeScript resolves to the batch overload and infers `any[]`. Cast is safe:
the callback form always returns the callback's return type.
*/
return await (prisma.transaction(
async (tx: Prisma.TransactionClient): Promise<{ lockedUntil?: Date }> => {
const record = await tx.twoFactorRateLimit.upsert({
where: { userId },
update: { attempts: { increment: 1 } },
create: { userId, attempts: 1 },
});
if (record.attempts >= MAX_ATTEMPTS) {
const lockedUntil = new Date(Date.now() + LOCKOUT_MINUTES * 60 * 1000);
await tx.twoFactorRateLimit.update({ where: { userId }, data: { lockedUntil } });
return { lockedUntil };
}
return {};
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
) as Promise<{ lockedUntil?: Date }>);
} catch (err: any) {
if (err.code === 'P2034') {
retries++;
continue;
}
throw err;
}
}
throw new Error('recordFailedAttempt: max retries exceeded');
}
export async function resetRateLimit(userId: string): Promise<void> {
await prisma.client.twoFactorRateLimit.deleteMany({ where: { userId } });
}
+28
View File
@@ -0,0 +1,28 @@
import prisma from '@/lib/prisma';
import { Prisma } from '@/generated/prisma/client';
type TxClient = Prisma.TransactionClient;
/** Records a one-time password as used so it cannot be reused within the next 90 seconds. */
export async function markOtpUsed(userId: string, otp: string, tx?: TxClient): Promise<void> {
const client = tx ?? prisma.client;
const expiresAt = new Date(Date.now() + 90 * 1000);
await client.twoFactorOtpUsed.upsert({
where: { userId_otp: { userId, otp } },
update: { expiresAt },
create: { userId, otp, expiresAt },
});
}
/** Returns true if this one-time password was already used recently, indicating a replay attack. Expired records are cleaned up automatically. */
export async function isOtpReplayed(userId: string, otp: string): Promise<boolean> {
const record = await prisma.client.twoFactorOtpUsed.findUnique({
where: { userId_otp: { userId, otp } },
});
if (!record) return false;
if (record.expiresAt < new Date()) {
await prisma.client.twoFactorOtpUsed.delete({ where: { userId_otp: { userId, otp } } });
return false;
}
return true;
}
+23
View File
@@ -0,0 +1,23 @@
import { generateSecret, generateURI, verify } from 'otplib';
import qrcode from 'qrcode';
export function generateTotpSecret(): string {
return generateSecret();
}
export function generateOtpAuthUri(secret: string, username: string): string {
return generateURI({
issuer: 'Umami',
label: username,
secret,
});
}
export async function generateQrCodeDataUrl(otpAuthUri: string): Promise<string> {
return qrcode.toDataURL(otpAuthUri, { errorCorrectionLevel: 'H' });
}
export async function verifyTotp(token: string, secret: string): Promise<boolean> {
const result = await verify({ secret, token });
return result.valid;
}
+8
View File
@@ -90,3 +90,11 @@ export async function canCreateTeamWebsite({ user }: Auth, teamId: string) {
export async function canViewAllTeams({ user }: Auth) {
return user?.isAdmin ?? false;
}
export async function canEnforceTwoFactorAuthForTeam({ user }: Auth, teamId: string) {
if (!user) {
return false;
}
return user.isAdmin;
}
+8
View File
@@ -35,3 +35,11 @@ export async function canUpdateUser({ user }: Auth, viewedUserId: string) {
export async function canDeleteUser({ user }: Auth) {
return user?.isAdmin ?? false;
}
export async function canEnforceTwoFactorAuthForEveryone({ user }: Auth) {
return user?.isAdmin ?? false;
}
export async function canEnforceTwoFactorAuthForUser({ user }: Auth) {
return user?.isAdmin ?? false;
}
+1
View File
@@ -30,6 +30,7 @@ async function findUser(criteria: Prisma.UserFindUniqueArgs, options: GetUserOpt
password: includePassword,
role: true,
createdAt: true,
twoFactorRequired: true,
},
});
}