diff --git a/packages/webui/README.md b/packages/webui/README.md index 51202e5e..901af770 100644 --- a/packages/webui/README.md +++ b/packages/webui/README.md @@ -13,6 +13,9 @@ status, OneBot configuration, logs, storage, and server settings. intermediate edit. - Failures must remain visible in the affected control and in the operation result; do not convert failed responses into successful feedback. +- Password change flows use floating labels and inline validation consistently. +- Password strength details appear only while the new-password field has focus + and leave with the same motion language when focus moves away. ## Local development diff --git a/packages/webui/src/components/interior/floating-label.tsx b/packages/webui/src/components/interior/floating-label.tsx new file mode 100644 index 00000000..e952edda --- /dev/null +++ b/packages/webui/src/components/interior/floating-label.tsx @@ -0,0 +1,303 @@ +"use client"; + +import { + useCallback, + useEffect, + useId, + useImperativeHandle, + useLayoutEffect, + useRef, + useState, +} from "react"; +import { motion, useReducedMotion } from "motion/react"; + +const INSTANT = { duration: 0 } as const; + +const LIFT = { type: "spring", stiffness: 760, damping: 46, mass: 0.5 } as const; + +const RAISE = -32; +const SLIDE = -12; +const SHRINK = 0.92; + +const useIsomorphicLayoutEffect = + typeof window === "undefined" ? useEffect : useLayoutEffect; + +export type UseFloatingLabelOptions = { + value?: string; + defaultValue?: string; + disabled?: boolean; +}; + +export type UseFloatingLabelReturn = { + ref: React.RefObject; + raised: boolean; + focused: boolean; + filled: boolean; + length: number; + instant: boolean; + fieldProps: { + onFocus: () => void; + onBlur: () => void; + onChange: (event: React.ChangeEvent) => void; + }; +}; + +type Fill = { length: number; instant: boolean }; + +export function useFloatingLabel({ + value, + defaultValue, + disabled = false, +}: UseFloatingLabelOptions = {}): UseFloatingLabelReturn { + const ref = useRef(null); + const mounted = useRef(false); + + const [focused, setFocused] = useState(false); + const [fill, setFill] = useState({ + length: (value ?? defaultValue ?? "").length, + instant: true, + }); + + const settle = useCallback((next: number, instant: boolean) => { + setFill((prev) => + prev.length === next && prev.instant === instant ? prev : { length: next, instant }, + ); + }, []); + + useIsomorphicLayoutEffect(() => { + const el = ref.current; + const next = value !== undefined ? value.length : el ? el.value.length : 0; + settle(next, !mounted.current); + mounted.current = true; + }, [value, settle]); + + useEffect(() => { + setFill((prev) => (prev.instant ? { ...prev, instant: false } : prev)); + }, []); + + useEffect(() => { + const el = ref.current; + if (!el || value !== undefined) return; + const read = () => settle(el.value.length, false); + el.addEventListener("input", read); + el.addEventListener("change", read); + return () => { + el.removeEventListener("input", read); + el.removeEventListener("change", read); + }; + }, [value, settle]); + + useEffect(() => { + if (disabled) setFocused(false); + }, [disabled]); + + const onFocus = useCallback(() => setFocused(true), []); + const onBlur = useCallback(() => setFocused(false), []); + const onChange = useCallback( + (event: React.ChangeEvent) => + settle(event.currentTarget.value.length, false), + [settle], + ); + + return { + ref, + raised: focused || fill.length > 0, + focused, + filled: fill.length > 0, + length: fill.length, + instant: fill.instant && !focused, + fieldProps: { onFocus, onBlur, onChange }, + }; +} + +export type FloatingLabelInputProps = { + label: string; + value?: string; + defaultValue?: string; + onChange?: (value: string, event: React.ChangeEvent) => void; + onFocus?: () => void; + onBlur?: () => void; + hint?: string; + invalid?: boolean; + id?: string; + name?: string; + type?: "text" | "email" | "password" | "search" | "tel" | "url"; + autoComplete?: string; + inputMode?: React.ComponentProps<"input">["inputMode"]; + maxLength?: number; + required?: boolean; + disabled?: boolean; + readOnly?: boolean; + spellCheck?: boolean; + inputRef?: React.Ref; + endAdornment?: React.ReactNode; + ariaDescribedBy?: string; + reserveHintSpace?: boolean; + className?: string; +}; + +export function FloatingLabelInput({ + label, + value, + defaultValue, + onChange, + onFocus, + onBlur, + hint, + invalid = false, + id, + name, + type = "text", + autoComplete, + inputMode, + maxLength, + required = false, + disabled = false, + readOnly = false, + spellCheck, + inputRef, + endAdornment, + ariaDescribedBy, + reserveHintSpace = true, + className = "", +}: FloatingLabelInputProps) { + const auto = useId(); + const fieldId = id ?? `${auto}-field`; + const hintId = `${auto}-hint`; + + const reduced = useReducedMotion(); + const { ref, raised, focused, length, instant, fieldProps } = useFloatingLabel({ + value, + defaultValue, + disabled, + }); + + const move = reduced || instant ? INSTANT : LIFT; + + useImperativeHandle(inputRef, () => ref.current as HTMLInputElement, [ref]); + + const attach = useCallback( + (node: HTMLInputElement | null) => { + ref.current = node; + }, + [ref], + ); + + const describedBy = [ariaDescribedBy, hint ? hintId : null] + .filter(Boolean) + .join(" "); + + return ( +
+
+
+ { + fieldProps.onFocus(); + onFocus?.(); + }} + onBlur={() => { + fieldProps.onBlur(); + onBlur?.(); + }} + onChange={(event) => { + fieldProps.onChange(event); + onChange?.(event.currentTarget.value, event); + }} + className={`absolute inset-0 h-full w-full rounded-[9px] bg-transparent px-3 py-0 text-[13px] leading-[20px] text-foreground outline-none focus-visible:outline-none disabled:cursor-not-allowed ${ + endAdornment ? "pr-16" : "" + }`} + /> + {endAdornment ? ( +
+ {endAdornment} +
+ ) : null} +
+ + + {label} + {required ? ( + + * + + ) : null} + +
+ + {reserveHintSpace || hint || maxLength !== undefined ? ( +
+

+ {hint} +

+ + {maxLength !== undefined ? ( + + + {maxLength} / {maxLength} + + + {length} / {maxLength} + + + ) : null} + + {hint ? ( + + {hint} + + ) : null} +
+ ) : null} +
+ ); +} diff --git a/packages/webui/src/components/interior/inline-validation.tsx b/packages/webui/src/components/interior/inline-validation.tsx new file mode 100644 index 00000000..b0a2339e --- /dev/null +++ b/packages/webui/src/components/interior/inline-validation.tsx @@ -0,0 +1,309 @@ +"use client"; + +import { useCallback, useEffect, useId, useRef, useState } from "react"; +import { motion, useReducedMotion } from "motion/react"; +import { FloatingLabelInput } from "@/components/interior/floating-label"; + +const CROSSFADE = { type: "spring", stiffness: 260, damping: 34, mass: 0.8 } as const; +const INSTANT = { duration: 0 } as const; + +const LINE = 16; + +export type ValidationStatus = "idle" | "pending" | "valid" | "invalid"; + +export type Validator = (value: string) => string | null; + +export type UseInlineValidationOptions = { + value: string; + validate: Validator; + debounce?: number; + validationKey?: unknown; +}; + +export type UseInlineValidationReturn = { + status: ValidationStatus; + error: string | null; + message: string; + touched: boolean; + commit: () => void; + reset: () => void; + fieldProps: { + onBlur: () => void; + "aria-invalid": boolean; + }; +}; + +type Settled = { + status: ValidationStatus; + error: string | null; + message: string; +}; + +const CLEAN: Settled = { status: "idle", error: null, message: "" }; + +export function useInlineValidation({ + value, + validate, + debounce = 400, + validationKey, +}: UseInlineValidationOptions): UseInlineValidationReturn { + const [touched, setTouched] = useState(false); + const [settled, setSettled] = useState(CLEAN); + + const check = useRef(validate); + const latest = useRef(value); + + useEffect(() => { + check.current = validate; + latest.current = value; + }); + + useEffect(() => { + if (!touched) return; + + const next = check.current(value); + const resolved: ValidationStatus = value.length > 0 ? "valid" : "idle"; + + if (next === null) { + setSettled((prev) => + prev.status === resolved && prev.error === null + ? prev + : { status: resolved, error: null, message: prev.message }, + ); + return; + } + + setSettled((prev) => + prev.status === "invalid" + ? prev + : { status: "pending", error: null, message: prev.message }, + ); + + const t = setTimeout(() => { + setSettled((prev) => + prev.error === next ? prev : { status: "invalid", error: next, message: next }, + ); + }, debounce); + + return () => clearTimeout(t); + }, [value, touched, debounce, validationKey]); + + const commit = useCallback(() => { + setTouched(true); + const v = latest.current; + const next = check.current(v); + setSettled((prev) => + next === null + ? { status: v.length > 0 ? "valid" : "idle", error: null, message: prev.message } + : { status: "invalid", error: next, message: next }, + ); + }, []); + + const reset = useCallback(() => { + setTouched(false); + setSettled(CLEAN); + }, []); + + return { + status: settled.status, + error: settled.error, + message: settled.message, + touched, + commit, + reset, + fieldProps: { onBlur: commit, "aria-invalid": settled.status === "invalid" }, + }; +} + +export type InlineValidationProps = { + label: string; + value: string; + onChange: (value: string) => void; + validate: Validator; + hint?: string; + id?: string; + name?: string; + type?: "text" | "email" | "password" | "tel" | "url" | "search"; + autoComplete?: string; + inputMode?: React.ComponentProps<"input">["inputMode"]; + debounce?: number; + validationKey?: unknown; + reserveLines?: number; + disabled?: boolean; + required?: boolean; + spellCheck?: boolean; + endAdornment?: React.ReactNode; + showValidIcon?: boolean; + onFocus?: () => void; + onBlur?: () => void; + className?: string; +}; + +export function InlineValidation({ + label, + value, + onChange, + validate, + hint, + id, + name, + type = "text", + autoComplete, + inputMode, + debounce = 400, + validationKey, + reserveLines = 1, + disabled = false, + required = false, + spellCheck, + endAdornment, + showValidIcon = true, + onFocus, + onBlur, + className = "", +}: InlineValidationProps) { + const reduced = useReducedMotion(); + const fade = reduced ? INSTANT : CROSSFADE; + + const auto = useId(); + const fieldId = id ?? `${auto}-field`; + const hintId = `${auto}-hint`; + const errorId = `${auto}-error`; + + const { status, error, message, fieldProps } = useInlineValidation({ + value, + validate, + debounce, + validationKey, + }); + + const invalid = status === "invalid"; + const valid = status === "valid"; + + const described = [hint ? hintId : null, invalid ? errorId : null] + .filter(Boolean) + .join(" "); + + const clamp = { + display: "-webkit-box" as const, + WebkitBoxOrient: "vertical" as const, + WebkitLineClamp: reserveLines, + overflow: "hidden" as const, + }; + + const statusGlyph = ( + + + + + + + + + + ); + + return ( +
+ { + fieldProps.onBlur(); + onBlur?.(); + }} + onChange={onChange} + endAdornment={( +
+ {statusGlyph} + {endAdornment} +
+ )} + /> + +
+ {hint ? ( + + {hint} + + ) : null} + + + {error ?? message} + + + {hint ? ( + + {hint} + + ) : null} + + + {error ?? ""} + +
+
+ ); +} diff --git a/packages/webui/src/components/interior/password-strength.tsx b/packages/webui/src/components/interior/password-strength.tsx new file mode 100644 index 00000000..99653949 --- /dev/null +++ b/packages/webui/src/components/interior/password-strength.tsx @@ -0,0 +1,269 @@ +"use client"; + +import { useEffect, useMemo, useState } from "react"; +import { AnimatePresence, motion, useReducedMotion } from "motion/react"; + +const CELL = { type: "spring", stiffness: 520, damping: 34, mass: 0.45 } as const; +const CROSSFADE = { type: "spring", stiffness: 260, damping: 34, mass: 0.8 } as const; +const INSTANT = { duration: 0 } as const; + +const COMMON = /^(?:password|passw0rd|qwerty|letmein|welcome|admin|iloveyou|monkey|dragon|abc123|111111|123123|123456)/i; +const RUN = /(.)\1{3,}/; +const RUN_UP = /(?:0123|1234|2345|3456|4567|5678|6789|abcd|bcde|cdef|defg|qwer|wert|erty|asdf)/i; +const SYMBOL = /[!-/:-@[-`{-~]/; + +export type PasswordRule = { + id: string; + label: string; + test: (value: string) => boolean; +}; + +export type EvaluatedRule = PasswordRule & { met: boolean }; + +export type UsePasswordStrengthOptions = { + rules?: readonly PasswordRule[]; + labels?: readonly string[]; + announceDelay?: number; +}; + +export type PasswordStrengthState = { + score: number; + max: number; + label: string; + rules: EvaluatedRule[]; + guessable: boolean; + announcement: string; +}; + +export const defaultPasswordRules: readonly PasswordRule[] = [ + { id: "length", label: "至少 12 个字符", test: (v) => v.length >= 12 }, + { + id: "case", + label: "同时包含大写和小写字母", + test: (v) => /[a-z]/.test(v) && /[A-Z]/.test(v), + }, + { id: "digit", label: "包含数字", test: (v) => /\d/.test(v) }, + { id: "symbol", label: "包含特殊符号", test: (v) => SYMBOL.test(v) }, +]; + +const defaultLabels = ["未输入", "弱", "一般", "良好", "强"] as const; + +export function usePasswordStrength( + value: string, + { + rules = defaultPasswordRules, + labels = defaultLabels, + announceDelay = 700, + }: UsePasswordStrengthOptions = {}, +): PasswordStrengthState { + const state = useMemo(() => { + const evaluated = rules.map((rule) => ({ ...rule, met: rule.test(value) })); + const passed = evaluated.reduce((n, r) => n + (r.met ? 1 : 0), 0); + const guessable = + value.length > 0 && (COMMON.test(value) || RUN.test(value) || RUN_UP.test(value)); + + const score = + value.length === 0 ? 0 : guessable ? 1 : Math.min(rules.length, Math.max(1, passed)); + + const label = labels[Math.min(score, labels.length - 1)] ?? ""; + const unmet = evaluated.filter((r) => !r.met); + + const announcement = + value.length === 0 + ? "" + : [ + `密码强度${label}。`, + guessable ? "这是容易被猜中的常见模式。" : "", + unmet.length === 0 + ? "已满足全部要求。" + : `仍需满足:${unmet.map((r) => r.label).join("、")}。`, + ] + .filter(Boolean) + .join(" "); + + return { score, max: rules.length, label, rules: evaluated, guessable, announcement }; + }, [value, rules, labels]); + + const [settled, setSettled] = useState(""); + + useEffect(() => { + if (state.announcement === "") { + setSettled(""); + return; + } + const id = setTimeout(() => setSettled(state.announcement), announceDelay); + return () => clearTimeout(id); + }, [state.announcement, announceDelay]); + + return { ...state, announcement: settled }; +} + +export type PasswordStrengthProps = { + value: string; + rules?: readonly PasswordRule[]; + labels?: readonly string[]; + announceDelay?: number; + showRules?: boolean; + visible?: boolean; + status?: React.ReactNode; + className?: string; +}; + +const TONES = { + none: { bar: "bg-muted-foreground/30", text: "text-muted-foreground" }, + danger: { bar: "bg-destructive", text: "text-destructive" }, + caution: { bar: "bg-warning", text: "text-warning" }, + safe: { bar: "bg-success", text: "text-success" }, +} as const; + +function toneFor(score: number, max: number) { + if (score === 0) return TONES.none; + const ratio = score / max; + if (ratio <= 0.34) return TONES.danger; + if (ratio <= 0.67) return TONES.caution; + return TONES.safe; +} + +export function PasswordStrength({ + value, + rules = defaultPasswordRules, + labels = defaultLabels, + announceDelay = 700, + showRules = true, + visible = true, + status, + className = "", +}: PasswordStrengthProps) { + const { + score, + max, + label, + rules: evaluated, + guessable, + announcement, + } = usePasswordStrength(value, { rules, labels, announceDelay }); + const reduced = useReducedMotion(); + const tone = toneFor(score, max); + + return ( + + {visible ? ( + +
+ {Array.from({ length: max }, (_, i) => ( +
+ +
+ ))} +
+ +
+ + {labels.map((text, i) => ( + + {text} + + ))} + + + + 容易被猜中 + +
+ + {showRules && ( +
    + {evaluated.map((rule) => ( +
  • + + + + + + + + {rule.label} + + {rule.met ? "已满足" : "未满足"} +
  • + ))} +
+ )} + + {status ? ( +
+ {status} +
+ ) : null} + +

+ {announcement} +

+
+ ) : null} +
+ ); +} diff --git a/packages/webui/src/components/pages/change-password-form.tsx b/packages/webui/src/components/pages/change-password-form.tsx index 58f0035f..0052e57d 100644 --- a/packages/webui/src/components/pages/change-password-form.tsx +++ b/packages/webui/src/components/pages/change-password-form.tsx @@ -1,12 +1,15 @@ import { useEffect, useMemo, useState } from 'react'; -import { motion, AnimatePresence } from 'motion/react'; -import { Check, Loader2 } from 'lucide-react'; +import { AnimatePresence, motion } from 'motion/react'; +import { Loader2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; +import { InlineValidation } from '@/components/interior/inline-validation'; +import { + PasswordStrength, + type PasswordRule as InteriorPasswordRule, +} from '@/components/interior/password-strength'; import { PasswordVisibilityIcon } from '@/components/ui/password-visibility-icon'; +import { actionErrorMessage, useActionFeedback } from '@/contexts/ActionFeedbackContext'; import { useTheme } from '@/contexts/ThemeContext'; -import { cn } from '@/lib/utils'; export interface PasswordRule { id: string; @@ -14,6 +17,16 @@ export interface PasswordRule { ok: boolean; } +const EMPTY_RULES: readonly PasswordRule[] = [ + { id: 'length', label: '长度不少于 10 位', ok: false }, + { id: 'lower', label: '包含小写字母', ok: false }, + { id: 'upper', label: '包含大写字母', ok: false }, + { id: 'special', label: '包含特殊符号 (!@#$%…)', ok: false }, + { id: 'no-space', label: '不包含空格', ok: false }, +]; + +const STRENGTH_LABELS = ['未输入', '很弱', '较弱', '一般', '良好', '强'] as const; + export interface ChangePasswordFormProps { /** * When provided, the "current password" field is omitted entirely and this @@ -50,6 +63,7 @@ export function ChangePasswordForm({ submitLabel = '保存新密码', }: ChangePasswordFormProps) { const carriesOld = knownOldPassword !== undefined; + const { runAction } = useActionFeedback(); const { appearance } = useTheme(); const reduceMotion = appearance.reduceMotion || appearance.disableMotion; @@ -58,27 +72,63 @@ export function ChangePasswordForm({ const [confirmPassword, setConfirmPassword] = useState(''); const [showOld, setShowOld] = useState(false); const [showNew, setShowNew] = useState(false); - const [rules, setRules] = useState([]); - const [valid, setValid] = useState(false); + const [newPasswordFocused, setNewPasswordFocused] = useState(false); + const [strengthResult, setStrengthResult] = useState<{ + password: string; + rules: PasswordRule[]; + valid: boolean; + }>({ password: '', rules: [], valid: false }); + const [strengthFailure, setStrengthFailure] = useState<{ + password: string; + message: string; + } | null>(null); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(''); const effectiveOld = carriesOld ? (knownOldPassword as string) : oldPassword; + const checkedCurrentPassword = strengthResult.password === newPassword; + const valid = checkedCurrentPassword && strengthResult.valid; + const strengthError = strengthFailure?.password === newPassword + ? strengthFailure.message + : ''; + const checkingStrength = + newPassword.length > 0 && !checkedCurrentPassword && strengthError.length === 0; + const displayedRules = checkedCurrentPassword && strengthResult.rules.length > 0 + ? strengthResult.rules + : EMPTY_RULES; + const strengthRules = useMemo( + () => displayedRules.map((rule) => ({ + id: rule.id, + label: rule.label, + test: () => rule.ok, + })), + [displayedRules], + ); const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword; const canSubmit = !submitting && effectiveOld.length > 0 && valid && confirmMatches && effectiveOld !== newPassword; // Debounce the strength check so we don't slam the API on every keystroke. useEffect(() => { + if (newPassword.length === 0) { + setStrengthFailure(null); + return; + } let cancelled = false; const handle = window.setTimeout(async () => { try { const res = await checkStrength(newPassword); if (cancelled) return; - setRules(res.rules); - setValid(res.valid); - } catch { - /* ignore – the form will just stay disabled */ + if (res.rules.length === 0) { + throw new Error('服务器未返回密码强度规则'); + } + setStrengthResult({ password: newPassword, rules: res.rules, valid: res.valid }); + setStrengthFailure(null); + } catch (caught) { + if (cancelled) return; + const message = actionErrorMessage(caught); + console.error('check password strength failed', caught); + setStrengthFailure({ password: newPassword, message }); } }, 180); return () => { @@ -93,7 +143,17 @@ export function ChangePasswordForm({ setSubmitting(true); setError(''); try { - const res = await submit(effectiveOld, newPassword); + const res = await runAction( + { + title: '正在更新访问密码', + detail: '正在保存新密码并使其他会话失效', + successTitle: '访问密码已更新', + successDetail: '其他会话已失效', + errorTitle: '访问密码更新失败', + resultError: (result) => result.success ? null : result.message || '修改失败', + }, + () => submit(effectiveOld, newPassword), + ); if (res.success) { onSuccess(); } else { @@ -107,74 +167,102 @@ export function ChangePasswordForm({ }; return ( -
+ {!carriesOld && ( -
- -
- setOldPassword(e.target.value)} - placeholder="输入当前访问密码" - className="h-10 pr-10 text-sm" + value.length > 0 ? null : '请输入当前密码'} + hint="用于确认当前管理员身份" + showValidIcon={false} + endAdornment={( + setShowOld((current) => !current)} /> - -
-
+ )} + /> )} -
- -
- + setNewPasswordFocused(true)} + onBlur={() => setNewPasswordFocused(false)} + validationKey={effectiveOld} + validate={(value) => { + if (value.length === 0) return '请输入新密码'; + if (value === effectiveOld) return '新密码不能与当前密码相同'; + return null; + }} + showValidIcon={false} + endAdornment={( + setShowNew((current) => !current)} + /> + )} + /> + +
+ setNewPassword(e.target.value)} - placeholder="设置新的强密码" - className="h-10 pr-10 text-sm" + rules={strengthRules} + labels={STRENGTH_LABELS} + visible={newPasswordFocused} + className="mt-1" + status={ + checkingStrength ? ( + 正在校验密码强度… + ) : strengthError ? ( + + 密码强度校验失败:{strengthError} + + ) : null + } /> -
-
- - setConfirmPassword(e.target.value)} - placeholder="再次输入新密码" - className="h-10 text-sm" - /> - {confirmPassword.length > 0 && !confirmMatches && ( - 两次输入的密码不一致 + { + if (value.length === 0) return '请再次输入新密码'; + if (value !== newPassword) return '两次输入的密码不一致'; + return null; + }} + hint="需要与新密码完全一致" + endAdornment={( + setShowNew((current) => !current)} + /> )} -
- - + /> {error && ( @@ -189,7 +277,7 @@ export function ChangePasswordForm({ )} -
+
{onCancel && ( ); } diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index b02899b6..38312c90 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -438,15 +438,14 @@ class HttpApiClient implements ApiClient { } async checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }> { - try { - const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>( - '/api/auth/check-strength', - { password }, - ); - return { rules: data.rules ?? [], valid: !!data.valid }; - } catch { - return { rules: [], valid: false }; + const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>( + '/api/auth/check-strength', + { password }, + ); + if (!Array.isArray(data.rules) || typeof data.valid !== 'boolean') { + throw new ApiError(502, '密码强度接口返回了无效响应'); } + return { rules: data.rules, valid: data.valid }; } async changePassword(oldPassword: string, newPassword: string): Promise { diff --git a/packages/webui/tests/password-inputs.test.tsx b/packages/webui/tests/password-inputs.test.tsx new file mode 100644 index 00000000..2e2e48eb --- /dev/null +++ b/packages/webui/tests/password-inputs.test.tsx @@ -0,0 +1,70 @@ +import { renderToStaticMarkup } from 'react-dom/server'; +import { describe, expect, it } from 'vitest'; +import { FloatingLabelInput } from '../src/components/interior/floating-label'; +import { InlineValidation } from '../src/components/interior/inline-validation'; +import { + PasswordStrength, + type PasswordRule, +} from '../src/components/interior/password-strength'; + +const RULES: readonly PasswordRule[] = [ + { id: 'length', label: '长度不少于 10 位', test: (value) => value.length >= 10 }, + { id: 'upper', label: '包含大写字母', test: (value) => /[A-Z]/.test(value) }, +]; + +describe('password input guidance', () => { + it('renders an accessible floating password label', () => { + const markup = renderToStaticMarkup( + {}} + />, + ); + + expect(markup).toContain('id="password"'); + expect(markup).toContain('for="password"'); + expect(markup).toContain('新密码'); + expect(markup).toContain('aria-required="true"'); + }); + + it('keeps the strength details out of the tree while hidden', () => { + const markup = renderToStaticMarkup( + , + ); + + expect(markup).not.toContain('role="meter"'); + expect(markup).not.toContain('长度不少于 10 位'); + }); + + it('shows the evaluated strength details while visible', () => { + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain('role="meter"'); + expect(markup).toContain('aria-valuenow="2"'); + expect(markup).toContain('长度不少于 10 位'); + expect(markup).toContain('包含大写字母'); + }); + + it('renders inline validation with its hint and status channel', () => { + const markup = renderToStaticMarkup( + {}} + validate={(value) => value ? null : '请再次输入新密码'} + hint="需要与新密码完全一致" + />, + ); + + expect(markup).toContain('确认新密码'); + expect(markup).toContain('需要与新密码完全一致'); + expect(markup).toContain('role="status"'); + }); +}); diff --git a/packages/webui/tests/password-strength-api.test.ts b/packages/webui/tests/password-strength-api.test.ts new file mode 100644 index 00000000..fbd05cf4 --- /dev/null +++ b/packages/webui/tests/password-strength-api.test.ts @@ -0,0 +1,73 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createApiClient } from '../src/lib/api/client'; + +const tokenStore = { + load: () => 'test-token', + save: () => undefined, +}; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('password strength API client', () => { + it('returns the server-owned rule evaluation', async () => { + const rules = [ + { id: 'length', label: '长度不少于 10 位', ok: true }, + { id: 'no-space', label: '不包含空格', ok: true }, + ]; + const fetchMock = vi.fn(async () => new Response(JSON.stringify({ + rules, + valid: true, + }), { + status: 200, + headers: { 'content-type': 'application/json' }, + })); + vi.stubGlobal('fetch', fetchMock); + + const client = createApiClient({ tokenStore }); + await expect(client.checkPasswordStrength('Strong-password')).resolves.toEqual({ + rules, + valid: true, + }); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/check-strength', expect.objectContaining({ + method: 'POST', + body: JSON.stringify({ password: 'Strong-password' }), + headers: { + Authorization: 'Bearer test-token', + 'Content-Type': 'application/json', + }, + signal: expect.any(AbortSignal), + })); + }); + + it('rejects malformed responses instead of silently disabling the form', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ + valid: false, + }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }))); + + const client = createApiClient({ tokenStore }); + await expect(client.checkPasswordStrength('candidate')).rejects.toMatchObject({ + status: 502, + message: '密码强度接口返回了无效响应', + }); + }); + + it('propagates request failures for observable inline validation', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ + message: 'strength service unavailable', + }), { + status: 503, + headers: { 'content-type': 'application/json' }, + }))); + + const client = createApiClient({ tokenStore }); + await expect(client.checkPasswordStrength('candidate')).rejects.toMatchObject({ + status: 503, + message: 'strength service unavailable', + }); + }); +});