diff --git a/packages/core/package.json b/packages/core/package.json index b6e2c4de..c97662c8 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -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", diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index 3dcd2bba..ad1fa4fc 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -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; + 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; + } } diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 58611be3..56af0ec5 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -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(); const loginAttempts = new Map(); +const totpEnrollments = new Map(); 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 = {}; + try { + const parsed = await c.req.json(); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + body = parsed as Record; + } + } 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. diff --git a/packages/core/src/webui/totp.ts b/packages/core/src/webui/totp.ts new file mode 100644 index 00000000..82cce090 --- /dev/null +++ b/packages/core/src/webui/totp.ts @@ -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(); + 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): value is WrappedTotpSecret & Record { + 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; + 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; + } +} diff --git a/packages/core/src/webui/webui-login.ts b/packages/core/src/webui/webui-login.ts new file mode 100644 index 00000000..81efb6e2 --- /dev/null +++ b/packages/core/src/webui/webui-login.ts @@ -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; + 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(sessions: Map, keepToken: string): void { + for (const token of sessions.keys()) { + if (token !== keepToken) sessions.delete(token); + } +} diff --git a/packages/core/tests/webui-login.test.ts b/packages/core/tests/webui-login.test.ts new file mode 100644 index 00000000..87b3610a --- /dev/null +++ b/packages/core/tests/webui-login.test.ts @@ -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']); + }); +}); diff --git a/packages/core/tests/webui-totp.test.ts b/packages/core/tests/webui-totp.test.ts new file mode 100644 index 00000000..84c89d1c --- /dev/null +++ b/packages/core/tests/webui-totp.test.ts @@ -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); + }); +}); diff --git a/packages/webui/package.json b/packages/webui/package.json index 1db336a9..49e1db45 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -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", diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index d5d4f207..ecbd4cea 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -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(undefined); + const [urlLoginPassword, setUrlLoginPassword] = useState(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 = ( { 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 ( + ); - return ; } function OnboardingGate({ diff --git a/packages/webui/src/components/interior/otp-input.tsx b/packages/webui/src/components/interior/otp-input.tsx new file mode 100644 index 00000000..abffcc13 --- /dev/null +++ b/packages/webui/src/components/interior/otp-input.tsx @@ -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 = { + 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) => void; + onKeyDown: (e: KeyboardEvent) => void; + onPaste: (e: ClipboardEvent) => void; + onFocus: (e: FocusEvent) => void; + onBlur: (e: FocusEvent) => 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(() => { + 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; +}; + +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 ( +
+ + {Array.from({ length }, (_, i) => { + const char = chars[i] ?? ""; + const active = focusedIndex === i; + const gap = groupEvery > 0 && i > 0 && i % groupEvery === 0; + + return ( +
+ {gap && groupSeparator ? ( + + + + ) : null} +
+ + + + + {char ? ( + + {char} + + ) : null} + + + {active && !char && !disabled ? ( + + ) : null} + +
+
+ ); + })} +
+ + {hasStatus && ( + <> +
+ + + {message} + + +
+ + {message} + + + )} +
+ ); +} diff --git a/packages/webui/src/components/pages/login-page.tsx b/packages/webui/src/components/pages/login-page.tsx index c1007148..444264d3 100644 --- a/packages/webui/src/components/pages/login-page.tsx +++ b/packages/webui/src/components/pages/login-page.tsx @@ -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