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:
23 files changed
+2676
-153
No files matched your search
+47
-19
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
Reference in new issue
Block a user