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

+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);
}
}