This commit is contained in:
Francis Cao committed 2026-07-23 11:50:39 -07:00
commit 13d18c0880
50 files changed
+2606 -184

No files matched your search

+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
@@ -396,6 +396,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> = {
@@ -446,5 +476,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>
);
}