Files
NapCatQQ/packages/napcat-webui-frontend/src/pages/web_login.tsx
T
Ryokuryuneko 091c012427 feat(webui): 添加双重登录验证(2FA)功能 (#1920)
* feat(webui): 添加双重登录验证(2FA)功能

* fix: 修复 store.delete 类型错误,添加完整项目文件

* feat(webui): 添加双重登录验证(2FA)功能

- 后端:实现 TOTP 验证码生成和验证
- 后端:添加 enable2FA 和 totpSecret 配置项
- 后端:登录处理器支持 2FA 验证
- 前端:添加 2FA 登录流程和配置页面

* feat(webui): 添加双重登录验证(2FA)功能

- 后端:实现 TOTP 验证码生成和验证 (TotpHelper.ts)
- 后端:添加 enable2FA 和 totpSecret 配置项 (config.ts)
- 后端:登录处理器支持 2FA 验证,添加 2FA 管理 API (Auth.ts)
- 后端:注册 2FA 相关路由 (auth.ts)
- 前端:登录页面添加 2FA 验证步骤 (web_login.tsx)
- 前端:添加 2FA 相关 API 调用方法 (webui_manager.ts)
- 前端:添加 2FA 配置页面 (webui.tsx)

* fix: 更新 AuthResponse 类型定义以支持 2FA

* fix: 修复 setLocalToken 类型错误

* fix: 修复 TotpHelper.ts 类型错误

* fix: address PR review feedback

- Remove database files from tracking
- Use local QRCodeSVG instead of third-party API
- Remove unused verify2FACode method
- Remove IP-based challenge storage (password already validated)
- Require TOTP code to disable 2FA
- Remove duplicate loginWithTokenAndTotp method
- Remove unused generateTotp method
- Use consistent English error messages

* fix: remove unused store import

* chore: translate 2FA UI to Chinese
2026-06-20 09:56:54 +08:00

401 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Button } from '@heroui/button';
import { CardBody, CardHeader } from '@heroui/card';
import { Image } from '@heroui/image';
import { Input } from '@heroui/input';
import { useLocalStorage } from '@uidotdev/usehooks';
import { useEffect, useState } from 'react';
import { toast } from 'react-hot-toast';
import { IoKeyOutline, IoArrowBack } from 'react-icons/io5';
import { useNavigate } from 'react-router-dom';
import logo from '@/assets/images/logo.png';
import key from '@/const/key';
import HoverEffectCard from '@/components/effect_card';
import { title } from '@/components/primitives';
import { ThemeSwitch } from '@/components/theme-switch';
import WebUIManager from '@/controllers/webui_manager';
import PureLayout from '@/layouts/pure';
import { motion } from 'motion/react';
export default function WebLoginPage () {
const urlSearchParams = new URLSearchParams(window.location.search);
const token = urlSearchParams.get('token');
const navigate = useNavigate();
const [tokenValue, setTokenValue] = useState<string>(token || '');
const [isLoading, setIsLoading] = useState<boolean>(false);
const [isPasskeyLoading, setIsPasskeyLoading] = useState<boolean>(true); // 初始为true,表示正在检查passkey
const [, setLocalToken] = useLocalStorage<string>(key.token, '');
// 2FA相关状态
const [require2FA, setRequire2FA] = useState<boolean>(false);
const [totpCode, setTotpCode] = useState<string>('');
const [pendingToken, setPendingToken] = useState<string>('');
// Helper function to decode base64url
function base64UrlToUint8Array (base64Url: string): Uint8Array {
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
// Helper function to encode Uint8Array to base64url
function uint8ArrayToBase64Url (uint8Array: Uint8Array): string {
const base64 = btoa(String.fromCharCode(...uint8Array));
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
// 自动检查并尝试passkey登录
const tryPasskeyLogin = async () => {
if (!navigator.credentials || !navigator.credentials.get) {
// toast.error('当前浏览器/环境不支持 Passkey 登录。');
return;
}
try {
// 检查是否有passkey
const options = await WebUIManager.generatePasskeyAuthenticationOptions();
// 如果有passkey,自动进行认证
const credential = await navigator.credentials.get({
publicKey: {
challenge: base64UrlToUint8Array(options.challenge) as BufferSource,
allowCredentials: options.allowCredentials?.map((cred: any) => ({
id: base64UrlToUint8Array(cred.id) as BufferSource,
type: cred.type,
transports: cred.transports,
})),
userVerification: options.userVerification,
},
}) as PublicKeyCredential;
if (!credential) {
throw new Error('Passkey authentication cancelled');
}
// 准备响应进行验证 - 转换为base64url字符串格式
const authResponse = credential.response as AuthenticatorAssertionResponse;
const response = {
id: credential.id,
rawId: uint8ArrayToBase64Url(new Uint8Array(credential.rawId)),
response: {
authenticatorData: uint8ArrayToBase64Url(new Uint8Array(authResponse.authenticatorData)),
clientDataJSON: uint8ArrayToBase64Url(new Uint8Array(authResponse.clientDataJSON)),
signature: uint8ArrayToBase64Url(new Uint8Array(authResponse.signature)),
userHandle: authResponse.userHandle ? uint8ArrayToBase64Url(new Uint8Array(authResponse.userHandle)) : null,
},
type: credential.type,
};
// 验证认证
const data = await WebUIManager.verifyPasskeyAuthentication(response);
if (data && data.Credential) {
setLocalToken(data.Credential);
navigate('/qq_login', { replace: true });
return true; // 登录成功
}
} catch (error) {
// passkey登录失败,继续显示token登录界面
console.log('Passkey login failed or not available:', error);
}
return false; // 登录失败
};
// 第一次登录(输入token)
const onSubmitToken = async () => {
if (!tokenValue) {
toast.error('请输入token');
return;
}
setIsLoading(true);
try {
const data = await WebUIManager.loginWithToken(tokenValue);
if (data) {
if (data.require2FA) {
// 需要2FA验证
setRequire2FA(true);
setPendingToken(tokenValue);
setIsLoading(false);
return;
}
// 不需要2FA,直接登录
if (data.Credential) {
setLocalToken(data.Credential);
}
navigate('/qq_login', { replace: true });
}
} catch (error) {
toast.error((error as Error).message);
} finally {
setIsLoading(false);
}
};
// 2FA验证提交
const onSubmit2FA = async () => {
if (!totpCode || totpCode.length !== 6) {
toast.error('Please enter 6-digit code');
return;
}
setIsLoading(true);
try {
const data = await WebUIManager.loginWithToken(pendingToken, totpCode);
if (data && data.Credential) {
setLocalToken(data.Credential);
navigate('/qq_login', { replace: true });
}
} catch (error) {
toast.error((error as Error).message);
} finally {
setIsLoading(false);
}
};
// 返回token输入步骤
const goBackToToken = () => {
setRequire2FA(false);
setTotpCode('');
setPendingToken('');
};
// 处理全局键盘事件
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Enter' && !isLoading && !isPasskeyLoading) {
if (require2FA) {
onSubmit2FA();
} else {
onSubmitToken();
}
}
};
useEffect(() => {
document.addEventListener('keydown', handleKeyDown);
// 清理函数
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [tokenValue, totpCode, isLoading, isPasskeyLoading, require2FA]); // 依赖项包含用于登录的状态
useEffect(() => {
// 如果URL中有token,直接登录
if (token) {
// 不需要检查passkey,立即清除loading状态,避免登录失败后输入框被永久禁用
setIsPasskeyLoading(false);
onSubmitToken();
return;
}
// 否则尝试passkey自动登录
tryPasskeyLogin().finally(() => {
setIsPasskeyLoading(false);
});
}, []);
return (
<>
<title>WebUI登录 - NapCat WebUI</title>
<PureLayout>
<motion.div
initial={{ opacity: 0, y: 20, scale: 0.95 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={{ duration: 0.5, type: 'spring', stiffness: 120, damping: 20 }}
className='w-[608px] max-w-full py-8 px-2 md:px-8 overflow-hidden'
>
<HoverEffectCard
className='items-center gap-4 pt-0 pb-6 bg-default-50'
maxXRotation={3}
maxYRotation={3}
>
<CardHeader className='inline-block max-w-lg text-center justify-center'>
<div className='flex items-center justify-center w-full gap-2 pt-10'>
<Image alt='logo' height='7em' src={logo} />
<div>
<span className={title()}>Web&nbsp;</span>
<span className={title({ color: 'violet' })}>
Login&nbsp;
</span>
</div>
</div>
<ThemeSwitch className='absolute right-4 top-4' />
</CardHeader>
<CardBody className='flex gap-5 py-5 px-5 md:px-10'>
{isPasskeyLoading && (
<div className='text-center text-small text-default-600 dark:text-default-400 px-2'>
🔐 正在检查Passkey...
</div>
)}
{/* 2FA验证步骤 */}
{require2FA ? (
<>
<Button
isIconOnly
variant='light'
className='self-start -ml-2'
onPress={goBackToToken}
>
<IoArrowBack size={20} />
</Button>
<div className='text-center text-default-600 dark:text-default-400'>
请输入Authenticator中的验证码
</div>
<form
onSubmit={(e) => {
e.preventDefault();
onSubmit2FA();
}}
>
<Input
type='text'
inputMode='numeric'
pattern='[0-9]*'
maxLength={6}
classNames={{
label: 'text-black/50 dark:text-white/90',
input: [
'bg-transparent',
'text-black/90 dark:text-white/90',
'placeholder:text-default-700/50 dark:placeholder:text-white/60',
],
innerWrapper: 'bg-transparent',
inputWrapper: [
'shadow-xl',
'bg-default-100/70',
'dark:bg-default/60',
'backdrop-blur-xl',
'backdrop-saturate-200',
'hover:bg-default-0/70',
'dark:hover:bg-default/70',
'group-data-[focus=true]:bg-default-100/50',
'dark:group-data-[focus=true]:bg-default/60',
'!cursor-text',
],
}}
isDisabled={isLoading}
label='验证码'
placeholder='请输入6位验证码'
radius='lg'
size='lg'
startContent={
<IoKeyOutline className='text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0' />
}
value={totpCode}
onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, ''))}
/>
</form>
<Button
className='mx-10 mt-10 text-lg py-7'
color='primary'
isLoading={isLoading}
radius='full'
size='lg'
variant='shadow'
onPress={onSubmit2FA}
>
验证
</Button>
</>
) : (
<>
<form
onSubmit={(e) => {
e.preventDefault();
onSubmitToken();
}}
>
{/* 隐藏的用户名字段,帮助浏览器识别登录表单 */}
<input
type='text'
name='username'
value='napcat-webui'
autoComplete='username'
className='absolute -left-[9999px] opacity-0 pointer-events-none'
readOnly
tabIndex={-1}
aria-label='Username'
/>
<Input
isClearable
type='password'
name='password'
autoComplete='current-password'
classNames={{
label: 'text-black/50 dark:text-white/90',
input: [
'bg-transparent',
'text-black/90 dark:text-white/90',
'placeholder:text-default-700/50 dark:placeholder:text-white/60',
],
innerWrapper: 'bg-transparent',
inputWrapper: [
'shadow-xl',
'bg-default-100/70',
'dark:bg-default/60',
'backdrop-blur-xl',
'backdrop-saturate-200',
'hover:bg-default-0/70',
'dark:hover:bg-default/70',
'group-data-[focus=true]:bg-default-100/50',
'dark:group-data-[focus=true]:bg-default/60',
'!cursor-text',
],
}}
isDisabled={isLoading || isPasskeyLoading}
label='Token'
placeholder='请输入token'
radius='lg'
size='lg'
startContent={
<IoKeyOutline className='text-black/50 mb-0.5 dark:text-white/90 text-slate-400 pointer-events-none flex-shrink-0' />
}
value={tokenValue}
onChange={(e) => setTokenValue(e.target.value)}
onClear={() => setTokenValue('')}
/>
</form>
<div className='text-center text-small text-default-600 dark:text-default-400 px-2'>
💡 提示:请从 NapCat 启动日志中查看登录密钥
</div>
<Button
className='mx-10 mt-10 text-lg py-7'
color='primary'
isLoading={isLoading}
radius='full'
size='lg'
variant='shadow'
onPress={onSubmitToken}
>
{!isLoading && (
<Image
alt='logo'
classNames={{
wrapper: '-ml-8',
}}
height='2em'
src={logo}
/>
)}
登录
</Button>
</>
)}
</CardBody>
</HoverEffectCard>
</motion.div>
</PureLayout>
</>
);
}