feat(webui): custom CSS + config export/import/reset (phase 6)
A "高级" Settings tab adds: - Custom CSS (appearance.customCss, <=50KB) applied post-auth only, as the last <style> so it overrides everything. It never reaches the login page: the server strips it from /api/ui/public, applyAppearance gates injection on a bearer token (so the localStorage cache can't leak it pre-auth), and the login page clears any lingering <style> on mount. `?safe-mode=1` (sticky for the tab session) disables custom CSS so a broken rule can't lock the operator out. - Export / import the whole UI config as JSON (import is normalized server-side, then reload); reset-all behind a confirm dialog. POST /api/ui and the import file are size-capped (256KB) on top of the per-field caps. Verified across 2 adversarial review rounds — the pre-auth cached-CSS leak/lockout vector found in round 1 is closed across the boot / logout / 401-expiry / re-login paths.
This commit is contained in:
7 files changed
+237
-8
No files matched your search
@@ -551,6 +551,12 @@ export async function initWebUI(
|
||||
app.get('/api/ui/public', (c) => c.json({ appearance: publicAppearance() }));
|
||||
|
||||
app.post('/api/ui', async (c) => {
|
||||
// Reject oversized bodies before buffering — the normalizer caps individual
|
||||
// fields (customCss 50KB, per-widget config 4KB) but not the whole payload.
|
||||
const declaredLen = Number(c.req.header('content-length'));
|
||||
if (Number.isFinite(declaredLen) && declaredLen > 256 * 1024) {
|
||||
return c.json({ success: false, message: '配置过大' }, 413);
|
||||
}
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
|
||||
@@ -87,6 +87,13 @@ export interface UiAppearance {
|
||||
timeFormat: TimeFormat;
|
||||
/** Dashboard poll interval (ms); 0 = paused. */
|
||||
pollInterval: number;
|
||||
/**
|
||||
* Operator custom CSS, applied AFTER auth only (never on the login page —
|
||||
* `publicAppearance` strips it). Capped at 50 KB. The client injects it as
|
||||
* the last <style> and skips it under `?safe-mode=1` so a broken rule can't
|
||||
* lock the operator out.
|
||||
*/
|
||||
customCss: string;
|
||||
}
|
||||
|
||||
export interface UiLayoutItem {
|
||||
@@ -157,6 +164,7 @@ const DEFAULT_APPEARANCE: UiAppearance = {
|
||||
sidebarDefaultCollapsed: false,
|
||||
timeFormat: '24h',
|
||||
pollInterval: 3000,
|
||||
customCss: '',
|
||||
};
|
||||
|
||||
const DEFAULT_OVERVIEW_BLOCKS: UiLayoutItem[] = [
|
||||
@@ -342,6 +350,7 @@ export function normalizeAppearance(value: unknown, imageState: ServerImageState
|
||||
sidebarDefaultCollapsed: boolOr(v.sidebarDefaultCollapsed, DEFAULT_APPEARANCE.sidebarDefaultCollapsed),
|
||||
timeFormat: oneOf<TimeFormat>(v.timeFormat, ['12h', '24h'], DEFAULT_APPEARANCE.timeFormat),
|
||||
pollInterval: clampNum(v.pollInterval, 0, 60_000, DEFAULT_APPEARANCE.pollInterval),
|
||||
customCss: typeof v.customCss === 'string' ? v.customCss.slice(0, 50_000) : DEFAULT_APPEARANCE.customCss,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -443,9 +452,11 @@ export function saveUiConfig(incoming: unknown): UiConfig {
|
||||
return next;
|
||||
}
|
||||
|
||||
/** The appearance-only subset served unauthenticated to the login page. */
|
||||
/** The appearance subset served unauthenticated to the login page. Strips
|
||||
* `customCss` so a broken/hostile rule can never reach the pre-auth page
|
||||
* (and so the operator can always log in to fix it). */
|
||||
export function publicAppearance(): UiAppearance {
|
||||
return loadUiConfig().appearance;
|
||||
return { ...loadUiConfig().appearance, customCss: '' };
|
||||
}
|
||||
|
||||
// ─── Background image lifecycle ─────────────────────────────────────────────
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { ArrowRight, Eye, EyeOff, KeyRound } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -16,6 +16,12 @@ interface LoginPageProps {
|
||||
export function LoginPage({ onLogin }: LoginPageProps) {
|
||||
const { appearance } = useTheme();
|
||||
const customBg = appearance.background.type !== 'none';
|
||||
|
||||
// The login page must never carry operator custom CSS. applyAppearance gates
|
||||
// it on a token, but an in-session logout / 401 expiry won't re-run it, so
|
||||
// clear any lingering custom-CSS <style> whenever the login page shows.
|
||||
useEffect(() => { document.getElementById('snowluma-custom-css')?.remove(); }, []);
|
||||
|
||||
const [password, setPassword] = useState('');
|
||||
const [showPwd, setShowPwd] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useRef, useState, type ReactNode } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import {
|
||||
Accessibility, Bug, Check, Clock, Download, ExternalLink, Github, Image as ImageIcon,
|
||||
Info, KeyRound, Loader2, Monitor, Moon, Palette, RefreshCw, ShieldCheck,
|
||||
Accessibility, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon,
|
||||
Info, KeyRound, Loader2, Monitor, Moon, Palette, RefreshCw, RotateCcw, ShieldCheck,
|
||||
Sparkles, Star, Sun, Tag, Upload, Trash2,
|
||||
} from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
@@ -12,6 +12,7 @@ import { Separator } from '@/components/ui/separator';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import {
|
||||
ACCENTS,
|
||||
DEFAULT_APPEARANCE,
|
||||
FONT_MONO_OPTIONS,
|
||||
FONT_SANS_OPTIONS,
|
||||
GRADIENT_OPTIONS,
|
||||
@@ -27,15 +28,19 @@ import {
|
||||
type ThemeMode,
|
||||
type TimeFormat,
|
||||
} from '@/contexts/ThemeContext';
|
||||
import { DEFAULT_LAYOUT } from '@/contexts/LayoutContext';
|
||||
import { ChangePasswordDialog } from '@/components/change-password-dialog';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { useAppState } from '@/contexts/AppStateContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
type SettingsTab = 'appearance' | 'data' | 'account' | 'about';
|
||||
type SettingsTab = 'appearance' | 'data' | 'advanced' | 'account' | 'about';
|
||||
|
||||
const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
|
||||
{ key: 'appearance', label: '外观', icon: Palette },
|
||||
{ key: 'data', label: '数据与格式', icon: RefreshCw },
|
||||
{ key: 'advanced', label: '高级', icon: Code2 },
|
||||
{ key: 'account', label: '账号安全', icon: ShieldCheck },
|
||||
{ key: 'about', label: '关于', icon: Info },
|
||||
];
|
||||
@@ -49,12 +54,142 @@ export function SettingsPage() {
|
||||
|
||||
{tab === 'appearance' && <AppearancePanel />}
|
||||
{tab === 'data' && <DataPanel />}
|
||||
{tab === 'advanced' && <AdvancedPanel />}
|
||||
{tab === 'account' && <AccountPanel />}
|
||||
{tab === 'about' && <AboutPanel />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── 高级(自定义 CSS + 备份/重置) ───────────────
|
||||
|
||||
function AdvancedPanel() {
|
||||
const { appearance, setAppearance } = useTheme();
|
||||
const api = useApi();
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
|
||||
const [confirmReset, setConfirmReset] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const onExport = async () => {
|
||||
setMsg(null);
|
||||
try {
|
||||
const config = await api.ui.get();
|
||||
const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'snowluma-ui-config.json';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch {
|
||||
setMsg({ kind: 'err', text: '导出失败' });
|
||||
}
|
||||
};
|
||||
|
||||
const onImportFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (fileRef.current) fileRef.current.value = '';
|
||||
if (!file) return;
|
||||
if (file.size > 256 * 1024) {
|
||||
setMsg({ kind: 'err', text: '导入失败:文件过大(上限 256KB)' });
|
||||
return;
|
||||
}
|
||||
setMsg(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const parsed = JSON.parse(await file.text()) as unknown;
|
||||
if (typeof parsed !== 'object' || parsed === null) throw new Error('shape');
|
||||
await api.ui.save(parsed as Parameters<typeof api.ui.save>[0]);
|
||||
// The server normalized it; reload so appearance + layout both re-read.
|
||||
window.location.reload();
|
||||
} catch {
|
||||
setBusy(false);
|
||||
setMsg({ kind: 'err', text: '导入失败:不是有效的配置 JSON' });
|
||||
}
|
||||
};
|
||||
|
||||
const doReset = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.ui.save({ appearance: DEFAULT_APPEARANCE, layout: DEFAULT_LAYOUT });
|
||||
window.location.reload();
|
||||
} catch {
|
||||
setBusy(false);
|
||||
setMsg({ kind: 'err', text: '重置失败' });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2"><Code2 className="size-4 text-primary" /> 自定义 CSS</CardTitle>
|
||||
<CardDescription>
|
||||
高级用户可注入自定义样式,登录后全局生效(登录页不受影响)。
|
||||
若改坏了界面,在地址后加 <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">?safe-mode=1</code> 可临时禁用自定义 CSS 进来修复。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<textarea
|
||||
value={appearance.customCss}
|
||||
onChange={(e) => setAppearance({ customCss: e.target.value })}
|
||||
maxLength={50000}
|
||||
spellCheck={false}
|
||||
placeholder={'/* 例如:放大侧栏字号 */\n.text-sidebar-foreground { font-size: 1.05em; }'}
|
||||
className="h-64 w-full resize-y rounded-lg border bg-card/40 p-3 font-mono text-[12px] leading-relaxed outline-none focus:border-primary"
|
||||
/>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-[11px] text-muted-foreground">{appearance.customCss.length} / 50000 字符</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setAppearance({ customCss: '' })}
|
||||
disabled={!appearance.customCss}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="size-4" /> 清空
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>备份与重置</CardTitle>
|
||||
<CardDescription>导出 / 导入全部界面配置(外观 + 布局 + 自定义 CSS)。背景图片需另行重新上传。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input ref={fileRef} type="file" accept="application/json,.json" onChange={onImportFile} className="hidden" />
|
||||
<Button variant="outline" size="sm" onClick={onExport} disabled={busy}>
|
||||
<Download className="size-4" /> 导出
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => fileRef.current?.click()} disabled={busy}>
|
||||
{busy ? <Loader2 className="size-4 animate-spin" /> : <Upload className="size-4" />} 导入
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setConfirmReset(true)} disabled={busy} className="text-destructive hover:text-destructive">
|
||||
<RotateCcw className="size-4" /> 重置全部
|
||||
</Button>
|
||||
</div>
|
||||
{msg && (
|
||||
<span className={cn('text-[11px]', msg.kind === 'ok' ? 'text-success' : 'text-destructive')}>{msg.text}</span>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmReset}
|
||||
onOpenChange={setConfirmReset}
|
||||
title="重置全部界面配置"
|
||||
description="将外观、仪表盘布局、导航与自定义 CSS 全部恢复为默认。此操作不可撤销。"
|
||||
confirmText="重置"
|
||||
onConfirm={doReset}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── mini tab strip ───────────────
|
||||
|
||||
function MiniTabs({ tab, onChange }: { tab: SettingsTab; onChange: (t: SettingsTab) => void }) {
|
||||
|
||||
@@ -109,6 +109,7 @@ export const DEFAULT_APPEARANCE: UiAppearance = {
|
||||
sidebarDefaultCollapsed: false,
|
||||
timeFormat: '24h',
|
||||
pollInterval: 3000,
|
||||
customCss: '',
|
||||
};
|
||||
|
||||
const LS_CACHE = 'snowluma_ui_appearance';
|
||||
@@ -223,6 +224,27 @@ function applyAppearance(a: UiAppearance, resolved: 'light' | 'dark'): void {
|
||||
document.head.appendChild(el);
|
||||
}
|
||||
el.textContent = accentVarsCss(a);
|
||||
|
||||
// Custom CSS — appended AFTER the accent block so it is the last style in
|
||||
// <head> and can override anything. Skipped under ?safe-mode=1 (escape
|
||||
// hatch) so a broken rule can't lock the operator out of fixing it.
|
||||
const cssId = 'snowluma-custom-css';
|
||||
let cssEl = document.getElementById(cssId) as HTMLStyleElement | null;
|
||||
// Apply custom CSS ONLY when authed — the cache (snowluma_ui_appearance)
|
||||
// may hold customCss from a prior session, and applyAppearance runs at boot
|
||||
// before auth; without this gate that cached CSS would hit the login page
|
||||
// (bypassing the server-side strip) and could lock the operator out.
|
||||
const css = (isSafeMode() || !authToken()) ? '' : (a.customCss || '');
|
||||
if (css) {
|
||||
if (!cssEl) {
|
||||
cssEl = document.createElement('style');
|
||||
cssEl.id = cssId;
|
||||
document.head.appendChild(cssEl);
|
||||
}
|
||||
if (cssEl.textContent !== css) cssEl.textContent = css;
|
||||
} else if (cssEl) {
|
||||
cssEl.textContent = '';
|
||||
}
|
||||
}
|
||||
|
||||
/** Manage the fixed full-viewport background layer behind the app. */
|
||||
@@ -285,7 +307,18 @@ function authToken(): string | null {
|
||||
}
|
||||
|
||||
async function fetchAppearance(): Promise<UiAppearance | null> {
|
||||
const token = authToken();
|
||||
try {
|
||||
// Authed: fetch the full config so we get `customCss` (which the public
|
||||
// subset strips). Pre-auth (login page): the cosmetic public subset only.
|
||||
if (token) {
|
||||
const res = await fetch('/api/ui', { headers: { Authorization: `Bearer ${token}` } });
|
||||
if (res.ok) {
|
||||
const data = (await res.json()) as { config?: { appearance?: UiAppearance } };
|
||||
if (data.config?.appearance) return data.config.appearance;
|
||||
}
|
||||
// 401/expired → fall through to the public subset.
|
||||
}
|
||||
const res = await fetch('/api/ui/public');
|
||||
if (!res.ok) return null;
|
||||
const data = (await res.json()) as { appearance?: UiAppearance };
|
||||
@@ -295,6 +328,22 @@ async function fetchAppearance(): Promise<UiAppearance | null> {
|
||||
}
|
||||
}
|
||||
|
||||
/** `?safe-mode=1` disables custom CSS so a broken rule can't lock the operator
|
||||
* out. Sticky for the session (sessionStorage) so it survives in-app
|
||||
* navigation — and so editing the CSS to fix it doesn't re-inject the broken
|
||||
* rule mid-fix. Clears when the tab/session closes. */
|
||||
function isSafeMode(): boolean {
|
||||
try {
|
||||
if (new URLSearchParams(window.location.search).get('safe-mode') === '1') {
|
||||
sessionStorage.setItem('snowluma_safe_mode', '1');
|
||||
return true;
|
||||
}
|
||||
return sessionStorage.getItem('snowluma_safe_mode') === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function persistAppearance(appearance: UiAppearance): Promise<void> {
|
||||
const token = authToken();
|
||||
if (!token) return; // pre-auth: local cache only (no settings UI exists there anyway)
|
||||
@@ -370,6 +419,9 @@ interface ThemeContextValue {
|
||||
removeBackground: () => Promise<void>;
|
||||
/** Format a timestamp per the configured 12h/24h preference. */
|
||||
formatClock: (input: string | number | Date) => string;
|
||||
/** Re-fetch appearance from the server (e.g. after login, so the authed
|
||||
* `customCss` loads). */
|
||||
reloadAppearance: () => Promise<void>;
|
||||
// ── back-compat conveniences ──
|
||||
mode: ThemeMode;
|
||||
setMode: (m: ThemeMode) => void;
|
||||
@@ -494,6 +546,18 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
});
|
||||
}, [appearance.timeFormat]);
|
||||
|
||||
const reloadAppearance = useCallback(async () => {
|
||||
// Post-auth, the only field the pre-auth public subset lacked is
|
||||
// `customCss`. Merge JUST that (via setAppearance, which preserves every
|
||||
// other field — incl. a pre-auth localStorage migration — and write-through
|
||||
// persists). A full overwrite here would clobber that migration with the
|
||||
// server's not-yet-persisted default.
|
||||
const server = await fetchAppearance();
|
||||
if (server && server.customCss !== appearanceRef.current.customCss) {
|
||||
setAppearance({ customCss: server.customCss });
|
||||
}
|
||||
}, [setAppearance]);
|
||||
|
||||
const value = useMemo<ThemeContextValue>(() => ({
|
||||
appearance,
|
||||
ready,
|
||||
@@ -502,10 +566,11 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
uploadBackground,
|
||||
removeBackground,
|
||||
formatClock,
|
||||
reloadAppearance,
|
||||
mode: appearance.mode,
|
||||
setMode: (m: ThemeMode) => setAppearance({ mode: m }),
|
||||
pollInterval: appearance.pollInterval,
|
||||
}), [appearance, ready, resolved, setAppearance, uploadBackground, removeBackground, formatClock]);
|
||||
}), [appearance, ready, resolved, setAppearance, uploadBackground, removeBackground, formatClock, reloadAppearance]);
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={value}>
|
||||
|
||||
@@ -19,9 +19,13 @@ import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInf
|
||||
*/
|
||||
export function AppLayout() {
|
||||
const api = useApi();
|
||||
const { pollInterval } = useTheme();
|
||||
const { pollInterval, reloadAppearance } = useTheme();
|
||||
const session = useSession();
|
||||
|
||||
// Now that we're authed, re-fetch appearance from /api/ui so the
|
||||
// authed-only `customCss` (stripped from the pre-auth public subset) loads.
|
||||
useEffect(() => { void reloadAppearance(); }, [reloadAppearance]);
|
||||
|
||||
const [qqList, setQqList] = useState<QQInfo[]>([]);
|
||||
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
|
||||
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
|
||||
|
||||
@@ -204,6 +204,8 @@ export interface UiAppearance {
|
||||
sidebarDefaultCollapsed: boolean;
|
||||
timeFormat: TimeFormat;
|
||||
pollInterval: number;
|
||||
/** Operator custom CSS (applied post-auth only; stripped from /api/ui/public). */
|
||||
customCss: string;
|
||||
}
|
||||
|
||||
export interface UiLayoutItem {
|
||||
|
||||
Reference in new issue
Block a user