From 6488c19172c362afb0eef9aa83ea8f114bf52287 Mon Sep 17 00:00:00 2001 From: kurihada Date: Thu, 26 Feb 2026 20:11:21 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20theme.ts=20=E6=89=80=E6=9C=89=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E6=B7=BB=E5=8A=A0=20SSR=20=E5=AE=88=E5=8D=AB=EF=BC=8C?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=20localStorage=20=E5=90=88=E6=B3=95=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - setStoredTheme/applyTheme/initTheme 添加 typeof window 检查 - getStoredTheme 校验存储值是否在白名单中,防止非法 theme 值 --- src/lib/theme.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/lib/theme.ts b/src/lib/theme.ts index dfddbd9..d0723a9 100644 --- a/src/lib/theme.ts +++ b/src/lib/theme.ts @@ -1,13 +1,18 @@ export type Theme = "light" | "dark" | "system"; const STORAGE_KEY = "nowhatever-theme"; +const VALID_THEMES: Theme[] = ["light", "dark", "system"]; export function getStoredTheme(): Theme { if (typeof window === "undefined") return "system"; - return (localStorage.getItem(STORAGE_KEY) as Theme) || "system"; + const stored = localStorage.getItem(STORAGE_KEY); + return stored && VALID_THEMES.includes(stored as Theme) + ? (stored as Theme) + : "system"; } export function setStoredTheme(theme: Theme): void { + if (typeof window === "undefined") return; localStorage.setItem(STORAGE_KEY, theme); applyTheme(theme); } @@ -21,11 +26,13 @@ function resolveTheme(theme: Theme): "light" | "dark" { } export function applyTheme(theme: Theme): void { + if (typeof window === "undefined") return; const resolved = resolveTheme(theme); document.documentElement.setAttribute("data-theme", resolved); } export function initTheme(): void { + if (typeof window === "undefined") return; const theme = getStoredTheme(); applyTheme(theme);