feat(webui): add optional TOTP 2FA for operator login (#351)

WebUI access was a single shared password. This adds optional
Authenticator TOTP as a second factor, with one-time recovery codes
and SSH as the last-resort disable path.

Login stays two HTTP posts with no pending token: a correct password
and enabled 2FA without a second factor returns { needsTotp: true };
the client then resubmits { password, totp } or { password, recoveryCode }.
The TOTP secret is wrapped with a password-derived AES-256-GCM key.
Eight XXXX-XXXX recovery codes are stored as SHA-256 hashes and each
code is consumed once. Enabling or disabling 2FA invalidates other
sessions; disabling still requires password plus TOTP or a recovery
code. SNOWLUMA_DEV_MODE hides the feature.

The login page uses a dedicated second-factor screen (Interior OTP
cells for the 6-digit code; the same cell UI for recovery codes,
grouped as XXXX-XXXX). Settings expose enroll/confirm/disable and
one-time recovery-code display.

Fixes #351
This commit is contained in:
DrSmoothl committed 2026-08-13 01:33:57 +08:00
1 parent 679f3b5b9f
commit 5c2f620c54
23 files changed
+2676 -153

No files matched your search

+3 -2
View File
@@ -44,10 +44,11 @@
"@snowluma/bridge": "workspace:*",
"@snowluma/common": "workspace:*",
"@snowluma/onebot": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/websocket": "workspace:*"
"@snowluma/websocket": "workspace:*",
"otpauth": "^9.5.1"
},
"devDependencies": {
"@hono/node-server": "^1.19.14",
+74 -10
View File
@@ -2,6 +2,12 @@ import { createLogger } from '@snowluma/common/logger';
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
import fs from 'fs';
import path from 'path';
import {
parseTotpStateLenient,
prepareTotpStateForRestore,
rewrapTotpSecret,
type TotpPersistedState,
} from './totp';
const log = createLogger('WebUI.Auth');
@@ -32,6 +38,7 @@ export interface WebuiAuthState {
mustChangePassword: boolean;
generatedAt: string;
updatedAt: string;
totp?: TotpPersistedState;
}
export interface PasswordRule {
@@ -91,24 +98,43 @@ export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState
if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) {
throw new Error('updatedAt must be a valid timestamp');
}
const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt']);
const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt', 'totp']);
const unknown = Object.keys(v).find((key) => !allowed.has(key));
if (unknown) throw new Error(`unknown field $.${unknown}`);
return {
const state: WebuiAuthState = {
passwordHash: v.passwordHash,
passwordSalt: v.passwordSalt,
mustChangePassword: v.mustChangePassword,
generatedAt: v.generatedAt,
updatedAt: v.updatedAt,
};
if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) {
return state;
}
state.totp = prepareTotpStateForRestore(v.totp);
return state;
}
function isValidState(value: unknown): value is WebuiAuthState {
function parseLiveAuthState(value: unknown): WebuiAuthState | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const v = value as Record<string, unknown>;
const totpValue = v.totp;
const withoutTotp = { ...v };
delete withoutTotp.totp;
try {
prepareWebuiAuthStateForRestore(value);
return true;
const state = prepareWebuiAuthStateForRestore(
Object.prototype.hasOwnProperty.call(v, 'totp')
? withoutTotp
: value,
);
const totp = parseTotpStateLenient(totpValue);
if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) {
log.warn('webui.json totp field is invalid and will be ignored; password credentials are unchanged');
}
if (totp) state.totp = totp;
return state;
} catch {
return false;
return null;
}
}
@@ -177,8 +203,9 @@ export class WebuiAuth {
try {
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
if (isValidState(parsed)) {
if (parsed.mustChangePassword) {
const live = parseLiveAuthState(parsed);
if (live) {
if (live.mustChangePassword) {
// Previous start generated a bootstrap password but the operator
// never completed the forced-change flow. The plaintext is gone
// (only the hash is on disk, and the log line from last run may
@@ -189,7 +216,7 @@ export class WebuiAuth {
log.warn('previous bootstrap password was never rotated; regenerated a new one');
return new WebuiAuth(state, initialPassword, false);
}
return new WebuiAuth(parsed, null, false);
return new WebuiAuth(live, null, false);
}
log.error('webui.json schema invalid; backing up and regenerating credentials');
backupCorruptConfig();
@@ -257,13 +284,20 @@ export class WebuiAuth {
}
}
setPassword(newPassword: string): void {
setPassword(newPassword: string, currentPassword?: string): void {
if (this.devMode) {
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
}
if (!isStrongPassword(newPassword)) {
throw new Error('密码不符合强度要求');
}
let totp = this.state.totp;
if (totp) {
if (typeof currentPassword !== 'string' || currentPassword.length === 0) {
throw new Error('修改密码需要当前密码以重新保护 2FA 密钥');
}
totp = rewrapTotpSecret(currentPassword, newPassword, totp);
}
const salt = randomBytes(16);
const hash = hashPassword(newPassword, salt);
const next: WebuiAuthState = {
@@ -272,8 +306,38 @@ export class WebuiAuth {
mustChangePassword: false,
generatedAt: this.state.generatedAt,
updatedAt: new Date().toISOString(),
...(totp ? { totp } : {}),
};
atomicWrite(next);
this.state = next;
}
totpEnabled(): boolean {
return this.state.totp !== undefined;
}
totpStatus(): { enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } {
const totp = this.state.totp;
if (!totp) return { enabled: false };
return {
enabled: true,
remainingRecoveryCodes: totp.recoveryCodeHashes.length,
label: totp.label,
};
}
totpState(): TotpPersistedState | undefined {
return this.state.totp;
}
persistTotp(totp: TotpPersistedState | undefined): void {
if (this.devMode) {
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA');
}
const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() };
if (totp) next.totp = totp;
else delete next.totp;
atomicWrite(next);
this.state = next;
}
}
+214 -8
View File
@@ -39,6 +39,13 @@ import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
import { completeWebuiLogin, invalidateOtherSessions } from './webui-login';
import {
beginTotpEnrollment,
confirmTotpEnrollment,
decideSecondFactorLogin,
regenerateRecoveryCodes,
} from './totp';
import {
EULA_ACCEPT_ENV,
getAgreementsPayload,
@@ -103,10 +110,18 @@ interface SessionInfo {
const sessionTokens = new Map<string, SessionInfo>();
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
const totpEnrollments = new Map<string, {
secret: string;
issuer: string;
accountName: string;
expiresAt: number;
}>();
const LOGIN_MAX_ATTEMPTS = 5;
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000;
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
const TOTP_ENROLL_TTL_MS = 10 * 60 * 1000;
const DEFAULT_TOTP_ISSUER = 'SnowLuma';
const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60;
@@ -229,6 +244,21 @@ function purgeExpiredTokens() {
for (const [ip, attempt] of loginAttempts) {
if (now > attempt.resetAt) loginAttempts.delete(ip);
}
for (const [token, enrollment] of totpEnrollments) {
if (now > enrollment.expiresAt) totpEnrollments.delete(token);
}
}
function sanitizeTotpLabelPart(value: unknown, fallback: string): string {
if (typeof value !== 'string') return fallback;
const trimmed = value.replace(/[\r\n\t]/g, '').trim();
if (!trimmed) return fallback;
return trimmed.slice(0, 64);
}
function defaultTotpAccountName(): string {
const host = os.hostname().trim();
return host || 'admin';
}
@@ -632,27 +662,42 @@ export async function initWebUI(
return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429);
}
let body: { password?: unknown };
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
if (!auth.verify(password)) {
const result = completeWebuiLogin(auth, body, now);
if (result.kind === 'bad-request') {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
if (result.kind === 'bad-password' || result.kind === 'bad-second-factor') {
const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS };
current.count += 1;
if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS;
loginAttempts.set(ip, current);
return c.json({ success: false, message: '密码错误' }, 401);
const message = result.kind === 'bad-second-factor' ? '验证码不正确' : '密码错误';
return c.json({ success: false, message }, 401);
}
if (result.kind === 'needs-totp') {
return c.json({ success: false, needsTotp: true });
}
loginAttempts.delete(ip);
if (result.totpState) {
try {
auth.persistTotp(result.totpState);
} catch (err) {
log.warn('persist totp after login failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '登录失败' }, 500);
}
}
const token = randomBytes(32).toString('hex');
const mustChange = auth.mustChangePassword();
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: result.mustChangePassword });
setAvatarSessionCookie(c, token, listener.tlsEnabled === true);
return c.json({ success: true, token, mustChangePassword: mustChange });
return c.json({ success: true, token, mustChangePassword: result.mustChangePassword });
});
app.post('/api/logout', (c) => {
@@ -703,7 +748,7 @@ export async function initWebUI(
return c.json({ success: false, message: '新密码不得与旧密码相同' }, 400);
}
try {
auth.setPassword(newPassword);
auth.setPassword(newPassword, oldPassword);
} catch (err) {
log.warn('change password failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '密码修改失败' }, 400);
@@ -717,6 +762,167 @@ export async function initWebUI(
return c.json({ success: true, requireRelogin: true });
});
const totpDisabledInDev = () => auth.isDevMode();
app.get('/api/auth/totp', (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
return c.json(auth.totpStatus());
});
app.post('/api/auth/totp/begin', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
if (auth.totpEnabled()) {
return c.json({ success: false, message: '2FA 已开启' }, 409);
}
const token = c.get('sessionToken' as never) as string;
let body: Record<string, unknown> = {};
try {
const parsed = await c.req.json();
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
body = parsed as Record<string, unknown>;
}
} catch {
body = {};
}
const issuer = sanitizeTotpLabelPart(body.issuer, DEFAULT_TOTP_ISSUER);
const accountName = sanitizeTotpLabelPart(body.accountName, defaultTotpAccountName());
const now = Date.now();
const existing = totpEnrollments.get(token);
const secret = existing && existing.expiresAt > now ? existing.secret : undefined;
const enrollment = beginTotpEnrollment({ issuer, accountName, secret });
totpEnrollments.set(token, {
secret: enrollment.secret,
issuer,
accountName,
expiresAt: now + TOTP_ENROLL_TTL_MS,
});
return c.json({
success: true,
secret: enrollment.secret,
otpauthUrl: enrollment.otpauthUrl,
issuer: enrollment.issuer,
accountName: enrollment.accountName,
});
});
app.post('/api/auth/totp/confirm', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
if (auth.totpEnabled()) {
return c.json({ success: false, message: '2FA 已开启' }, 409);
}
const token = c.get('sessionToken' as never) as string;
let body: { password?: unknown; code?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
const code = typeof body.code === 'string' ? body.code : '';
if (!auth.verify(password)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
const pending = totpEnrollments.get(token);
if (!pending || pending.expiresAt <= Date.now()) {
totpEnrollments.delete(token);
return c.json({ success: false, message: '请先开始绑定' }, 400);
}
try {
const enabled = confirmTotpEnrollment({
password,
secret: pending.secret,
code,
label: `${pending.issuer} (${pending.accountName})`,
atMs: Date.now(),
});
auth.persistTotp(enabled.state);
totpEnrollments.delete(token);
invalidateOtherSessions(sessionTokens, token);
log.info('webui 2FA enabled; other sessions invalidated');
return c.json({ success: true, recoveryCodes: enabled.recoveryCodes });
} catch (err) {
log.warn('totp confirm failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '验证码不正确' }, 401);
}
});
app.post('/api/auth/totp/disable', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
if (!auth.totpEnabled()) {
return c.json({ success: false, message: '2FA 未开启' }, 400);
}
const token = c.get('sessionToken' as never) as string;
let body: { password?: unknown; totp?: unknown; recoveryCode?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
if (!auth.verify(password)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
const decision = decideSecondFactorLogin({
totpEnabled: true,
state: auth.totpState(),
password,
totp: typeof body.totp === 'string' ? body.totp : undefined,
recoveryCode: typeof body.recoveryCode === 'string' ? body.recoveryCode : undefined,
atMs: Date.now(),
});
if (decision.kind !== 'ok') {
return c.json({ success: false, message: '验证码不正确' }, 401);
}
auth.persistTotp(undefined);
totpEnrollments.delete(token);
invalidateOtherSessions(sessionTokens, token);
log.info('webui 2FA disabled; other sessions invalidated');
return c.json({ success: true });
});
app.post('/api/auth/totp/recovery-codes', async (c) => {
if (totpDisabledInDev()) {
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
}
const state = auth.totpState();
if (!state) {
return c.json({ success: false, message: '2FA 未开启' }, 400);
}
let body: { password?: unknown; totp?: unknown };
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
const password = typeof body.password === 'string' ? body.password : '';
const totp = typeof body.totp === 'string' ? body.totp : '';
if (!auth.verify(password)) {
return c.json({ success: false, message: '当前密码不正确' }, 401);
}
try {
const next = regenerateRecoveryCodes({
password,
state,
totp,
atMs: Date.now(),
});
auth.persistTotp(next.state);
log.info('webui 2FA recovery codes regenerated');
return c.json({ success: true, recoveryCodes: next.recoveryCodes });
} catch (err) {
log.warn('totp recovery regenerate failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '验证码不正确' }, 401);
}
});
// ─── EULA / PRIVACY consent ──────────────────────────────────────────────
// Both are bearer-gated (consent is collected AFTER login) and live in the
// consent + must-change allowlists so they're reachable during onboarding.
+337
View File
@@ -0,0 +1,337 @@
import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
import * as OTPAuth from 'otpauth';
const TOTP_PERIOD_SECONDS = 30;
const TOTP_WINDOW = 1;
const TOTP_DIGITS = 6;
const RECOVERY_CODE_COUNT = 8;
const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const WRAP_SALT_BYTES = 16;
const WRAP_IV_BYTES = 12;
const WRAP_KEY_BYTES = 32;
const SCRYPT_N = 16384;
const SCRYPT_R = 8;
const SCRYPT_P = 1;
export interface WrappedTotpSecret {
wrapSalt: string;
iv: string;
ciphertext: string;
authTag: string;
}
export interface TotpPersistedState extends WrappedTotpSecret {
recoveryCodeHashes: string[];
lastUsedStep: number;
label: string;
}
export interface TotpEnrollment {
secret: string;
otpauthUrl: string;
issuer: string;
accountName: string;
}
function totpFromSecret(secretBase32: string, issuer = '', accountName = 'admin'): OTPAuth.TOTP {
return new OTPAuth.TOTP({
issuer,
label: accountName,
algorithm: 'SHA1',
digits: TOTP_DIGITS,
period: TOTP_PERIOD_SECONDS,
secret: OTPAuth.Secret.fromBase32(secretBase32),
});
}
export function verifyTotpCode(
secretBase32: string,
code: string,
atMs: number,
lastUsedStep?: number,
): { ok: true; step: number } | { ok: false } {
const token = code.replace(/\s/g, '');
if (!/^\d{6}$/.test(token)) return { ok: false };
let totp: OTPAuth.TOTP;
try {
totp = totpFromSecret(secretBase32);
} catch {
return { ok: false };
}
const delta = totp.validate({ token, timestamp: atMs, window: TOTP_WINDOW });
if (delta === null) return { ok: false };
const step = totp.counter({ timestamp: atMs }) + delta;
if (lastUsedStep !== undefined && step === lastUsedStep) return { ok: false };
return { ok: true, step };
}
function deriveWrapKey(password: string, salt: Buffer): Buffer {
return scryptSync(password, salt, WRAP_KEY_BYTES, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
}
export function wrapTotpSecret(password: string, secret: string): WrappedTotpSecret {
const wrapSalt = randomBytes(WRAP_SALT_BYTES);
const iv = randomBytes(WRAP_IV_BYTES);
const key = deriveWrapKey(password, wrapSalt);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
return {
wrapSalt: wrapSalt.toString('hex'),
iv: iv.toString('hex'),
ciphertext: ciphertext.toString('hex'),
authTag: cipher.getAuthTag().toString('hex'),
};
}
export function unwrapTotpSecret(password: string, wrapped: WrappedTotpSecret): string | null {
try {
const wrapSalt = Buffer.from(wrapped.wrapSalt, 'hex');
const iv = Buffer.from(wrapped.iv, 'hex');
const ciphertext = Buffer.from(wrapped.ciphertext, 'hex');
const authTag = Buffer.from(wrapped.authTag, 'hex');
if (wrapSalt.length !== WRAP_SALT_BYTES || iv.length !== WRAP_IV_BYTES || authTag.length !== 16) {
return null;
}
const key = deriveWrapKey(password, wrapSalt);
const decipher = createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
} catch {
return null;
}
}
function randomRecoveryChunk(): string {
const bytes = randomBytes(4);
let chunk = '';
for (let i = 0; i < 4; i++) {
chunk += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length];
}
return chunk;
}
export function generateRecoveryCodes(): string[] {
const codes = new Set<string>();
while (codes.size < RECOVERY_CODE_COUNT) {
codes.add(`${randomRecoveryChunk()}-${randomRecoveryChunk()}`);
}
return [...codes];
}
export function normalizeRecoveryCode(code: string): string {
return code.replace(/[-\s]/g, '').toUpperCase();
}
export function hashRecoveryCode(code: string): string {
return createHash('sha256').update(normalizeRecoveryCode(code), 'utf8').digest('hex');
}
function hashesEqual(left: string, right: string): boolean {
const a = Buffer.from(left, 'hex');
const b = Buffer.from(right, 'hex');
if (a.length !== b.length || a.length === 0) return false;
return timingSafeEqual(a, b);
}
export function consumeRecoveryCode(
code: string,
hashes: readonly string[],
): { ok: true; remainingHashes: string[] } | { ok: false } {
const candidate = hashRecoveryCode(code);
const index = hashes.findIndex((hash) => hashesEqual(hash, candidate));
if (index < 0) return { ok: false };
return { ok: true, remainingHashes: hashes.filter((_, i) => i !== index) };
}
export function beginTotpEnrollment(options: {
issuer: string;
accountName: string;
secret?: string;
}): TotpEnrollment {
const secret = options.secret ?? new OTPAuth.Secret({ size: 20 }).base32;
const totp = totpFromSecret(secret, options.issuer, options.accountName);
return {
secret,
otpauthUrl: totp.toString(),
issuer: options.issuer,
accountName: options.accountName,
};
}
export function confirmTotpEnrollment(options: {
password: string;
secret: string;
code: string;
label: string;
atMs: number;
}): { state: TotpPersistedState; recoveryCodes: string[] } {
const verified = verifyTotpCode(options.secret, options.code, options.atMs);
if (!verified.ok) {
throw new Error('验证码不正确');
}
const recoveryCodes = generateRecoveryCodes();
return {
recoveryCodes,
state: {
...wrapTotpSecret(options.password, options.secret),
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
lastUsedStep: verified.step,
label: options.label,
},
};
}
export function verifySecondFactor(options: {
password: string;
state: TotpPersistedState;
atMs: number;
totp?: string;
recoveryCode?: string;
}): { ok: true; state: TotpPersistedState } | { ok: false } {
if (typeof options.recoveryCode === 'string' && options.recoveryCode.length > 0) {
const consumed = consumeRecoveryCode(options.recoveryCode, options.state.recoveryCodeHashes);
if (!consumed.ok) return { ok: false };
return { ok: true, state: { ...options.state, recoveryCodeHashes: consumed.remainingHashes } };
}
if (typeof options.totp !== 'string') return { ok: false };
const secret = unwrapTotpSecret(options.password, options.state);
if (secret === null) return { ok: false };
const checked = verifyTotpCode(secret, options.totp, options.atMs, options.state.lastUsedStep);
if (!checked.ok) return { ok: false };
return { ok: true, state: { ...options.state, lastUsedStep: checked.step } };
}
export type SecondFactorDecision =
| { kind: 'needs-totp' }
| { kind: 'bad-second-factor' }
| { kind: 'ok'; state?: TotpPersistedState };
export function decideSecondFactorLogin(options: {
totpEnabled: boolean;
state?: TotpPersistedState;
password: string;
totp?: string;
recoveryCode?: string;
atMs: number;
}): SecondFactorDecision {
if (!options.totpEnabled) return { kind: 'ok' };
if (!options.state) return { kind: 'bad-second-factor' };
const totp = typeof options.totp === 'string' && options.totp.trim().length > 0
? options.totp.trim()
: undefined;
const recoveryCode = typeof options.recoveryCode === 'string' && options.recoveryCode.trim().length > 0
? options.recoveryCode.trim()
: undefined;
if (!totp && !recoveryCode) return { kind: 'needs-totp' };
const result = verifySecondFactor({
password: options.password,
state: options.state,
atMs: options.atMs,
totp,
recoveryCode,
});
if (!result.ok) return { kind: 'bad-second-factor' };
return { kind: 'ok', state: result.state };
}
export function regenerateRecoveryCodes(options: {
password: string;
state: TotpPersistedState;
totp: string;
atMs: number;
}): { state: TotpPersistedState; recoveryCodes: string[] } {
const verified = verifySecondFactor({
password: options.password,
state: options.state,
totp: options.totp,
atMs: options.atMs,
});
if (!verified.ok) {
throw new Error('验证码不正确');
}
const recoveryCodes = generateRecoveryCodes();
return {
recoveryCodes,
state: {
...verified.state,
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
},
};
}
export function rewrapTotpSecret(
oldPassword: string,
newPassword: string,
state: TotpPersistedState,
): TotpPersistedState {
const secret = unwrapTotpSecret(oldPassword, state);
if (secret === null) {
throw new Error('无法使用当前密码解开 2FA 密钥');
}
return {
...state,
...wrapTotpSecret(newPassword, secret),
};
}
const HEX = /^[0-9a-f]+$/i;
function isWrappedShape(value: Record<string, unknown>): value is WrappedTotpSecret & Record<string, unknown> {
return typeof value.wrapSalt === 'string'
&& HEX.test(value.wrapSalt)
&& value.wrapSalt.length === WRAP_SALT_BYTES * 2
&& typeof value.iv === 'string'
&& HEX.test(value.iv)
&& value.iv.length === WRAP_IV_BYTES * 2
&& typeof value.ciphertext === 'string'
&& HEX.test(value.ciphertext)
&& value.ciphertext.length > 0
&& value.ciphertext.length % 2 === 0
&& typeof value.authTag === 'string'
&& HEX.test(value.authTag)
&& value.authTag.length === 32;
}
export function prepareTotpStateForRestore(value: unknown): TotpPersistedState {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error('totp state must be an object');
}
const v = value as Record<string, unknown>;
if (!isWrappedShape(v)) {
throw new Error('totp wrapped secret fields are invalid');
}
if (!Array.isArray(v.recoveryCodeHashes)
|| v.recoveryCodeHashes.length > RECOVERY_CODE_COUNT
|| v.recoveryCodeHashes.some((hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash))) {
throw new Error('totp recoveryCodeHashes must be SHA-256 hex strings');
}
if (typeof v.lastUsedStep !== 'number' || !Number.isInteger(v.lastUsedStep) || v.lastUsedStep < 0) {
throw new Error('totp lastUsedStep must be a non-negative integer');
}
if (typeof v.label !== 'string' || v.label.length === 0 || v.label.length > 128) {
throw new Error('totp label must be a non-empty string');
}
const allowed = new Set(['wrapSalt', 'iv', 'ciphertext', 'authTag', 'recoveryCodeHashes', 'lastUsedStep', 'label']);
const unknown = Object.keys(v).find((key) => !allowed.has(key));
if (unknown) throw new Error(`unknown totp field $.${unknown}`);
return {
wrapSalt: v.wrapSalt.toLowerCase(),
iv: v.iv.toLowerCase(),
ciphertext: v.ciphertext.toLowerCase(),
authTag: v.authTag.toLowerCase(),
recoveryCodeHashes: v.recoveryCodeHashes.map((hash) => (hash as string).toLowerCase()),
lastUsedStep: v.lastUsedStep,
label: v.label,
};
}
export function parseTotpStateLenient(value: unknown): TotpPersistedState | undefined {
if (value === undefined || value === null) return undefined;
try {
return prepareTotpStateForRestore(value);
} catch {
return undefined;
}
}
+51
View File
@@ -0,0 +1,51 @@
import { decideSecondFactorLogin, type TotpPersistedState } from './totp';
export interface WebuiLoginAuth {
verify(password: string): boolean;
totpEnabled(): boolean;
totpState(): TotpPersistedState | undefined;
mustChangePassword(): boolean;
}
export type WebuiLoginResult =
| { kind: 'bad-request' }
| { kind: 'bad-password' }
| { kind: 'needs-totp' }
| { kind: 'bad-second-factor' }
| { kind: 'ok'; mustChangePassword: boolean; totpState?: TotpPersistedState };
function readString(value: unknown): string {
return typeof value === 'string' ? value : '';
}
export function completeWebuiLogin(auth: WebuiLoginAuth, body: unknown, atMs: number): WebuiLoginResult {
if (!body || typeof body !== 'object' || Array.isArray(body)) {
return { kind: 'bad-request' };
}
const record = body as Record<string, unknown>;
const password = readString(record.password);
if (!auth.verify(password)) {
return { kind: 'bad-password' };
}
const decision = decideSecondFactorLogin({
totpEnabled: auth.totpEnabled(),
state: auth.totpState(),
password,
totp: readString(record.totp) || undefined,
recoveryCode: readString(record.recoveryCode) || undefined,
atMs,
});
if (decision.kind === 'needs-totp') return { kind: 'needs-totp' };
if (decision.kind === 'bad-second-factor') return { kind: 'bad-second-factor' };
return {
kind: 'ok',
mustChangePassword: auth.mustChangePassword(),
...(decision.state ? { totpState: decision.state } : {}),
};
}
export function invalidateOtherSessions<T>(sessions: Map<string, T>, keepToken: string): void {
for (const token of sessions.keys()) {
if (token !== keepToken) sessions.delete(token);
}
}
+88
View File
@@ -0,0 +1,88 @@
import { describe, expect, it } from 'vitest';
import { confirmTotpEnrollment } from '../src/webui/totp';
import { completeWebuiLogin, invalidateOtherSessions, type WebuiLoginAuth } from '../src/webui/webui-login';
const RFC_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
const T59_MS = 59_000;
const T59_CODE = '287082';
const PASSWORD = 'Correct-Horse-1!';
function authWithoutTotp(): WebuiLoginAuth {
return {
verify: (password) => password === PASSWORD,
totpEnabled: () => false,
totpState: () => undefined,
mustChangePassword: () => false,
};
}
describe('completeWebuiLogin', () => {
it('rejects a wrong password without mentioning TOTP', () => {
expect(completeWebuiLogin(authWithoutTotp(), { password: 'nope' }, T59_MS)).toEqual({
kind: 'bad-password',
});
});
it('logs in with only a password when 2FA is off', () => {
expect(completeWebuiLogin(authWithoutTotp(), { password: PASSWORD }, T59_MS)).toEqual({
kind: 'ok',
mustChangePassword: false,
});
});
it('asks for TOTP after a correct password when 2FA is on', () => {
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
const auth: WebuiLoginAuth = {
verify: (password) => password === PASSWORD,
totpEnabled: () => true,
totpState: () => enabled.state,
mustChangePassword: () => false,
};
expect(completeWebuiLogin(auth, { password: PASSWORD }, T59_MS)).toEqual({
kind: 'needs-totp',
});
});
it('accepts password plus TOTP and returns the updated totp state', () => {
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
const auth: WebuiLoginAuth = {
verify: (password) => password === PASSWORD,
totpEnabled: () => true,
totpState: () => enabled.state,
mustChangePassword: () => true,
};
const result = completeWebuiLogin(
auth,
{ password: PASSWORD, totp: '081804' },
1_111_111_109_000,
);
expect(result.kind).toBe('ok');
if (result.kind !== 'ok') return;
expect(result.mustChangePassword).toBe(true);
expect(result.totpState?.lastUsedStep).toBeGreaterThan(enabled.state.lastUsedStep);
});
});
describe('invalidateOtherSessions', () => {
it('keeps the current session and drops the rest', () => {
const sessions = new Map([
['keep', { n: 1 }],
['drop-a', { n: 2 }],
['drop-b', { n: 3 }],
]);
invalidateOtherSessions(sessions, 'keep');
expect([...sessions.keys()]).toEqual(['keep']);
});
});
+272
View File
@@ -0,0 +1,272 @@
import { describe, expect, it } from 'vitest';
import { prepareWebuiAuthStateForRestore } from '../src/webui/auth';
import {
beginTotpEnrollment,
confirmTotpEnrollment,
consumeRecoveryCode,
decideSecondFactorLogin,
generateRecoveryCodes,
hashRecoveryCode,
parseTotpStateLenient,
prepareTotpStateForRestore,
regenerateRecoveryCodes,
rewrapTotpSecret,
unwrapTotpSecret,
verifySecondFactor,
verifyTotpCode,
wrapTotpSecret,
} from '../src/webui/totp';
// RFC 6238 Appendix B, SHA-1, secret ASCII "12345678901234567890".
// 8-digit vector at T=59 is 94287082; 6-digit TOTP is that value mod 10^6.
const RFC_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
const T59_MS = 59_000;
const T59_CODE = '287082';
const T1111111109_MS = 1_111_111_109_000;
const T1111111109_CODE = '081804';
const PASSWORD = 'Correct-Horse-1!';
describe('verifyTotpCode', () => {
it('accepts the RFC 6238 SHA-1 6-digit code at T=59', () => {
expect(verifyTotpCode(RFC_SECRET, T59_CODE, T59_MS)).toEqual({ ok: true, step: 1 });
});
it('rejects a wrong 6-digit code at the same instant', () => {
expect(verifyTotpCode(RFC_SECRET, '000000', T59_MS)).toEqual({ ok: false });
});
it('rejects the same time-step being used twice', () => {
expect(verifyTotpCode(RFC_SECRET, T59_CODE, T59_MS, 1)).toEqual({ ok: false });
});
});
describe('wrapTotpSecret', () => {
it('round-trips a TOTP secret with the wrapping password', () => {
const wrapped = wrapTotpSecret(PASSWORD, RFC_SECRET);
expect(wrapped.ciphertext.toLowerCase()).not.toContain(
Buffer.from(RFC_SECRET, 'utf8').toString('hex'),
);
expect(unwrapTotpSecret(PASSWORD, wrapped)).toBe(RFC_SECRET);
});
it('returns null when the wrapping password is wrong', () => {
const wrapped = wrapTotpSecret(PASSWORD, RFC_SECRET);
expect(unwrapTotpSecret('Wrong-Password-2!', wrapped)).toBeNull();
});
});
describe('recovery codes', () => {
it('generates 8 XXXX-XXXX codes that each verify once', () => {
const codes = generateRecoveryCodes();
expect(codes).toHaveLength(8);
expect(new Set(codes).size).toBe(8);
for (const code of codes) {
expect(code).toMatch(/^[A-Z2-9]{4}-[A-Z2-9]{4}$/);
}
const hashes = codes.map(hashRecoveryCode);
const first = consumeRecoveryCode(codes[0]!, hashes);
expect(first.ok).toBe(true);
if (!first.ok) return;
expect(first.remainingHashes).toHaveLength(7);
expect(consumeRecoveryCode(codes[0]!, first.remainingHashes)).toEqual({ ok: false });
});
});
describe('totp enrollment and second factor', () => {
it('enables 2FA only after a matching TOTP code and then accepts a later code', () => {
const enrollment = beginTotpEnrollment({
issuer: 'SnowLuma',
accountName: 'testhost',
secret: RFC_SECRET,
});
expect(enrollment.otpauthUrl).toContain('otpauth://totp/');
expect(enrollment.otpauthUrl).toContain('secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
expect(enrollment.otpauthUrl).toContain('issuer=SnowLuma');
expect(() => confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: '000000',
label: 'SnowLuma (testhost)',
atMs: T59_MS,
})).toThrow(/验证码/);
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
expect(enabled.recoveryCodes).toHaveLength(8);
expect(enabled.state.lastUsedStep).toBe(1);
expect(enabled.state.label).toBe('SnowLuma (testhost)');
expect(enabled.state.recoveryCodeHashes).toHaveLength(8);
expect(verifySecondFactor({
password: PASSWORD,
totp: T59_CODE,
state: enabled.state,
atMs: T59_MS,
})).toEqual({ ok: false });
const later = verifySecondFactor({
password: PASSWORD,
totp: T1111111109_CODE,
state: enabled.state,
atMs: T1111111109_MS,
});
expect(later.ok).toBe(true);
if (!later.ok) return;
expect(later.state.lastUsedStep).toBeGreaterThan(enabled.state.lastUsedStep);
});
it('accepts a recovery code at login and consumes only that hash', () => {
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
const used = enabled.recoveryCodes[3]!;
const result = verifySecondFactor({
password: PASSWORD,
recoveryCode: used,
state: enabled.state,
atMs: T59_MS,
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.state.recoveryCodeHashes).toHaveLength(7);
expect(verifySecondFactor({
password: PASSWORD,
recoveryCode: used,
state: result.state,
atMs: T59_MS,
})).toEqual({ ok: false });
});
it('re-wraps the TOTP secret when the password changes', () => {
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
const nextPassword = 'Correct-Horse-2!';
const rewrapped = rewrapTotpSecret(PASSWORD, nextPassword, enabled.state);
expect(unwrapTotpSecret(nextPassword, rewrapped)).toBe(RFC_SECRET);
expect(unwrapTotpSecret(PASSWORD, rewrapped)).toBeNull();
expect(verifySecondFactor({
password: nextPassword,
totp: T1111111109_CODE,
state: rewrapped,
atMs: T1111111109_MS,
}).ok).toBe(true);
});
});
describe('totp persistence', () => {
it('round-trips a valid persisted totp object for backup restore', () => {
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
const restored = prepareTotpStateForRestore(JSON.parse(JSON.stringify(enabled.state)));
expect(restored).toEqual(enabled.state);
});
it('rejects a malformed totp object on restore', () => {
expect(() => prepareTotpStateForRestore({ wrapSalt: 'zz' })).toThrow(/totp/i);
});
it('treats a malformed totp object as absent when loading live config', () => {
expect(parseTotpStateLenient({ wrapSalt: 'zz' })).toBeUndefined();
expect(parseTotpStateLenient(undefined)).toBeUndefined();
});
it('keeps totp on credential restore and rejects a malformed totp object', () => {
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
const base = {
passwordHash: 'ab'.repeat(64),
passwordSalt: 'cd'.repeat(16),
mustChangePassword: false,
generatedAt: '2026-06-18T00:00:00.000Z',
updatedAt: '2026-06-18T00:00:00.000Z',
};
expect(prepareWebuiAuthStateForRestore({ ...base, totp: enabled.state }).totp).toEqual(enabled.state);
expect(() => prepareWebuiAuthStateForRestore({ ...base, totp: { wrapSalt: 'zz' } })).toThrow(/totp/i);
});
});
describe('decideSecondFactorLogin', () => {
it('asks for TOTP when 2FA is on and the request has no second factor', () => {
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
expect(decideSecondFactorLogin({
totpEnabled: true,
state: enabled.state,
password: PASSWORD,
atMs: T59_MS,
})).toEqual({ kind: 'needs-totp' });
});
it('skips the second factor when 2FA is off', () => {
expect(decideSecondFactorLogin({
totpEnabled: false,
password: PASSWORD,
totp: '000000',
atMs: T59_MS,
})).toEqual({ kind: 'ok' });
});
});
describe('regenerateRecoveryCodes', () => {
it('replaces every recovery hash after a valid TOTP', () => {
const enabled = confirmTotpEnrollment({
password: PASSWORD,
secret: RFC_SECRET,
code: T59_CODE,
label: 'SnowLuma (testhost)',
atMs: T59_MS,
});
const oldCode = enabled.recoveryCodes[0]!;
const next = regenerateRecoveryCodes({
password: PASSWORD,
state: enabled.state,
totp: T1111111109_CODE,
atMs: T1111111109_MS,
});
expect(next.recoveryCodes).toHaveLength(8);
expect(next.recoveryCodes).not.toContain(oldCode);
expect(verifySecondFactor({
password: PASSWORD,
recoveryCode: oldCode,
state: next.state,
atMs: T1111111109_MS,
})).toEqual({ ok: false });
expect(verifySecondFactor({
password: PASSWORD,
recoveryCode: next.recoveryCodes[0]!,
state: next.state,
atMs: T1111111109_MS,
}).ok).toBe(true);
});
});
+2 -1
View File
@@ -31,7 +31,8 @@
"react": "^19.2.5",
"react-dom": "^19.2.5",
"tailwind-merge": "^3.5.0",
"tw-animate-css": "^1.2.5"
"tw-animate-css": "^1.2.5",
"uqr": "^0.1.3"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
+47 -19
View File
@@ -92,6 +92,8 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi
// (which browsers autofill, misleading users on upgrade). Stays undefined
// for a returning session that's already authed but still must change.
const [loginPassword, setLoginPassword] = useState<string | undefined>(undefined);
const [urlLoginPassword, setUrlLoginPassword] = useState<string | undefined>(undefined);
const [urlNeedsTotp, setUrlNeedsTotp] = useState(false);
const authLoading = !authChecked || (authed && agreements === null && agreementsError === null);
const { showSkeleton: showAuthSkeleton } = useSkeletonSwap({ ready: !authLoading });
@@ -134,6 +136,10 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi
if (pw) {
const result = await client.login(pw);
if (result.ok) { ok = true; urlPassword = pw; }
else if ('needsTotp' in result && result.needsTotp) {
setUrlLoginPassword(pw);
setUrlNeedsTotp(true);
}
}
}
if (ok) {
@@ -166,6 +172,8 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi
setReplayingOnboarding(false);
onboardingReturnPath.current = null;
setLoginPassword(undefined);
setUrlLoginPassword(undefined);
setUrlNeedsTotp(false);
}, []);
const handleDecline = useCallback(async () => {
@@ -220,11 +228,15 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi
} else if (!authed) {
view = (
<LoginGate
initialPassword={urlLoginPassword}
initialNeedsTotp={urlNeedsTotp}
onAuthed={(needsChange, password) => {
setAuthed(true);
setStatus('已连接');
setMustChange(needsChange);
setLoginPassword(password);
setUrlLoginPassword(undefined);
setUrlNeedsTotp(false);
setOnboardingFinished(false);
void refreshAgreements();
}}
@@ -351,29 +363,45 @@ function Splash({ children }: { children: React.ReactNode }) {
);
}
function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: string) => void }) {
function LoginGate({
onAuthed,
initialPassword,
initialNeedsTotp,
}: {
onAuthed: (mustChange: boolean, password: string) => void;
initialPassword?: string;
initialNeedsTotp?: boolean;
}) {
const api = useApi();
const { runAction } = useActionFeedback();
const { startAction, dismiss } = useActionFeedback();
const handleLogin = useCallback(
async (password: string) => {
const result = await runAction(
{
title: '正在登录',
detail: '正在验证 WebUI 访问密码',
successTitle: '登录成功',
successDetail: '正在进入控制台',
errorTitle: '登录失败',
resultError: (login) => login.ok ? null : login.message,
},
() => api.login(password),
);
if (!result.ok) return { success: false, error: result.message };
onAuthed(result.mustChangePassword, password);
return { success: true };
async (password: string, secondFactor?: { totp?: string; recoveryCode?: string }) => {
const handle = startAction({
title: '正在登录',
detail: secondFactor ? '正在验证一次性密码' : '正在验证 WebUI 访问密码',
});
const result = await api.login(password, secondFactor);
if (result.ok) {
handle.succeed({ title: '登录成功', detail: '正在进入控制台' });
onAuthed(result.mustChangePassword, password);
return { success: true };
}
if ('message' in result) {
handle.fail(result.message, { title: '登录失败' });
return { success: false, error: result.message };
}
dismiss();
return { success: false, needsTotp: true };
},
[api, onAuthed, runAction],
[api, dismiss, onAuthed, startAction],
);
return (
<LoginPage
onLogin={handleLogin}
initialPassword={initialPassword}
initialNeedsTotp={initialNeedsTotp}
/>
);
return <LoginPage onLogin={handleLogin} />;
}
function OnboardingGate({
@@ -0,0 +1,503 @@
"use client";
import {
useCallback,
useEffect,
useId,
useImperativeHandle,
useRef,
useState,
type ChangeEvent,
type ClipboardEvent,
type FocusEvent,
type KeyboardEvent,
type Ref,
} from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
const CROSSFADE = { type: "spring", stiffness: 260, damping: 34, mass: 0.8 } as const;
const EASE = [0.23, 1, 0.32, 1] as const;
export type OtpMode = "numeric" | "alphanumeric";
const ALLOW: Record<OtpMode, RegExp> = {
numeric: /^[0-9]$/,
alphanumeric: /^[0-9a-zA-Z]$/,
};
export type UseOtpInputOptions = {
length?: number;
mode?: OtpMode;
defaultValue?: string;
disabled?: boolean;
onChange?: (value: string) => void;
onComplete?: (value: string) => void;
};
export type OtpCellProps = {
ref: (el: HTMLInputElement | null) => void;
value: string;
disabled: boolean;
type: "text";
inputMode: "numeric" | "text";
autoComplete: string;
autoCorrect: "off";
autoCapitalize: "off";
spellCheck: false;
onChange: (e: ChangeEvent<HTMLInputElement>) => void;
onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => void;
onPaste: (e: ClipboardEvent<HTMLInputElement>) => void;
onFocus: (e: FocusEvent<HTMLInputElement>) => void;
onBlur: (e: FocusEvent<HTMLInputElement>) => void;
};
export type UseOtpInputReturn = {
chars: string[];
value: string;
length: number;
complete: boolean;
focusedIndex: number;
getCellProps: (index: number) => OtpCellProps;
focusAt: (index: number) => void;
clear: () => void;
};
export function useOtpInput({
length = 6,
mode = "numeric",
defaultValue = "",
disabled = false,
onChange,
onComplete,
}: UseOtpInputOptions = {}): UseOtpInputReturn {
const allow = ALLOW[mode];
const keep = useCallback(
(text: string) =>
text
.split("")
.filter((c) => allow.test(c))
.join(""),
[allow],
);
const [chars, setChars] = useState<string[]>(() => {
const seed = defaultValue
.split("")
.filter((c) => ALLOW[mode].test(c))
.slice(0, length);
return Array.from({ length }, (_, i) => seed[i] ?? "");
});
const [focusedIndex, setFocusedIndex] = useState(-1);
const charsRef = useRef(chars);
const refs = useRef<(HTMLInputElement | null)[]>([]);
const changed = useRef(onChange);
const completed = useRef(onComplete);
useEffect(() => {
charsRef.current = chars;
}, [chars]);
useEffect(() => {
changed.current = onChange;
}, [onChange]);
useEffect(() => {
completed.current = onComplete;
}, [onComplete]);
useEffect(() => {
setChars((prev) =>
prev.length === length
? prev
: Array.from({ length }, (_, i) => prev[i] ?? ""),
);
refs.current.length = length;
}, [length]);
const commit = useCallback((next: string[]) => {
charsRef.current = next;
setChars(next);
const value = next.join("");
changed.current?.(value);
if (next.length > 0 && next.every((c) => c !== "")) completed.current?.(value);
}, []);
const focusAt = useCallback(
(index: number) => {
const el = refs.current[Math.max(0, Math.min(length - 1, index))];
if (!el) return;
el.focus();
el.select();
},
[length],
);
const fillFrom = useCallback(
(index: number, text: string) => {
const incoming = keep(text);
if (incoming.length === 0) return;
const next = [...charsRef.current];
let cursor = index;
for (const c of incoming) {
if (cursor >= length) break;
next[cursor] = c;
cursor += 1;
}
commit(next);
focusAt(cursor);
},
[commit, focusAt, keep, length],
);
const clear = useCallback(() => {
commit(Array.from({ length }, () => ""));
focusAt(0);
}, [commit, focusAt, length]);
const getCellProps = useCallback(
(index: number): OtpCellProps => ({
ref: (el) => {
refs.current[index] = el;
},
value: chars[index] ?? "",
disabled,
type: "text",
inputMode: mode === "numeric" ? "numeric" : "text",
autoComplete: index === 0 ? "one-time-code" : "off",
autoCorrect: "off",
autoCapitalize: "off",
spellCheck: false,
onChange: (e) => {
const previous = charsRef.current[index] ?? "";
const raw = e.currentTarget.value;
const trimmed =
raw.length > 1 && previous && raw.startsWith(previous)
? raw.slice(previous.length)
: raw;
const incoming = keep(trimmed);
if (incoming.length === 0) {
if (raw.length === 0 && previous) {
const next = [...charsRef.current];
next[index] = "";
commit(next);
}
e.currentTarget.value = charsRef.current[index] ?? "";
return;
}
if (incoming.length === 1) {
const next = [...charsRef.current];
next[index] = incoming;
e.currentTarget.value = incoming;
commit(next);
if (index < length - 1) focusAt(index + 1);
return;
}
fillFrom(index, incoming);
},
onKeyDown: (e) => {
if (e.key === "Backspace") {
e.preventDefault();
const current = charsRef.current;
const next = [...current];
if (current[index]) {
next[index] = "";
commit(next);
return;
}
if (index > 0) {
next[index - 1] = "";
commit(next);
focusAt(index - 1);
}
return;
}
if (e.key === "Delete") {
e.preventDefault();
const next = [...charsRef.current];
next[index] = "";
commit(next);
return;
}
if (e.key === "ArrowLeft") {
e.preventDefault();
focusAt(index - 1);
return;
}
if (e.key === "ArrowRight") {
e.preventDefault();
focusAt(index + 1);
return;
}
if (e.key === "Home") {
e.preventDefault();
focusAt(0);
return;
}
if (e.key === "End") {
e.preventDefault();
focusAt(length - 1);
}
},
onPaste: (e) => {
e.preventDefault();
const text = keep(e.clipboardData.getData("text"));
fillFrom(text.length >= length ? 0 : index, text);
},
onFocus: (e) => {
e.currentTarget.select();
const firstEmpty = charsRef.current.findIndex((c) => c === "");
if (firstEmpty !== -1 && firstEmpty < index) {
focusAt(firstEmpty);
return;
}
setFocusedIndex(index);
},
onBlur: (e) => {
const to = e.relatedTarget as HTMLInputElement | null;
if (to && refs.current.includes(to)) return;
setFocusedIndex(-1);
},
}),
[chars, commit, disabled, fillFrom, focusAt, keep, length, mode],
);
const value = chars.join("");
return {
chars,
value,
length,
complete: chars.length > 0 && chars.every((c) => c !== ""),
focusedIndex,
getCellProps,
focusAt,
clear,
};
}
export type OtpStatus = "idle" | "error" | "success";
export type OtpInputHandle = {
clear: () => void;
focus: () => void;
};
export type OtpInputProps = {
length?: number;
mode?: OtpMode;
defaultValue?: string;
onChange?: (value: string) => void;
onComplete?: (value: string) => void;
/** Official usage example: red cells + shake on the false → true edge. */
error?: boolean;
status?: OtpStatus;
errorMessage?: string;
successMessage?: string;
hint?: string;
label?: string;
groupEvery?: number;
/** Draw a rule between groups (recovery XXXX-XXXX). Spacing-only when false. */
groupSeparator?: boolean;
disabled?: boolean;
autoFocus?: boolean;
focusOnError?: boolean;
className?: string;
ref?: Ref<OtpInputHandle>;
};
export function OtpInput({
length = 6,
mode = "numeric",
defaultValue = "",
onChange,
onComplete,
error: errorProp = false,
status = "idle",
errorMessage = "",
successMessage = "",
hint = "",
label = "Verification code",
groupEvery = 3,
groupSeparator = false,
disabled = false,
autoFocus = false,
focusOnError = true,
className = "",
ref,
}: OtpInputProps) {
const reduced = useReducedMotion();
const statusId = useId();
const { chars, focusedIndex, getCellProps, focusAt, clear } = useOtpInput({
length,
mode,
defaultValue,
disabled,
onChange,
onComplete,
});
const wasError = useRef(false);
const error = errorProp || status === "error";
const success = status === "success";
const tone = error ? "error" : success ? "success" : "idle";
useImperativeHandle(
ref,
() => ({
clear: () => {
clear();
focusAt(0);
},
focus: () => focusAt(0),
}),
[clear, focusAt],
);
useEffect(() => {
if (error && !wasError.current && focusOnError && !disabled) focusAt(0);
wasError.current = error;
}, [error, focusOnError, disabled, focusAt]);
useEffect(() => {
if (autoFocus && !disabled) focusAt(0);
}, [autoFocus, disabled, focusAt]);
const enter = reduced ? { duration: 0 } : { duration: 0.22, ease: EASE };
const swap = reduced ? { duration: 0 } : CROSSFADE;
const hasStatus =
hint.length > 0 || errorMessage.length > 0 || successMessage.length > 0;
const message = error ? errorMessage : success ? successMessage : hint;
const messageTone = error
? "text-destructive"
: success
? "text-success"
: "text-muted-foreground";
return (
<div className={`flex w-full flex-col ${className}`}>
<motion.div
role="group"
aria-label={label}
className="relative flex w-full gap-2.5"
initial={false}
variants={{ idle: { x: 0 }, wrong: { x: [0, -5, 4, -3, 0] } }}
animate={error && !reduced ? "wrong" : "idle"}
transition={{ duration: 0.32, ease: EASE }}
>
{Array.from({ length }, (_, i) => {
const char = chars[i] ?? "";
const active = focusedIndex === i;
const gap = groupEvery > 0 && i > 0 && i % groupEvery === 0;
return (
<div key={i} className="contents">
{gap && groupSeparator ? (
<span
aria-hidden
className="flex h-16 w-3.5 shrink-0 items-center justify-center"
>
<span className="h-[2px] w-3 rounded-full bg-muted-foreground/55" />
</span>
) : null}
<div className={`relative h-16 min-w-0 flex-1 ${gap && !groupSeparator ? "ms-3" : ""}`}>
<input
{...getCellProps(i)}
aria-label={`${label}, character ${i + 1} of ${length}`}
aria-invalid={error || undefined}
aria-describedby={hasStatus ? statusId : undefined}
className={`size-full rounded-xl border-2 text-center text-xl text-transparent caret-transparent outline-none transition-[background-color,border-color,box-shadow] duration-150 selection:bg-transparent focus-visible:outline-none disabled:opacity-50 ${
error
? "border-destructive bg-background"
: success
? "border-success bg-background"
: active
? "border-primary bg-background"
: char
? "border-border bg-background"
: "border-border/80 bg-muted/60 shadow-[inset_0_1px_2px_color-mix(in_oklab,var(--foreground)_8%,transparent)]"
}`}
/>
<span
aria-hidden
className="pointer-events-none absolute inset-0 grid place-items-center"
>
<AnimatePresence initial={false} mode="popLayout">
{char ? (
<motion.span
key={char}
initial={
reduced
? false
: { opacity: 0, scale: 0.97, y: 10, filter: "blur(6px)" }
}
animate={{ opacity: 1, scale: 1, y: 0, filter: "blur(0px)" }}
exit={
reduced
? { opacity: 0 }
: { opacity: 0, scale: 0.98, y: -6, filter: "blur(3px)" }
}
transition={enter}
className="col-start-1 row-start-1 font-mono text-[22px] tabular-nums text-foreground"
>
{char}
</motion.span>
) : null}
</AnimatePresence>
{active && !char && !disabled ? (
<motion.span
className="col-start-1 row-start-1 block h-6 w-[1.5px] rounded-[1px] bg-foreground"
initial={{ opacity: 1 }}
animate={reduced ? { opacity: 1 } : { opacity: [1, 1, 0, 0] }}
transition={
reduced
? { duration: 0 }
: {
duration: 1.06,
times: [0, 0.5, 0.5, 1],
repeat: Infinity,
ease: "linear",
}
}
/>
) : null}
</span>
</div>
</div>
);
})}
</motion.div>
{hasStatus && (
<>
<div aria-hidden className="mt-2 grid h-4 text-[11.5px] leading-[16px]">
<AnimatePresence initial={false} mode="wait">
<motion.span
key={tone}
initial={reduced ? { opacity: 0 } : { opacity: 0, y: 3 }}
animate={{ opacity: 1, y: 0 }}
exit={reduced ? { opacity: 0 } : { opacity: 0, y: -3 }}
transition={swap}
className={`col-start-1 row-start-1 ${messageTone}`}
>
{message}
</motion.span>
</AnimatePresence>
</div>
<span id={statusId} role="status" className="sr-only">
{message}
</span>
</>
)}
</div>
);
}
@@ -1,7 +1,8 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react';
import { motion } from 'motion/react';
import { ArrowRight, KeyRound, Sparkles } from 'lucide-react';
import { Modal } from '@/components/interior/modal';
import { OtpInput, type OtpInputHandle } from '@/components/interior/otp-input';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
@@ -12,9 +13,16 @@ import { LoginWaves } from '@/components/login-waves';
import { useTheme } from '@/contexts/ThemeContext';
import { cn } from '@/lib/utils';
import { APP_NAME, APP_VERSION } from '@/types';
import { parseSecondFactor } from '@/lib/totp-second-factor';
interface LoginPageProps {
onLogin: (password: string) => Promise<{ success: boolean; error?: string }>;
onLogin: (
password: string,
secondFactor?: { totp?: string; recoveryCode?: string },
) => Promise<{ success: boolean; error?: string; needsTotp?: boolean }>;
initialPassword?: string;
initialNeedsTotp?: boolean;
initialUseRecovery?: boolean;
}
// Device-local preference for the (heavy) animated login background. Kept out
@@ -33,7 +41,12 @@ function readLoginFx(): boolean {
try { return !window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch { return true; }
}
export function LoginPage({ onLogin }: LoginPageProps) {
export function LoginPage({
onLogin,
initialPassword = '',
initialNeedsTotp = false,
initialUseRecovery = false,
}: LoginPageProps) {
const { appearance } = useTheme();
const customBg = appearance.background.type !== 'none';
const reduce = appearance.reduceMotion || appearance.disableMotion;
@@ -43,7 +56,11 @@ export function LoginPage({ onLogin }: LoginPageProps) {
// clear any lingering custom-CSS <style> whenever the login page shows.
useEffect(() => { document.getElementById('snowluma-custom-css')?.remove(); }, []);
const [password, setPassword] = useState('');
const [password, setPassword] = useState(initialPassword);
const [useRecovery, setUseRecovery] = useState(initialUseRecovery);
const [needsTotp, setNeedsTotp] = useState(initialNeedsTotp);
const [otpStatus, setOtpStatus] = useState<'idle' | 'checking' | 'rejected'>('idle');
const otpRef = useRef<OtpInputHandle>(null);
const [showPwd, setShowPwd] = useState(false);
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
@@ -56,24 +73,213 @@ export function LoginPage({ onLogin }: LoginPageProps) {
try { localStorage.setItem(LOGIN_FX_KEY, v ? '1' : '0'); } catch { /* ignore */ }
};
const handleSubmit = async (e: React.FormEvent) => {
useEffect(() => {
if (otpStatus !== 'rejected') return;
const id = window.setTimeout(() => {
otpRef.current?.clear();
setOtpStatus('idle');
setError('');
}, 1600);
return () => window.clearTimeout(id);
}, [otpStatus]);
const goBackToPassword = () => {
setNeedsTotp(false);
setUseRecovery(false);
setOtpStatus('idle');
setError('');
};
const handlePasswordSubmit = async (e: FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
const result = await onLogin(password);
setLoading(false);
if (result.needsTotp) {
setNeedsTotp(true);
setUseRecovery(false);
setOtpStatus('idle');
setError('');
return;
}
if (!result.success) {
setError(result.error || '登录失败');
setShake((k) => k + 1);
}
};
const submitTotp = async (code: string) => {
setOtpStatus('checking');
const result = await onLogin(password, parseSecondFactor(code));
if (result.success) return;
if (result.needsTotp) {
setOtpStatus('idle');
return;
}
setError(result.error || (useRecovery
? '恢复码不正确,改错的那一位即可。'
: '验证码不正确,改错的那一位即可。'));
setOtpStatus('rejected');
};
const handleTotpSubmit = (e: FormEvent) => {
e.preventDefault();
};
return (
<LoginShell
customBg={customBg}
reduce={reduce}
fxOn={fxOn}
helpOpen={helpOpen}
onHelpOpen={setHelpOpen}
onToggleFx={toggleFx}
wide={useRecovery}
>
{needsTotp ? (
<>
<LoginBrand subtitle={useRecovery ? '输入保存的一次性恢复码' : '输入 Authenticator 中的 6 位验证码'} />
<form onSubmit={handleTotpSubmit} className="mt-8 flex flex-col gap-3.5">
<OtpInput
key={useRecovery ? 'recovery' : 'totp'}
ref={otpRef}
autoFocus
className="w-full"
length={useRecovery ? 8 : 6}
mode={useRecovery ? 'alphanumeric' : 'numeric'}
groupEvery={useRecovery ? 4 : 3}
groupSeparator={useRecovery}
label={useRecovery ? '恢复码' : '验证码'}
disabled={otpStatus === 'checking'}
error={otpStatus === 'rejected'}
errorMessage={error || (useRecovery
? '恢复码不正确,改错的那一位即可。'
: '验证码不正确,改错的那一位即可。')}
hint={useRecovery
? '可以把完整恢复码粘贴到任意一格,连字符会自动忽略。'
: '可以把完整验证码粘贴到任意一格。'}
onChange={() => setOtpStatus((s) => (s === 'rejected' ? 'idle' : s))}
onComplete={(code) => { void submitTotp(code); }}
/>
<div className="flex items-center justify-between text-[12px]">
<button
type="button"
onClick={goBackToPassword}
className="text-muted-foreground transition-colors hover:text-foreground cursor-pointer"
>
返回
</button>
<button
type="button"
onClick={() => {
setUseRecovery((v) => !v);
setOtpStatus('idle');
setError('');
}}
className="text-muted-foreground transition-colors hover:text-foreground cursor-pointer"
>
{useRecovery ? '改用验证码' : '使用恢复码'}
</button>
</div>
</form>
</>
) : (
<>
<LoginBrand subtitle="OneBot v11 协议网关 · 安全登录" />
<form onSubmit={handlePasswordSubmit} className="mt-8 flex flex-col gap-3.5">
<motion.div
key={shake}
animate={shake > 0 ? { x: [0, -8, 8, -6, 6, -3, 3, 0] } : {}}
transition={{ duration: 0.4 }}
className="relative"
>
<KeyRound className="pointer-events-none absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
type={showPwd ? 'text' : 'password'}
placeholder="输入访问令牌"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoFocus
autoComplete="current-password"
className="h-12 rounded-xl bg-background/40 pl-10 pr-11 text-sm"
/>
<button
type="button"
onClick={() => setShowPwd((v) => !v)}
className="absolute right-2 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground cursor-pointer"
tabIndex={-1}
aria-label={showPwd ? '隐藏密码' : '显示密码'}
>
<PasswordVisibilityIcon visible={showPwd} reduceMotion={reduce} />
</button>
</motion.div>
{error && (
<motion.p
initial={reduce ? false : { opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
className="rounded-lg bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
>
{error}
</motion.p>
)}
<Button type="submit" disabled={loading || !password} className="h-12 rounded-xl text-[15px]">
{loading ? '验证中…' : (
<>
进入控制台 <ArrowRight className="optical-forward size-4" />
</>
)}
</Button>
</form>
</>
)}
</LoginShell>
);
}
function LoginBrand({ subtitle }: { subtitle: string }) {
return (
<div className="flex flex-col items-center gap-3 text-center">
<div className="flex size-14 items-center justify-center rounded-2xl bg-primary/10 shadow-sm ring-1 ring-primary/20">
<img src="/logo.png" alt="SnowLuma" className="size-10 object-contain" />
</div>
<div>
<div className="flex items-center justify-center gap-2">
<span className="text-2xl font-semibold tracking-tight">{APP_NAME}</span>
<span className="rounded-full bg-primary/10 px-1.5 py-0.5 font-mono text-micro text-primary tabular-nums">v{APP_VERSION}</span>
</div>
<p className="mt-1 text-xs text-muted-foreground">{subtitle}</p>
</div>
</div>
);
}
function LoginShell({
customBg,
reduce,
fxOn,
helpOpen,
onHelpOpen,
onToggleFx,
wide = false,
children,
}: {
customBg: boolean;
reduce: boolean;
fxOn: boolean;
helpOpen: boolean;
onHelpOpen: (open: boolean) => void;
onToggleFx: (value: boolean) => void;
wide?: boolean;
children: ReactNode;
}) {
return (
<div className={cn('relative flex min-h-screen items-center justify-center overflow-hidden px-4 py-8', customBg ? 'bg-transparent' : 'bg-background')}>
{/* Animated wavy-line background (device-local toggle) */}
{fxOn && <LoginWaves />}
{/* Soft glow backdrop — also helps the frosted card read against the waves */}
<div
className="pointer-events-none absolute inset-0"
style={{
@@ -90,81 +296,20 @@ export function LoginPage({ onLogin }: LoginPageProps) {
initial={reduce ? false : { opacity: 0, y: 16, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={reduce ? { duration: 0 } : { duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
className="relative z-10 flex w-full max-w-md flex-col items-center"
className={cn('relative z-10 flex w-full flex-col items-center', wide ? 'max-w-2xl' : 'max-w-md')}
>
{/* Frosted "vibrancy" card */}
<Card className="w-full overflow-hidden border-border/50 bg-card/75 shadow-2xl shadow-primary/5 backdrop-blur-2xl supports-[backdrop-filter]:bg-card/65">
<CardContent className="px-7 py-9 sm:px-10">
{/* Centered brand focal point */}
<div className="flex flex-col items-center gap-3 text-center">
<div className="flex size-14 items-center justify-center rounded-2xl bg-primary/10 shadow-sm ring-1 ring-primary/20">
<img src="/logo.png" alt="SnowLuma" className="size-10 object-contain" />
</div>
<div>
<div className="flex items-center justify-center gap-2">
<span className="text-2xl font-semibold tracking-tight">{APP_NAME}</span>
<span className="rounded-full bg-primary/10 px-1.5 py-0.5 font-mono text-micro text-primary tabular-nums">v{APP_VERSION}</span>
</div>
<p className="mt-1 text-xs text-muted-foreground">OneBot v11 协议网关 · 安全登录</p>
</div>
</div>
<form onSubmit={handleSubmit} className="mt-8 flex flex-col gap-3.5">
<motion.div
key={shake}
animate={shake > 0 ? { x: [0, -8, 8, -6, 6, -3, 3, 0] } : {}}
transition={{ duration: 0.4 }}
className="relative"
>
<KeyRound className="pointer-events-none absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
type={showPwd ? 'text' : 'password'}
placeholder="输入访问令牌"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoFocus
className="h-12 rounded-xl bg-background/40 pl-10 pr-11 text-sm"
/>
<button
type="button"
onClick={() => setShowPwd((v) => !v)}
className="absolute right-2 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground cursor-pointer"
tabIndex={-1}
aria-label={showPwd ? '隐藏密码' : '显示密码'}
>
<PasswordVisibilityIcon visible={showPwd} reduceMotion={reduce} />
</button>
</motion.div>
{error && (
<motion.p
initial={reduce ? false : { opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
className="rounded-lg bg-destructive/10 px-3 py-2 text-center text-xs text-destructive"
>
{error}
</motion.p>
)}
<Button type="submit" disabled={loading || !password} className="h-12 rounded-xl text-[15px]">
{loading ? '验证中…' : (
<>
进入控制台 <ArrowRight className="optical-forward size-4" />
</>
)}
</Button>
</form>
{children}
<p className="mt-7 text-center text-meta text-muted-foreground">
© {new Date().getFullYear()} SnowLuma. All rights reserved.
</p>
</CardContent>
</Card>
{/* 灵动岛-style frosted capsule: perf escape hatch for the background */}
<motion.button
type="button"
onClick={() => setHelpOpen(true)}
onClick={() => onHelpOpen(true)}
whileHover={reduce ? undefined : { scale: 1.04 }}
whileTap={reduce ? undefined : { scale: 0.96 }}
transition={{ type: 'spring', stiffness: 420, damping: 26 }}
@@ -177,7 +322,7 @@ export function LoginPage({ onLogin }: LoginPageProps) {
<Modal
open={helpOpen}
onClose={() => setHelpOpen(false)}
onClose={() => onHelpOpen(false)}
title="界面有点卡顿?"
description="登录页背景是一个跟随鼠标的动态线条效果,在部分设备上可能比较吃性能。可以在这里关掉它——该开关仅作用于本设备的登录页,与系统的动效设置相互独立。"
closeLabel="关闭性能设置弹窗"
@@ -189,7 +334,7 @@ export function LoginPage({ onLogin }: LoginPageProps) {
<p className="text-sm font-medium">登录页动态背景</p>
<p className="mt-0.5 text-xs text-muted-foreground">{fxOn ? '已开启 · 关闭后背景为静态' : '已关闭 · 背景为静态'}</p>
</div>
<ToggleSwitch value={fxOn} onChange={toggleFx} ariaLabel="登录页动态背景" />
<ToggleSwitch value={fxOn} onChange={onToggleFx} ariaLabel="登录页动态背景" />
</div>
<p className="text-xs leading-relaxed text-muted-foreground">
@@ -37,6 +37,7 @@ import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useSession } from '@/contexts/SessionContext';
import { NAV_ITEMS } from '@/components/layout/sidebar';
import { TOPBAR_CATALOGUE } from '@/components/layout/top-bar';
import { TotpPanel } from '@/components/settings/totp-panel';
import { ChangePasswordDialog } from '@/components/change-password-dialog';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { SkeletonSwap } from '@/components/interior/skeleton-swap';
@@ -1220,44 +1221,47 @@ function AccountPanel() {
const [confirmLogout, setConfirmLogout] = useState(false);
return (
<Group title="账号安全" icon={ShieldCheck} description="WebUI 仅有 admin 一个账号,密码以 scrypt 哈希持久化到 config/webui.json。">
<SettingRow
label="访问密码"
hint={pwdSavedAt
? <span className="text-success">已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。</span>
: '修改后其他设备的会话将立即失效。'}
>
<Button variant="outline" size="sm" onClick={() => setShowChangePwd(true)}>
<KeyRound className="size-4" /> 修改密码
</Button>
</SettingRow>
<SettingRow label="退出登录" hint="立即清除当前浏览器的会话令牌。">
<Button variant="ghost" size="sm" onClick={() => setConfirmLogout(true)} className="text-destructive hover:text-destructive">
<div className="flex flex-col gap-5">
<Group title="账号安全" icon={ShieldCheck} description="WebUI 仅有 admin 一个账号,密码以 scrypt 哈希持久化到 config/webui.json。">
<SettingRow
label="访问密码"
hint={pwdSavedAt
? <span className="text-success">已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。</span>
: '修改后其他设备的会话将立即失效。'}
>
<Button variant="outline" size="sm" onClick={() => setShowChangePwd(true)}>
<KeyRound className="size-4" /> 修改密码
</Button>
</SettingRow>
<SettingRow label="退出登录" hint="立即清除当前浏览器的会话令牌。">
<Button variant="ghost" size="sm" onClick={() => setConfirmLogout(true)} className="text-destructive hover:text-destructive">
退出登录
</Button>
</SettingRow>
</Button>
</SettingRow>
<ConfirmDialog
open={confirmLogout}
onOpenChange={setConfirmLogout}
title="确认退出登录?"
description="退出后将清除当前会话令牌,需要重新输入访问密码才能进入控制台。"
confirmText="退出登录"
destructive
activity={{
title: '正在退出登录',
successTitle: '已退出登录',
errorTitle: '退出登录失败',
}}
onConfirm={onLogout}
/>
<ConfirmDialog
open={confirmLogout}
onOpenChange={setConfirmLogout}
title="确认退出登录?"
description="退出后将清除当前会话令牌,需要重新输入访问密码才能进入控制台。"
confirmText="退出登录"
destructive
activity={{
title: '正在退出登录',
successTitle: '已退出登录',
errorTitle: '退出登录失败',
}}
onConfirm={onLogout}
/>
<ChangePasswordDialog
open={showChangePwd}
onOpenChange={setShowChangePwd}
onSuccess={() => setPwdSavedAt(Date.now())}
/>
</Group>
<ChangePasswordDialog
open={showChangePwd}
onOpenChange={setShowChangePwd}
onSuccess={() => setPwdSavedAt(Date.now())}
/>
</Group>
<TotpPanel />
</div>
);
}
@@ -0,0 +1,392 @@
import { useCallback, useEffect, useState } from 'react';
import { KeyRound, ShieldCheck } from 'lucide-react';
import { Card, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Modal } from '@/components/interior/modal';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useApi } from '@/lib/api';
import type { TotpEnrollment, TotpStatus } from '@/lib/api/types';
import { parseSecondFactor } from '@/lib/totp-second-factor';
import { TotpQr } from '@/components/settings/totp-qr';
import { TotpRecoveryCodes } from '@/components/settings/totp-recovery-codes';
function SettingRow({
label,
hint,
children,
}: {
label: string;
hint?: string;
children: React.ReactNode;
}) {
return (
<div className="flex flex-col gap-3 px-5 py-4 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
<div className="min-w-0">
<p className="text-sm font-medium">{label}</p>
{hint && <p className="mt-0.5 text-[12px] leading-snug text-muted-foreground">{hint}</p>}
</div>
<div className="sm:shrink-0">{children}</div>
</div>
);
}
export function TotpPanel() {
const api = useApi();
const [status, setStatus] = useState<TotpStatus | 'hidden' | 'loading'>('loading');
const [setupOpen, setSetupOpen] = useState(false);
const [disableOpen, setDisableOpen] = useState(false);
const [regenOpen, setRegenOpen] = useState(false);
const refresh = useCallback(async () => {
try {
setStatus(await api.totp.status());
} catch {
setStatus('hidden');
}
}, [api]);
useEffect(() => { void refresh(); }, [refresh]);
if (status === 'hidden') return null;
return (
<Card className="overflow-hidden">
<CardHeader className="gap-1 pb-4">
<CardTitle className="flex items-center gap-2 text-[15px]">
<ShieldCheck className="size-4 text-primary" />
双重验证
</CardTitle>
<CardDescription className="text-[12px] leading-relaxed">
登录时在访问密码之外再验证 Authenticator 一次性密码。默认关闭。
</CardDescription>
</CardHeader>
<div className="divide-y divide-border/60 border-t border-border/60">
{status === 'loading' ? (
<SettingRow label="2FA" hint="正在读取…">
<span className="text-sm text-muted-foreground">…</span>
</SettingRow>
) : status.enabled ? (
<>
<SettingRow label="状态" hint={`已绑定 ${status.label} · 剩余 ${status.remainingRecoveryCodes} 个恢复码`}>
<span className="text-sm text-success">已开启</span>
</SettingRow>
<SettingRow label="恢复码" hint="重新生成后旧码立即作废。">
<Button variant="outline" size="sm" onClick={() => setRegenOpen(true)}>
重新生成
</Button>
</SettingRow>
<SettingRow label="关闭 2FA" hint="需要当前密码,以及验证码或恢复码。其他设备的会话将失效。">
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" onClick={() => setDisableOpen(true)}>
关闭
</Button>
</SettingRow>
</>
) : (
<SettingRow label="Authenticator" hint="扫描二维码或手动输入密钥,再用 6 位验证码确认。">
<Button variant="outline" size="sm" onClick={() => setSetupOpen(true)}>
<KeyRound className="size-4" /> 开启 2FA
</Button>
</SettingRow>
)}
</div>
<TotpSetupDialog
open={setupOpen}
onOpenChange={setSetupOpen}
onEnabled={async () => { await refresh(); }}
/>
<TotpChallengeDialog
open={disableOpen}
onOpenChange={setDisableOpen}
title="关闭双重验证"
description="关闭后,只需访问密码即可登录。其他已登录会话会立即失效。"
confirmText="关闭 2FA"
destructive
onSubmit={async (password, second) => api.totp.disable(password, second)}
onDone={refresh}
/>
<TotpRegenDialog
open={regenOpen}
onOpenChange={setRegenOpen}
onDone={refresh}
/>
</Card>
);
}
function TotpSetupDialog({
open,
onOpenChange,
onEnabled,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
onEnabled: () => void | Promise<void>;
}) {
const api = useApi();
const [enrollment, setEnrollment] = useState<TotpEnrollment | null>(null);
const [issuer, setIssuer] = useState('');
const [accountName, setAccountName] = useState('');
const [password, setPassword] = useState('');
const [code, setCode] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);
const loadEnrollment = useCallback(async (nextIssuer?: string, nextAccount?: string) => {
const result = await api.totp.begin({
...(nextIssuer ? { issuer: nextIssuer } : {}),
...(nextAccount ? { accountName: nextAccount } : {}),
});
if (!result.success) {
setError(result.message);
return;
}
setEnrollment(result);
setIssuer(result.issuer);
setAccountName(result.accountName);
setError('');
}, [api]);
useEffect(() => {
if (!open) {
setEnrollment(null);
setPassword('');
setCode('');
setError('');
setRecoveryCodes(null);
return;
}
void loadEnrollment();
}, [open, loadEnrollment]);
const refreshLabels = async () => {
if (!enrollment) return;
await loadEnrollment(issuer, accountName);
};
const confirm = async () => {
setBusy(true);
setError('');
await loadEnrollment(issuer, accountName);
const result = await api.totp.confirm(password, code);
setBusy(false);
if (!result.success) {
setError(result.message);
return;
}
setRecoveryCodes(result.recoveryCodes);
await onEnabled();
};
return (
<Modal
open={open}
onClose={() => { if (!recoveryCodes) onOpenChange(false); }}
title={recoveryCodes ? '保存恢复码' : '开启双重验证'}
description={recoveryCodes
? '这些恢复码只显示一次。丢失 Authenticator 时用它们登录。'
: '用 Authenticator 扫描二维码,或手动输入密钥,然后输入当前访问密码和 6 位验证码。'}
closeLabel="关闭 2FA 绑定"
maxWidth={440}
>
{recoveryCodes ? (
<TotpRecoveryCodes codes={recoveryCodes} onConfirm={() => onOpenChange(false)} />
) : (
<div className="flex flex-col gap-4">
{enrollment && (
<div className="flex flex-col items-center gap-3">
<TotpQr value={enrollment.otpauthUrl} label="2FA 绑定二维码" />
<p className="break-all text-center font-mono text-xs text-muted-foreground">{enrollment.secret}</p>
</div>
)}
<div className="grid grid-cols-2 gap-3">
<label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
服务名
<Input value={issuer} onChange={(e) => setIssuer(e.target.value)} onBlur={() => { void refreshLabels(); }} />
</label>
<label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
账号名
<Input value={accountName} onChange={(e) => setAccountName(e.target.value)} onBlur={() => { void refreshLabels(); }} />
</label>
</div>
<Input
type="password"
placeholder="当前访问密码"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
/>
<Input
inputMode="numeric"
autoComplete="one-time-code"
placeholder="6 位验证码"
value={code}
onChange={(e) => setCode(e.target.value)}
/>
{error && <p className="text-xs text-destructive">{error}</p>}
<Button type="button" disabled={busy || !password || !code} onClick={() => { void confirm(); }}>
{busy ? '正在开启…' : '确认开启'}
</Button>
</div>
)}
</Modal>
);
}
function TotpChallengeDialog({
open,
onOpenChange,
title,
description,
confirmText,
destructive,
onSubmit,
onDone,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
description: string;
confirmText: string;
destructive?: boolean;
onSubmit: (password: string, second: { totp?: string; recoveryCode?: string }) => Promise<{ success: boolean; message?: string }>;
onDone: () => void | Promise<void>;
}) {
const [password, setPassword] = useState('');
const [second, setSecond] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
if (!open) {
setPassword('');
setSecond('');
setError('');
}
}, [open]);
const submit = async () => {
setBusy(true);
setError('');
const result = await onSubmit(password, parseSecondFactor(second));
setBusy(false);
if (!result.success) {
setError(result.message ?? '操作失败');
return;
}
await onDone();
onOpenChange(false);
};
return (
<Modal
open={open}
onClose={() => onOpenChange(false)}
title={title}
description={description}
closeLabel={`关闭${title}`}
maxWidth={400}
>
<div className="flex flex-col gap-3">
<Input
type="password"
placeholder="当前访问密码"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
/>
<Input
placeholder="6 位验证码或恢复码"
value={second}
onChange={(e) => setSecond(e.target.value)}
autoComplete="one-time-code"
/>
{error && <p className="text-xs text-destructive">{error}</p>}
<Button
type="button"
variant={destructive ? 'destructive' : 'default'}
disabled={busy || !password || !second.trim()}
onClick={() => { void submit(); }}
>
{busy ? '处理中…' : confirmText}
</Button>
</div>
</Modal>
);
}
function TotpRegenDialog({
open,
onOpenChange,
onDone,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
onDone: () => void | Promise<void>;
}) {
const api = useApi();
const [password, setPassword] = useState('');
const [totp, setTotp] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const [codes, setCodes] = useState<string[] | null>(null);
useEffect(() => {
if (!open) {
setPassword('');
setTotp('');
setError('');
setCodes(null);
}
}, [open]);
const submit = async () => {
setBusy(true);
setError('');
const result = await api.totp.regenerateRecoveryCodes(password, totp.trim());
setBusy(false);
if (!result.success) {
setError(result.message);
return;
}
setCodes(result.recoveryCodes);
await onDone();
};
return (
<Modal
open={open}
onClose={() => { if (!codes) onOpenChange(false); }}
title={codes ? '新的恢复码' : '重新生成恢复码'}
description={codes ? '旧恢复码已作废。请保存下面的新码。' : '需要当前密码和 Authenticator 验证码。旧恢复码会立即作废。'}
closeLabel="关闭恢复码"
maxWidth={440}
>
{codes ? (
<TotpRecoveryCodes codes={codes} onConfirm={() => onOpenChange(false)} />
) : (
<div className="flex flex-col gap-3">
<Input
type="password"
placeholder="当前访问密码"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
/>
<Input
inputMode="numeric"
placeholder="6 位验证码"
value={totp}
onChange={(e) => setTotp(e.target.value)}
autoComplete="one-time-code"
/>
{error && <p className="text-xs text-destructive">{error}</p>}
<Button type="button" disabled={busy || !password || !totp.trim()} onClick={() => { void submit(); }}>
{busy ? '正在生成…' : '生成新恢复码'}
</Button>
</div>
)}
</Modal>
);
}
@@ -0,0 +1,24 @@
import { useMemo } from 'react';
import { encode } from 'uqr';
export function TotpQr({ value, label }: { value: string; label: string }) {
const qr = useMemo(() => encode(value, { ecc: 'M', border: 2 }), [value]);
const modules = qr.data.flatMap((row, y) => (
row.flatMap((on, x) => (
on ? <rect key={`${x}-${y}`} x={x} y={y} width="1" height="1" /> : []
))
));
return (
<svg
role="img"
aria-label={label}
viewBox={`0 0 ${qr.size} ${qr.size}`}
className="size-44 rounded-lg bg-white text-black"
shapeRendering="crispEdges"
>
<rect width={qr.size} height={qr.size} fill="white" />
<g fill="black">{modules}</g>
</svg>
);
}
@@ -0,0 +1,74 @@
import { useState } from 'react';
import { Check, Copy } from 'lucide-react';
import { Button } from '@/components/ui/button';
async function copyText(value: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(value);
return true;
} catch {
try {
const ta = document.createElement('textarea');
ta.value = value;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand('copy');
document.body.removeChild(ta);
return ok;
} catch {
return false;
}
}
}
export function TotpRecoveryCodes({
codes,
onConfirm,
}: {
codes: string[];
onConfirm: () => void;
}) {
const [copied, setCopied] = useState(false);
const [saved, setSaved] = useState(false);
return (
<div className="flex flex-col gap-4">
<p className="text-sm text-muted-foreground">
每个恢复码只能用一次。请立刻抄写或保存到离线位置,关闭后将无法再查看。
</p>
<ol className="grid grid-cols-2 gap-2 font-mono text-sm">
{codes.map((code) => (
<li key={code} className="rounded-md border bg-muted/40 px-3 py-2 text-center tracking-wide">
{code}
</li>
))}
</ol>
<Button
type="button"
variant="outline"
size="sm"
className="self-start"
onClick={async () => {
if (await copyText(codes.join('\n'))) setCopied(true);
}}
>
{copied ? <Check className="size-4" /> : <Copy className="size-4" />}
{copied ? '已复制' : '复制全部'}
</Button>
<label className="flex items-start gap-2 text-sm">
<input
type="checkbox"
checked={saved}
onChange={(e) => setSaved(e.target.checked)}
className="mt-0.5"
/>
我已把恢复码保存到安全的地方
</label>
<Button type="button" disabled={!saved} onClick={onConfirm}>
完成
</Button>
</div>
);
}
+114 -4
View File
@@ -14,6 +14,7 @@ import {
type StateStreamOptions,
type StreamStatus,
type TokenStore,
type TotpStatus,
} from './types';
import { localStorageTokenStore } from './token-store';
@@ -62,6 +63,7 @@ class HttpApiClient implements ApiClient {
readonly storage: ApiClient['storage'];
readonly debug: ApiClient['debug'];
readonly agreements: ApiClient['agreements'];
readonly totp: ApiClient['totp'];
constructor(opts: CreateApiClientOptions = {}) {
this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY);
@@ -312,6 +314,97 @@ class HttpApiClient implements ApiClient {
}
},
};
this.totp = {
status: async () => {
const data = await this.getJson<TotpStatus>('/api/auth/totp');
if (data.enabled === true) {
return {
enabled: true,
remainingRecoveryCodes: data.remainingRecoveryCodes,
label: data.label,
};
}
return { enabled: false };
},
begin: async (options) => {
try {
const res = await this.request('/api/auth/totp/begin', {
method: 'POST',
body: JSON.stringify(options ?? {}),
});
const data = await readJson<{
success?: boolean;
message?: string;
secret?: string;
otpauthUrl?: string;
issuer?: string;
accountName?: string;
}>(res);
if (
res.ok
&& data.success === true
&& typeof data.secret === 'string'
&& typeof data.otpauthUrl === 'string'
&& typeof data.issuer === 'string'
&& typeof data.accountName === 'string'
) {
return {
success: true,
secret: data.secret,
otpauthUrl: data.otpauthUrl,
issuer: data.issuer,
accountName: data.accountName,
};
}
return { success: false, message: data.message ?? '无法开始 2FA 绑定' };
} catch (e) {
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
}
},
confirm: async (password, code) => {
try {
const res = await this.request('/api/auth/totp/confirm', {
method: 'POST',
body: JSON.stringify({ password, code }),
});
const data = await readJson<{ success?: boolean; message?: string; recoveryCodes?: string[] }>(res);
if (res.ok && data.success === true && Array.isArray(data.recoveryCodes)) {
return { success: true, recoveryCodes: data.recoveryCodes };
}
return { success: false, message: data.message ?? '2FA 绑定失败' };
} catch (e) {
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
}
},
disable: async (password, secondFactor) => {
try {
const res = await this.request('/api/auth/totp/disable', {
method: 'POST',
body: JSON.stringify({ password, ...secondFactor }),
});
const data = await readJson<{ success?: boolean; message?: string }>(res);
return { success: res.ok && !!data.success, message: data.message };
} catch (e) {
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
}
},
regenerateRecoveryCodes: async (password, totp) => {
try {
const res = await this.request('/api/auth/totp/recovery-codes', {
method: 'POST',
body: JSON.stringify({ password, totp }),
});
const data = await readJson<{ success?: boolean; message?: string; recoveryCodes?: string[] }>(res);
if (res.ok && data.success === true && Array.isArray(data.recoveryCodes)) {
return { success: true, recoveryCodes: data.recoveryCodes };
}
return { success: false, message: data.message ?? '无法重新生成恢复码' };
} catch (e) {
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
}
},
};
}
// ---------- HTTP helpers ----------
@@ -388,20 +481,37 @@ class HttpApiClient implements ApiClient {
// ---------- auth ----------
async login(password: string): Promise<LoginResult> {
async login(
password: string,
secondFactor?: { totp?: string; recoveryCode?: string },
): Promise<LoginResult> {
// Login deliberately bypasses fetchJson/onUnauthorized so a bad password
// doesn't trigger a global sign-out side effect.
try {
const res = await this.fetchWithDeadline('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
body: JSON.stringify({
password,
...(secondFactor?.totp ? { totp: secondFactor.totp } : {}),
...(secondFactor?.recoveryCode ? { recoveryCode: secondFactor.recoveryCode } : {}),
}),
});
const payload = await readJson<{
token?: string;
mustChangePassword?: boolean;
needsTotp?: boolean;
message?: string;
}>(res);
if (res.ok && payload.needsTotp === true) {
return { ok: false, needsTotp: true };
}
if (!res.ok) {
const payload = await readJson<ErrorPayload>(res);
return { ok: false, message: extractErrorMessage(payload, '令牌错误') };
}
const payload = await readJson<{ token: string; mustChangePassword?: boolean }>(res);
if (typeof payload.token !== 'string' || payload.token.length === 0) {
return { ok: false, message: extractErrorMessage(payload, '令牌错误') };
}
this.setToken(payload.token);
return { ok: true, mustChangePassword: !!payload.mustChangePassword };
} catch (e) {
+28 -1
View File
@@ -43,8 +43,28 @@ export class ApiError extends Error {
export type LoginResult =
| { ok: true; mustChangePassword: boolean }
| { ok: false; needsTotp: true }
| { ok: false; message: string };
export type TotpStatus =
| { enabled: false }
| { enabled: true; remainingRecoveryCodes: number; label: string };
export type TotpEnrollment = {
secret: string;
otpauthUrl: string;
issuer: string;
accountName: string;
};
export type TotpBeginResult =
| { success: true } & TotpEnrollment
| { success: false; message: string };
export type TotpConfirmResult =
| { success: true; recoveryCodes: string[] }
| { success: false; message: string };
export type ChangePasswordResult = { success: boolean; message?: string };
export interface AgreementDoc {
@@ -115,7 +135,7 @@ export interface StateStreamOptions {
export interface ApiClient {
// ---- auth ----
login(password: string): Promise<LoginResult>;
login(password: string, secondFactor?: { totp?: string; recoveryCode?: string }): Promise<LoginResult>;
logout(): Promise<void>;
/** True if the current token is still valid. */
status(): Promise<boolean>;
@@ -123,6 +143,13 @@ export interface ApiClient {
mustChangePassword(): Promise<boolean>;
checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>;
changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult>;
totp: {
status(): Promise<TotpStatus>;
begin(options?: { issuer?: string; accountName?: string }): Promise<TotpBeginResult>;
confirm(password: string, code: string): Promise<TotpConfirmResult>;
disable(password: string, secondFactor: { totp?: string; recoveryCode?: string }): Promise<{ success: boolean; message?: string }>;
regenerateRecoveryCodes(password: string, totp: string): Promise<TotpConfirmResult>;
};
// ---- EULA / PRIVACY consent (shown after login, before set-password) ----
agreements: {
@@ -0,0 +1,6 @@
export function parseSecondFactor(value: string): { totp: string } | { recoveryCode: string } {
const trimmed = value.trim();
const digits = trimmed.replace(/\s/g, '');
if (/^\d{6}$/.test(digits)) return { totp: digits };
return { recoveryCode: trimmed };
}
@@ -0,0 +1,51 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
const tokenStore = {
load: () => null as string | null,
save: vi.fn(),
};
afterEach(() => {
vi.unstubAllGlobals();
tokenStore.save.mockReset();
});
describe('login 2FA client', () => {
it('returns needsTotp without storing a session token', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
success: false,
needsTotp: true,
}), {
status: 200,
headers: { 'content-type': 'application/json' },
})));
const client = createApiClient({ tokenStore });
await expect(client.login('Correct-Horse-1!')).resolves.toEqual({ ok: false, needsTotp: true });
expect(tokenStore.save).not.toHaveBeenCalled();
});
it('sends the TOTP on the second login request and stores the session', async () => {
const fetchMock = vi.fn(async () => new Response(JSON.stringify({
success: true,
token: 'session-token',
mustChangePassword: false,
}), {
status: 200,
headers: { 'content-type': 'application/json' },
}));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await expect(client.login('Correct-Horse-1!', { totp: '287082' })).resolves.toEqual({
ok: true,
mustChangePassword: false,
});
expect(fetchMock).toHaveBeenCalledWith('/api/login', expect.objectContaining({
method: 'POST',
body: JSON.stringify({ password: 'Correct-Horse-1!', totp: '287082' }),
}));
expect(tokenStore.save).toHaveBeenCalledWith('session-token');
});
});
+72
View File
@@ -0,0 +1,72 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it, vi } from 'vitest';
import { LoginPage } from '../src/components/pages/login-page';
vi.mock('@/contexts/ThemeContext', () => ({
useTheme: () => ({
appearance: {
background: { type: 'none' },
reduceMotion: true,
disableMotion: true,
palette: 'default',
},
mode: 'light',
setMode: () => undefined,
}),
paletteResolved: () => false,
}));
describe('LoginPage 2FA step', () => {
it('keeps the password form on its own screen', () => {
const markup = renderToStaticMarkup(
<LoginPage onLogin={async () => ({ success: false, error: 'no' })} />,
);
expect(markup).toContain('输入访问令牌');
expect(markup).toContain('进入控制台');
expect(markup).toContain('max-w-md');
expect(markup).not.toContain('max-w-2xl');
expect(markup).not.toContain('character 1 of 6');
expect(markup).not.toContain('验证并进入');
});
it('shows a separate TOTP screen after the password factor succeeds', () => {
const markup = renderToStaticMarkup(
<LoginPage
initialPassword="Correct-Horse-1!"
initialNeedsTotp
onLogin={async () => ({ success: false, needsTotp: true })}
/>,
);
expect(markup).not.toContain('输入访问令牌');
expect(markup).toContain('输入 Authenticator 中的 6 位验证码');
expect(markup).not.toContain('验证并进入');
expect(markup).toContain('character 1 of 6');
expect(markup).toContain('可以把完整验证码粘贴到任意一格。');
expect(markup).toContain('使用恢复码');
expect(markup).toContain('返回');
expect(markup).toContain('max-w-md');
expect(markup).not.toContain('max-w-2xl');
expect(markup).not.toContain('h-[2px] w-3 rounded-full');
});
it('uses the same cell UI for a recovery code instead of a single field', () => {
const markup = renderToStaticMarkup(
<LoginPage
initialPassword="Correct-Horse-1!"
initialNeedsTotp
initialUseRecovery
onLogin={async () => ({ success: false, needsTotp: true })}
/>,
);
expect(markup).toContain('输入保存的一次性恢复码');
expect(markup).toContain('character 1 of 8');
expect(markup).toContain('character 8 of 8');
expect(markup).toContain('可以把完整恢复码粘贴到任意一格');
expect(markup).toContain('改用验证码');
expect(markup).toContain('max-w-2xl');
expect(markup).toContain('h-[2px] w-3 rounded-full');
expect(markup).not.toContain('XXXX-XXXX');
expect(markup).not.toContain('验证并进入');
expect(markup).not.toContain('输入访问令牌');
});
});
+31
View File
@@ -0,0 +1,31 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { OtpInput } from '../src/components/interior/otp-input';
describe('OtpInput official error/hint contract', () => {
it('shows the hint while error is false', () => {
const markup = renderToStaticMarkup(
<OtpInput
label="验证码"
hint="可以把完整验证码粘贴到任意一格。"
error={false}
errorMessage="验证码不正确,改错的那一位即可。"
/>,
);
expect(markup).toContain('可以把完整验证码粘贴到任意一格。');
expect(markup).not.toContain('验证码不正确,改错的那一位即可。');
});
it('swaps to the error message when error is true', () => {
const markup = renderToStaticMarkup(
<OtpInput
label="验证码"
hint="可以把完整验证码粘贴到任意一格。"
error
errorMessage="验证码不正确,改错的那一位即可。"
/>,
);
expect(markup).toContain('验证码不正确,改错的那一位即可。');
expect(markup).toContain('aria-invalid="true"');
});
});
@@ -0,0 +1,12 @@
import { describe, expect, it } from 'vitest';
import { parseSecondFactor } from '../src/lib/totp-second-factor';
describe('parseSecondFactor', () => {
it('treats a 6-digit code as TOTP, ignoring spaces', () => {
expect(parseSecondFactor('287 082')).toEqual({ totp: '287082' });
});
it('treats a recovery code as a recovery code', () => {
expect(parseSecondFactor('AB3D-K7MQ')).toEqual({ recoveryCode: 'AB3D-K7MQ' });
});
});
+24
View File
@@ -122,6 +122,9 @@ importers:
'@snowluma/websocket':
specifier: workspace:*
version: link:../websocket
otpauth:
specifier: ^9.5.1
version: 9.5.1
devDependencies:
'@hono/node-server':
specifier: ^1.19.14
@@ -428,6 +431,9 @@ importers:
tw-animate-css:
specifier: ^1.2.5
version: 1.4.0
uqr:
specifier: ^0.1.3
version: 0.1.3
devDependencies:
'@eslint/js':
specifier: ^10.0.1
@@ -853,6 +859,10 @@ packages:
'@emnapi/core': ^1.7.1
'@emnapi/runtime': ^1.7.1
'@noble/[email protected]':
resolution: {integrity: sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==}
engines: {node: '>= 20.19.0'}
'@oxc-project/[email protected]':
resolution: {integrity: sha512-WT+Gb24i8hmvo85AIv2oEYouEXkRlKAlT9WaCa3TfLgNCN+GhrJOGZuIlMouAh38Qe4QOx26eUOVsq70qXrywA==}
@@ -2867,6 +2877,9 @@ packages:
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
engines: {node: '>= 0.8.0'}
[email protected]:
resolution: {integrity: sha512-fJmDAHc8wImfqqqOXIlBvT1dEKrZK0Cmb2VEgScpNTolCz0PHh6ExUZGv4sLtOsWNaHCQlD+rRqaPgnoxFoZjQ==}
[email protected]:
resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}
engines: {node: '>=10'}
@@ -3264,6 +3277,9 @@ packages:
peerDependencies:
browserslist: '>= 4.21.0'
[email protected]:
resolution: {integrity: sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==}
[email protected]:
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
@@ -3759,6 +3775,8 @@ snapshots:
'@tybys/wasm-util': 0.10.3
optional: true
'@noble/[email protected]': {}
'@oxc-project/[email protected]': {}
'@parcel/[email protected]':
@@ -5595,6 +5613,10 @@ snapshots:
type-check: 0.4.0
word-wrap: 1.2.5
[email protected]:
dependencies:
'@noble/hashes': 2.2.0
[email protected]:
dependencies:
yocto-queue: 0.1.0
@@ -6011,6 +6033,8 @@ snapshots:
escalade: 3.2.0
picocolors: 1.1.1
[email protected]: {}
[email protected]:
dependencies:
punycode: 2.3.1