From f93fd52523e52f556ebc7704ff08eeabdfde6815 Mon Sep 17 00:00:00 2001 From: Todos Date: Thu, 5 Nov 2026 09:51:53 +0800 Subject: [PATCH 1/2] chore: checkpoint aNjqq32bU4h4s0J3CgYT8 --- web/src/components/admin/settings-panels.tsx | 25 ++++ web/src/components/public-page.tsx | 22 ++- web/src/lib/mockDb.ts | 9 +- web/src/lib/types.ts | 2 + web/test/public-page.test.tsx | 106 +++++++++++++- web/test/settings-panels.test.tsx | 54 +++++++ web/test/theme-toggle.test.tsx | 1 + worker/src/index.ts | 2 + worker/src/routes/admin.ts | 7 + worker/src/routes/wallpaper.ts | 102 ++++++++++++++ worker/src/services/site-data.ts | 2 + worker/src/types.ts | 2 + worker/test/settings.test.ts | 69 +++++++++ worker/test/setup.test.ts | 1 + worker/test/wallpaper.test.ts | 140 +++++++++++++++++++ 15 files changed, 539 insertions(+), 5 deletions(-) create mode 100644 worker/src/routes/wallpaper.ts create mode 100644 worker/test/wallpaper.test.ts diff --git a/web/src/components/admin/settings-panels.tsx b/web/src/components/admin/settings-panels.tsx index 5468423..3b70ae9 100644 --- a/web/src/components/admin/settings-panels.tsx +++ b/web/src/components/admin/settings-panels.tsx @@ -250,6 +250,8 @@ export function SettingsPanel({ const [form, setForm] = React.useState({ ...settings, logoUrl: settings.logoUrl ?? "", + // 旧数据 / 旧 mock 可能没有该字段:契约默认 Bing + wallpaperSource: settings.wallpaperSource ?? "bing", // 旧数据 / 旧 mock 可能没有该字段:契约默认开 searchNewTab: settings.searchNewTab ?? true, }); @@ -278,6 +280,29 @@ export function SettingsPanel({ onChange={(e) => setForm({ ...form, siteTitle: e.target.value })} /> +
+ + +

+ 选「自定义壁纸」时使用下方背景图;选「Bing 每日壁纸」时忽略背景图地址。 +

+
void }) { const settings = siteData?.settings; const categories = siteData?.categories ?? []; + // 壁纸来源(SPEC:缺省 bing)。custom 且填了 backgroundUrl 才用自定义图, + // 否则(bing / custom 但 backgroundUrl 为空)都走 Bing 每日壁纸端点。 + const wallpaperSource = settings?.wallpaperSource ?? "bing"; + const customBackgroundUrl = settings?.backgroundUrl ?? ""; + const useBing = wallpaperSource !== "custom" || !customBackgroundUrl; + + // bing 取图失败时回落:先试 backgroundUrl(非空),再落到纯色底(url 层去掉)。 + const [bingFailed, setBingFailed] = React.useState(false); + React.useEffect(() => { + setBingFailed(false); + if (!useBing) return; + const img = new Image(); + img.onload = () => setBingFailed(false); + img.onerror = () => setBingFailed(true); + img.src = "/api/wallpaper/today"; + }, [useBing]); + + const backgroundUrl = + useBing && !bingFailed ? "/api/wallpaper/today" : customBackgroundUrl; + // 私有标识:/api/private 的分类 DTO 不含 visibility,用「全量里有、公开列表里没有」推导私有分类。 const publicIds = new Set(publicData?.categories.map((c) => c.id) ?? []); const privateIds = new Set( @@ -59,7 +79,7 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) { className="fixed inset-0 -z-10 bg-cover bg-center bg-no-repeat" style={{ backgroundImage: `linear-gradient(rgba(15,23,42,0.55), rgba(15,23,42,0.35)), url(${JSON.stringify( - settings?.backgroundUrl ?? "", + backgroundUrl, )})`, backgroundColor: "#0f172a", }} diff --git a/web/src/lib/mockDb.ts b/web/src/lib/mockDb.ts index bcfef36..4b0aebb 100644 --- a/web/src/lib/mockDb.ts +++ b/web/src/lib/mockDb.ts @@ -148,6 +148,7 @@ function seed(): MockState { siteTitle: "我的导航", backgroundUrl: "https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=2400&q=80", + wallpaperSource: "bing", logoUrl: "", theme: "system", columns: 8, @@ -160,11 +161,15 @@ function load(): MockState { try { const raw = localStorage.getItem(STORAGE_KEY); if (raw) { - // 旧 mock 库没有 searchNewTab:按契约默认开补齐,避免界面读到 undefined + // 旧 mock 库没有 searchNewTab / wallpaperSource:按契约默认补齐,避免界面读到 undefined const state = JSON.parse(raw) as Omit & { settings: Partial; }; - state.settings = { searchNewTab: true, ...state.settings }; + state.settings = { + searchNewTab: true, + wallpaperSource: "bing", + ...state.settings, + }; return state as MockState; } } catch { diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 24acd5a..fbb66c5 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -41,6 +41,8 @@ export interface SearchEngine { export interface SiteSettings { siteTitle: string; backgroundUrl: string; + /** 壁纸来源(后端 KV `wallpaper_source`,无此键时为 bing):`bing` 每日壁纸 / `custom` 用 backgroundUrl */ + wallpaperSource: "bing" | "custom"; /** 站点 Logo 图片地址(外链 URL 或上传后的 `/assets/...` 路径,空串表示无) */ logoUrl: string; theme: "system" | "light" | "dark"; diff --git a/web/test/public-page.test.tsx b/web/test/public-page.test.tsx index dc7d03d..d6b2e5a 100644 --- a/web/test/public-page.test.tsx +++ b/web/test/public-page.test.tsx @@ -1,6 +1,6 @@ -import { render, screen, within } from "@testing-library/react"; +import { render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { PublicPage } from "@/components/public-page"; import { useNavStore } from "@/lib/nav-store"; import type { SearchEngine, SiteSettings } from "@/lib/types"; @@ -12,6 +12,7 @@ vi.mock("sonner", () => ({ const baseSettings: SiteSettings = { siteTitle: "我的导航", backgroundUrl: "", + wallpaperSource: "bing", logoUrl: "", theme: "system", columns: 6, @@ -120,3 +121,104 @@ describe("PublicPage:搜索跳转方式跟随站点设置 searchNewTab", () => expect(location.href).toBe("http://localhost/start"); }); }); + +describe("PublicPage:壁纸来源解析(缺省 bing)", () => { + /** 背景层是唯一的 aria-hidden 且带 backgroundImage 的 div。 */ + function backgroundLayer(container: HTMLElement): HTMLElement { + const el = Array.from( + container.querySelectorAll('div[aria-hidden="true"]'), + ).find((d) => d.style.backgroundImage); + if (!el) throw new Error("背景层未找到"); + return el; + } + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("wallpaperSource=bing(缺省)+ 无 backgroundUrl:背景层指向 /api/wallpaper/today", () => { + seed(baseSettings); + const { container } = render(); + expect(backgroundLayer(container).style.backgroundImage).toContain( + "/api/wallpaper/today", + ); + }); + + it("wallpaperSource=custom + backgroundUrl 非空:背景层用 backgroundUrl", () => { + seed({ + ...baseSettings, + wallpaperSource: "custom", + backgroundUrl: "https://cdn.example.com/bg.jpg", + }); + const { container } = render(); + const bg = backgroundLayer(container).style.backgroundImage; + expect(bg).toContain("https://cdn.example.com/bg.jpg"); + expect(bg).not.toContain("/api/wallpaper/today"); + }); + + it("wallpaperSource=custom 但 backgroundUrl 为空:回落 /api/wallpaper/today", () => { + seed({ ...baseSettings, wallpaperSource: "custom", backgroundUrl: "" }); + const { container } = render(); + expect(backgroundLayer(container).style.backgroundImage).toContain( + "/api/wallpaper/today", + ); + }); + + it("wallpaperSource=bing 但 backgroundUrl 非空:仍用 Bing(忽略自定义图)", () => { + seed({ + ...baseSettings, + wallpaperSource: "bing", + backgroundUrl: "https://cdn.example.com/bg.jpg", + }); + const { container } = render(); + expect(backgroundLayer(container).style.backgroundImage).toContain( + "/api/wallpaper/today", + ); + }); + + it("bing 图加载失败:回落 backgroundUrl(非空)", async () => { + seed({ + ...baseSettings, + wallpaperSource: "bing", + backgroundUrl: "https://cdn.example.com/bg.jpg", + }); + + class FailingImage { + onload: (() => void) | null = null; + onerror: (() => void) | null = null; + set src(_v: string) { + queueMicrotask(() => this.onerror?.()); + } + } + vi.stubGlobal("Image", FailingImage); + + const { container } = render(); + + await waitFor(() => + expect(backgroundLayer(container).style.backgroundImage).toContain( + "https://cdn.example.com/bg.jpg", + ), + ); + }); + + it("bing 图加载失败且无 backgroundUrl:去掉 url 层(纯色底)", async () => { + seed({ ...baseSettings, wallpaperSource: "bing", backgroundUrl: "" }); + + class FailingImage { + onload: (() => void) | null = null; + onerror: (() => void) | null = null; + set src(_v: string) { + queueMicrotask(() => this.onerror?.()); + } + } + vi.stubGlobal("Image", FailingImage); + + const { container } = render(); + + await waitFor(() => { + const bg = backgroundLayer(container).style.backgroundImage; + expect(bg).not.toContain("/api/wallpaper/today"); + expect(bg).not.toContain("cdn.example.com"); + }); + }); +}); diff --git a/web/test/settings-panels.test.tsx b/web/test/settings-panels.test.tsx index bd9c877..44eb9d9 100644 --- a/web/test/settings-panels.test.tsx +++ b/web/test/settings-panels.test.tsx @@ -25,6 +25,7 @@ const updateSettingsMock = vi.mocked(adminUpdateSettings); const baseSettings: SiteSettings = { siteTitle: "我的导航", backgroundUrl: "", + wallpaperSource: "bing", logoUrl: "", theme: "system", columns: 6, @@ -199,3 +200,56 @@ describe("SettingsPanel:搜索在新标签页打开开关(默认开)", () expect(screen.getByLabelText("搜索在新标签页打开")).toBeChecked(); }); }); + +describe("SettingsPanel:壁纸来源切换(默认 Bing)", () => { + beforeEach(() => { + uploadMock.mockReset(); + updateSettingsMock.mockReset(); + updateSettingsMock.mockImplementation(async (input) => ({ + ...baseSettings, + ...input, + })); + }); + + it("默认渲染「Bing 每日壁纸」,保存时提交 wallpaperSource=bing", async () => { + const user = userEvent.setup(); + + render(); + + expect(screen.getByText("壁纸来源")).toBeInTheDocument(); + expect(screen.getByText("Bing 每日壁纸")).toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: "保存设置" })); + + await waitFor(() => expect(updateSettingsMock).toHaveBeenCalledTimes(1)); + expect(updateSettingsMock.mock.calls[0][0]).toMatchObject({ + wallpaperSource: "bing", + }); + }); + + it("旧数据缺 wallpaperSource 时按默认 bing 显示", () => { + render( + , + ); + expect(screen.getByText("Bing 每日壁纸")).toBeInTheDocument(); + }); + + it("切换到「自定义壁纸」并保存:提交 wallpaperSource=custom", async () => { + const user = userEvent.setup(); + + render(); + + await user.click(screen.getByRole("combobox", { name: "选择壁纸来源" })); + await user.click(screen.getByRole("option", { name: "自定义壁纸" })); + + await user.click(screen.getByRole("button", { name: "保存设置" })); + + await waitFor(() => expect(updateSettingsMock).toHaveBeenCalledTimes(1)); + expect(updateSettingsMock.mock.calls[0][0]).toMatchObject({ + wallpaperSource: "custom", + }); + }); +}); diff --git a/web/test/theme-toggle.test.tsx b/web/test/theme-toggle.test.tsx index f520da0..8e41779 100644 --- a/web/test/theme-toggle.test.tsx +++ b/web/test/theme-toggle.test.tsx @@ -18,6 +18,7 @@ import type { SiteSettings } from "@/lib/types"; const baseSettings: SiteSettings = { siteTitle: "我的导航", backgroundUrl: "", + wallpaperSource: "bing", logoUrl: "", theme: "system", columns: 6, diff --git a/worker/src/index.ts b/worker/src/index.ts index 90baa05..d10badf 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -7,6 +7,7 @@ import { publicRoutes } from "./routes/public"; import { privateRoutes } from "./routes/private"; import { adminRoutes } from "./routes/admin"; import { setupRoutes } from "./routes/setup"; +import { wallpaperRoutes } from "./routes/wallpaper"; import { assetPublicRoutes } from "./routes/assets"; import { getSetting } from "./db/queries/settings"; import { deleteExpiredSessions } from "./db/queries/users"; @@ -49,6 +50,7 @@ app.route("/api/auth/passkey", webauthnRoutes); app.route("/api/public", publicRoutes); app.route("/api/private", privateRoutes); app.route("/api/admin", adminRoutes); +app.route("/api/wallpaper", wallpaperRoutes); // Setup surface: GET /api/setup/state (canonical), GET /api/setup/status // (legacy alias), POST /api/setup (secret-gated upgrade — SETUP-PAGE-SPEC §3). app.route("/api", setupRoutes); diff --git a/worker/src/routes/admin.ts b/worker/src/routes/admin.ts index 4bced9e..e62aea6 100644 --- a/worker/src/routes/admin.ts +++ b/worker/src/routes/admin.ts @@ -414,6 +414,7 @@ const SETTING_KEYS = [ "theme", "columns", "search_new_tab", + "wallpaper_source", ] as const; adminRoutes.get("/settings", async (c) => { @@ -466,6 +467,12 @@ adminRoutes.put("/settings", async (c) => { return badRequest("searchNewTab must be a boolean"); updates.search_new_tab = body.searchNewTab ? "1" : "0"; } + if (body.wallpaperSource !== undefined) { + const wallpaperSource = String(body.wallpaperSource); + if (!["bing", "custom"].includes(wallpaperSource)) + return badRequest("wallpaperSource must be 'bing' or 'custom'"); + updates.wallpaper_source = wallpaperSource; + } for (const [key, value] of Object.entries(updates)) { await setSetting(c.env.DB, prefix, key, value); diff --git a/worker/src/routes/wallpaper.ts b/worker/src/routes/wallpaper.ts new file mode 100644 index 0000000..6589f0e --- /dev/null +++ b/worker/src/routes/wallpaper.ts @@ -0,0 +1,102 @@ +import { Hono } from "hono"; +import type { HonoEnv } from "../types"; + +export const wallpaperRoutes = new Hono(); + +/** Bing 每日壁纸元信息接口(zh-CN,当日 idx=0)。 */ +const BING_API = + "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN"; + +/** 北京时间(Asia/Shanghai)当天日期 YYYY-MM-DD,用作按天缓存键。 */ +function beijingDate(d: Date): string { + return new Intl.DateTimeFormat("en-CA", { + timeZone: "Asia/Shanghai", + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(d); +} + +/** 到下一个北京时间零点的秒数(Cache-Control:当天图缓存至次日)。 */ +function secondsUntilNextBeijingMidnight(now: Date): number { + const DAY_MS = 24 * 60 * 60 * 1000; + const BEIJING_MIDNIGHT_UTC_MS = 16 * 60 * 60 * 1000; // 00:00 CST == 16:00 UTC + const ms = now.getTime(); + let next = Math.floor(ms / DAY_MS) * DAY_MS + BEIJING_MIDNIGHT_UTC_MS; + if (next <= ms) next += DAY_MS; + return Math.max(1, Math.ceil((next - ms) / 1000)); +} + +/** + * 回源当日 Bing 壁纸:先取元信息,优先 UHD 变体,UHD 失败降回接口原图。 + * 任何一步失败返回 null(交由上层走昨日缓存 / 502 回落)。 + */ +async function fetchBingWallpaper(): Promise { + let meta: Response; + try { + meta = await fetch(BING_API); + } catch { + return null; + } + if (!meta.ok) return null; + + let data: { images?: { url?: string }[] }; + try { + data = (await meta.json()) as { images?: { url?: string }[] }; + } catch { + return null; + } + const urlPath = data.images?.[0]?.url; + if (!urlPath) return null; + + const baseUrl = `https://www.bing.com${urlPath}`; + // 分辨率段(如 _1920x1080.jpg)换为 _UHD.jpg;本就是 UHD 时不重复拉取。 + const uhdUrl = baseUrl.replace(/_\d+x\d+\.(jpg|jpeg|png)/i, "_UHD.$1"); + const candidates = uhdUrl === baseUrl ? [baseUrl] : [uhdUrl, baseUrl]; + + for (const url of candidates) { + try { + const res = await fetch(url); + if (!res.ok) continue; + if ((res.headers.get("content-type") ?? "").startsWith("image/")) + return res; + } catch { + // continue to next candidate + } + } + return null; +} + +// GET /api/wallpaper/today — 同源代理当日 Bing 壁纸(无鉴权,公共页未登录也要取图)。 +wallpaperRoutes.get("/today", async (c) => { + const now = new Date(); + const todayKey = `bing-wallpaper:${beijingDate(now)}`; + + // 当天缓存命中直接返回(含存储时写好的 Cache-Control)。 + const cached = await caches.default.match(todayKey); + if (cached) return cached; + + const image = await fetchBingWallpaper(); + if (image) { + const headers = new Headers(image.headers); + headers.set( + "cache-control", + `public, max-age=${secondsUntilNextBeijingMidnight(now)}`, + ); + const response = new Response(image.body, { status: 200, headers }); + try { + await caches.default.put(todayKey, response.clone()); + } catch { + // 缓存是尽力而为:写失败不影响本次取图。 + } + return response; + } + + // 回源失败:宁用昨日缓存图,不用空白。 + const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000); + const yesterdayKey = `bing-wallpaper:${beijingDate(yesterday)}`; + const previous = await caches.default.match(yesterdayKey); + if (previous) return previous; + + return c.json({ error: "wallpaper unavailable" }, 502); +}); diff --git a/worker/src/services/site-data.ts b/worker/src/services/site-data.ts index 06e614a..8b93f20 100644 --- a/worker/src/services/site-data.ts +++ b/worker/src/services/site-data.ts @@ -43,6 +43,8 @@ export function toSiteSettingsDto( return { siteTitle: settings.site_title ?? "nav", backgroundUrl: settings.background_url ?? "", + // 缺省/脏值一律归一 `bing`:存量库没有该键时默认用 Bing 每日壁纸。 + wallpaperSource: settings.wallpaper_source === "custom" ? "custom" : "bing", logoUrl: settings.logo_url ?? "", theme: settings.theme ?? "system", columns: Number.isFinite(columns) && columns > 0 ? columns : 0, diff --git a/worker/src/types.ts b/worker/src/types.ts index 4166019..43c97b9 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -150,6 +150,8 @@ export interface SearchEngineDto { export interface SiteSettingsDto { siteTitle: string; backgroundUrl: string; + /** 壁纸来源(settings key `wallpaper_source`):`bing`(默认)或 `custom`(用 backgroundUrl)。 */ + wallpaperSource: "bing" | "custom"; /** Local upload path (`/assets/…`) or an external URL; "" when unset. */ logoUrl: string; theme: string; diff --git a/worker/test/settings.test.ts b/worker/test/settings.test.ts index 8e04190..b9f8dfa 100644 --- a/worker/test/settings.test.ts +++ b/worker/test/settings.test.ts @@ -224,3 +224,72 @@ describe("settings searchNewTab (search_new_tab)", () => { expect((await readJson(res)).keys).toContain("search_new_tab"); }); }); + +/** + * `wallpaperSource`(壁纸来源):KV 键 `wallpaper_source`,值 `bing`/`custom`。 + * 存量库无此键时 DTO 按 `bing` 返回;公开端点同样带出该字段给前端。 + */ +describe("settings wallpaperSource (wallpaper_source)", () => { + let env: Env; + let app: Hono; + let cookie: string; + + beforeEach(async () => { + env = makeEnv(); + app = makeApp(); + await runMigrations(env); + cookie = await signIn(app, env); + }); + + it("defaults to bing when the key is absent (admin + public DTO)", async () => { + expect(storedSetting(env, "wallpaper_source")).toBeNull(); + + const admin = await readJson(await getSettings(app, env, cookie)); + expect(admin.wallpaperSource).toBe("bing"); + + const pub = await readJson(await app.request("/api/public", {}, env)); + expect(pub.settings.wallpaperSource).toBe("bing"); + }); + + it("round-trips custom/bing and mirrors into /api/public", async () => { + let res = await putSettings(app, env, cookie, { wallpaperSource: "custom" }); + expect(res.status).toBe(200); + expect((await readJson(res)).wallpaperSource).toBe("custom"); + expect(storedSetting(env, "wallpaper_source")).toBe("custom"); + expect( + (await readJson(await app.request("/api/public", {}, env))).settings + .wallpaperSource, + ).toBe("custom"); + + res = await putSettings(app, env, cookie, { wallpaperSource: "bing" }); + expect((await readJson(res)).wallpaperSource).toBe("bing"); + expect(storedSetting(env, "wallpaper_source")).toBe("bing"); + }); + + it("keeps the stored value when other settings are written", async () => { + await putSettings(app, env, cookie, { wallpaperSource: "custom" }); + const res = await putSettings(app, env, cookie, { siteTitle: "nav2" }); + expect((await readJson(res)).wallpaperSource).toBe("custom"); + }); + + it("rejects invalid values with 400 and keeps the stored value", async () => { + await putSettings(app, env, cookie, { wallpaperSource: "bing" }); + for (const wallpaperSource of ["custom2", "Bing", "", null, 1]) { + const res = await putSettings(app, env, cookie, { wallpaperSource }); + expect(res.status).toBe(400); + expect(await readJson(res)).toEqual({ + error: "wallpaperSource must be 'bing' or 'custom'", + }); + } + expect(storedSetting(env, "wallpaper_source")).toBe("bing"); + }); + + it("lists wallpaper_source in the settings whitelist", async () => { + const res = await app.request( + "/api/admin/settings/keys", + { headers: { cookie } }, + env, + ); + expect((await readJson(res)).keys).toContain("wallpaper_source"); + }); +}); diff --git a/worker/test/setup.test.ts b/worker/test/setup.test.ts index 177c6bb..1806050 100644 --- a/worker/test/setup.test.ts +++ b/worker/test/setup.test.ts @@ -414,6 +414,7 @@ describe("admin system endpoints", () => { "searchNewTab", "siteTitle", "theme", + "wallpaperSource", ]); expect(JSON.stringify(publicBody)).not.toContain(SETUP_PAGE_KEY); diff --git a/worker/test/wallpaper.test.ts b/worker/test/wallpaper.test.ts new file mode 100644 index 0000000..24f82e2 --- /dev/null +++ b/worker/test/wallpaper.test.ts @@ -0,0 +1,140 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Hono } from "hono"; +import { wallpaperRoutes } from "../src/routes/wallpaper"; + +const BING_API = + "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN"; +const IMAGE_PATH = + "/th?id=OHR.Test_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp"; +const UHD_URL = `https://www.bing.com/th?id=OHR.Test_UHD.jpg&rf=LaDigue_1920x1080.jpg&pid=hp`; +const ORIG_URL = `https://www.bing.com${IMAGE_PATH}`; + +/** 极简 Cache 替身:只实现端点用到的 match / put。 */ +class MemoryCache { + map = new Map(); + async match(key: string): Promise { + return this.map.get(key); + } + async put(key: string, res: Response): Promise { + this.map.set(key, res); + } +} + +function beijingDate(d: Date): string { + return new Intl.DateTimeFormat("en-CA", { + timeZone: "Asia/Shanghai", + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(d); +} + +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + headers: { "content-type": "application/json" }, + }); +} + +function imageResponse(): Response { + return new Response(new Uint8Array([1, 2, 3]), { + headers: { "content-type": "image/jpeg" }, + }); +} + +function makeApp(): Hono { + const app = new Hono(); + app.route("/api/wallpaper", wallpaperRoutes); + return app; +} + +describe("GET /api/wallpaper/today", () => { + let cache: MemoryCache; + let app: Hono; + + const todayKey = () => `bing-wallpaper:${beijingDate(new Date())}`; + const yesterdayKey = () => + `bing-wallpaper:${beijingDate( + new Date(Date.now() - 24 * 60 * 60 * 1000), + )}`; + + beforeEach(() => { + cache = new MemoryCache(); + vi.stubGlobal("caches", { default: cache }); + app = makeApp(); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("当天缓存命中:不再回源,直接返回缓存响应", async () => { + cache.map.set(todayKey(), imageResponse()); + const fetchMock = vi.fn(); + vi.stubGlobal("fetch", fetchMock); + + const res = await app.request("/api/wallpaper/today"); + + expect(fetchMock).not.toHaveBeenCalled(); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/jpeg"); + }); + + it("当天首次请求回源并写入缓存,第二次请求命中缓存不回源", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(jsonResponse({ images: [{ url: IMAGE_PATH }] })) + .mockResolvedValueOnce(imageResponse()); + vi.stubGlobal("fetch", fetchMock); + + const first = await app.request("/api/wallpaper/today"); + expect(first.status).toBe(200); + expect(first.headers.get("content-type")).toBe("image/jpeg"); + expect(first.headers.get("cache-control")).toMatch(/^public, max-age=\d+$/); + expect(fetchMock).toHaveBeenCalledWith(BING_API); + expect(fetchMock).toHaveBeenCalledWith(UHD_URL); + expect(cache.map.has(todayKey())).toBe(true); + + const callsAfterFirst = fetchMock.mock.calls.length; + const second = await app.request("/api/wallpaper/today"); + expect(second.status).toBe(200); + expect(fetchMock.mock.calls.length).toBe(callsAfterFirst); + }); + + it("UHD 回源失败时降回接口原图", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(jsonResponse({ images: [{ url: IMAGE_PATH }] })) + .mockResolvedValueOnce(new Response("", { status: 500 })) // UHD 失败 + .mockResolvedValueOnce(imageResponse()); // 原图成功 + vi.stubGlobal("fetch", fetchMock); + + const res = await app.request("/api/wallpaper/today"); + + expect(res.status).toBe(200); + expect(fetchMock).toHaveBeenCalledWith(UHD_URL); + expect(fetchMock).toHaveBeenCalledWith(ORIG_URL); + }); + + it("回源失败且存在昨日缓存:返回昨日缓存图", async () => { + cache.map.set(yesterdayKey(), imageResponse()); + const fetchMock = vi + .fn() + .mockResolvedValue(new Response("", { status: 500 })); + vi.stubGlobal("fetch", fetchMock); + + const res = await app.request("/api/wallpaper/today"); + + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/jpeg"); + }); + + it("全链路失败(无缓存、回源失败):返回 502 JSON", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("offline")); + vi.stubGlobal("fetch", fetchMock); + + const res = await app.request("/api/wallpaper/today"); + + expect(res.status).toBe(502); + expect(await res.json()).toEqual({ error: "wallpaper unavailable" }); + }); +}); From ec6b61db0cedb5f0a05e813c2d90b8e20202d0fb Mon Sep 17 00:00:00 2001 From: Todos Date: Thu, 5 Nov 2026 11:16:36 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(wallpaper):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E9=94=AE=E9=9D=9E=E6=B3=95=E4=B8=8E=E6=98=A8?= =?UTF-8?q?=E6=97=A5=E5=9B=9E=E9=80=80=EF=BC=8C=E7=99=BD=E5=90=8D=E5=8D=95?= =?UTF-8?q?=E5=93=8D=E5=BA=94=E5=A4=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 缓存键改为同源绝对 URL(裸串在 workerd 会 500);缓存条目 TTL 与客户端 TTL 分层(2 天 vs 到次日零点);只透传 content-type/cache-control;设置未到达时不发探针;补齐契约文档与回归测试。 Co-Authored-By: Claude Code Checkpoint: f4r47QJEYtNgnyRqVLn9D --- docs/api-contract.md | 16 +++- web/src/components/admin/settings-panels.tsx | 3 +- web/src/components/public-page.tsx | 13 ++- web/test/public-page.test.tsx | 21 +++++ worker/src/routes/wallpaper.ts | 84 ++++++++++++++--- worker/test/settings.test.ts | 4 +- worker/test/wallpaper.test.ts | 97 ++++++++++++++++++-- 7 files changed, 211 insertions(+), 27 deletions(-) diff --git a/docs/api-contract.md b/docs/api-contract.md index 9bb6bde..bc1f683 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -42,6 +42,7 @@ "settings": { "siteTitle": "nav", "backgroundUrl": "", + "wallpaperSource": "bing", "logoUrl": "", "theme": "system", "columns": 0, @@ -50,6 +51,15 @@ } ``` +`wallpaperSource`:首页壁纸来源,`bing`(默认,Bing 每日壁纸)| `custom`(用 `backgroundUrl` 自定义图)。存量库无此键时按 `bing` 返回。 + +### GET /api/wallpaper/today + +同源代理 Bing 每日壁纸(无鉴权,公共页未登录也要取图)。 +- 200:图片二进制,`Content-Type: image/*`;`Cache-Control: public, max-age=<到下一个北京时间零点的秒数>`。 +- 回源失败时回退到昨日缓存图(同样 200);连昨日缓存也无 → `502 {"error":"wallpaper unavailable"}`。 +- 服务端按北京时间自然日缓存当天图(内部缓存条目多保留一天以支持次日回退);不向上游透传 `content-length` / `x-msedge-ref` / `nel` / `report-to` 等头。 + ## 私有 ### GET /api/private @@ -113,11 +123,13 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14): ### 站点设置 -- `GET /api/admin/settings` → `{siteTitle, backgroundUrl, logoUrl, theme, columns, searchNewTab}` -- `PUT /api/admin/settings` body 可含 `{siteTitle, backgroundUrl, logoUrl, theme(light|dark|system), columns(0–12), searchNewTab(boolean)}` → 更新后对象 +- `GET /api/admin/settings` → `{siteTitle, backgroundUrl, wallpaperSource, logoUrl, theme, columns, searchNewTab}` +- `PUT /api/admin/settings` body 可含 `{siteTitle, backgroundUrl, wallpaperSource(bing|custom), logoUrl, theme(light|dark|system), columns(0–12), searchNewTab(boolean)}` → 更新后对象 `searchNewTab`:搜索是否在新标签页打开。存储键 `search_new_tab`,值 `"1"`/`"0"`(同 `totp_enabled` 的 KV 布尔惯例);库中**无此键**(存量库)时按 `true` 返回。写入只接受布尔值,非布尔返回 400 `searchNewTab must be a boolean`。 +`wallpaperSource`:首页壁纸来源。存储键 `wallpaper_source`,值 `"bing"`/`"custom"`;库中**无此键**(存量库)时按 `bing` 返回。写入只接受 `bing`/`custom`,其他值返回 400 `wallpaperSource must be 'bing' or 'custom'`。 + `columns` 允许 `0–12`,其中 `0` 表示**未配置**(用默认值):`0` 原样存入并原样返回,不会被替换成默认列数。`GET /api/admin/settings` 对未配置的库返回 `columns: 0`,所以 `0–12` 都能往返提交;超出范围返回 400 `columns must be between 0 and 12`。 `backgroundUrl` / `logoUrl` 的值可以是外链 URL,也可以是本地上传路径(`/assets/…`,见下节)。`/assets/…` 被替换成**任何**其他值时,旧 R2 对象自动删除;外链旧值一律不删。 diff --git a/web/src/components/admin/settings-panels.tsx b/web/src/components/admin/settings-panels.tsx index 3b70ae9..d103bc3 100644 --- a/web/src/components/admin/settings-panels.tsx +++ b/web/src/components/admin/settings-panels.tsx @@ -300,7 +300,8 @@ export function SettingsPanel({

- 选「自定义壁纸」时使用下方背景图;选「Bing 每日壁纸」时忽略背景图地址。 + 选「自定义壁纸」时使用下方背景图;选「Bing + 每日壁纸」时忽略背景图地址。

void }) { // 壁纸来源(SPEC:缺省 bing)。custom 且填了 backgroundUrl 才用自定义图, // 否则(bing / custom 但 backgroundUrl 为空)都走 Bing 每日壁纸端点。 + // 站点设置未到达(settings 为 undefined)时先不解析来源、也不发探针, + // 以免设置还没回就提前拉取整张大图;此时先显示纯色底。 + const settingsReady = settings !== undefined; const wallpaperSource = settings?.wallpaperSource ?? "bing"; const customBackgroundUrl = settings?.backgroundUrl ?? ""; - const useBing = wallpaperSource !== "custom" || !customBackgroundUrl; + const useBing = + settingsReady && (wallpaperSource !== "custom" || !customBackgroundUrl); // bing 取图失败时回落:先试 backgroundUrl(非空),再落到纯色底(url 层去掉)。 const [bingFailed, setBingFailed] = React.useState(false); @@ -62,8 +66,11 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) { img.src = "/api/wallpaper/today"; }, [useBing]); - const backgroundUrl = - useBing && !bingFailed ? "/api/wallpaper/today" : customBackgroundUrl; + const backgroundUrl = !settingsReady + ? "" + : useBing && !bingFailed + ? "/api/wallpaper/today" + : customBackgroundUrl; // 私有标识:/api/private 的分类 DTO 不含 visibility,用「全量里有、公开列表里没有」推导私有分类。 const publicIds = new Set(publicData?.categories.map((c) => c.id) ?? []); diff --git a/web/test/public-page.test.tsx b/web/test/public-page.test.tsx index d6b2e5a..ca16582 100644 --- a/web/test/public-page.test.tsx +++ b/web/test/public-page.test.tsx @@ -136,6 +136,27 @@ describe("PublicPage:壁纸来源解析(缺省 bing)", () => { vi.unstubAllGlobals(); }); + it("站点设置未到达(publicData 为 null):不发起探针,背景层不指向端点", () => { + useNavStore.setState({ + publicData: null, + privateData: null, + authStatus: "anonymous", + loginPromptOpen: false, + loadPublic: async () => {}, + loadPrivate: async () => {}, + }); + const imageSpy = vi.fn(); + vi.stubGlobal("Image", imageSpy); + + const { container } = render(); + + // 设置没回之前不应提前拉取整张大图。 + expect(imageSpy).not.toHaveBeenCalled(); + expect(backgroundLayer(container).style.backgroundImage).not.toContain( + "/api/wallpaper/today", + ); + }); + it("wallpaperSource=bing(缺省)+ 无 backgroundUrl:背景层指向 /api/wallpaper/today", () => { seed(baseSettings); const { container } = render(); diff --git a/worker/src/routes/wallpaper.ts b/worker/src/routes/wallpaper.ts index 6589f0e..6d77879 100644 --- a/worker/src/routes/wallpaper.ts +++ b/worker/src/routes/wallpaper.ts @@ -7,6 +7,8 @@ export const wallpaperRoutes = new Hono(); const BING_API = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN"; +const DAY_SECONDS = 24 * 60 * 60; + /** 北京时间(Asia/Shanghai)当天日期 YYYY-MM-DD,用作按天缓存键。 */ function beijingDate(d: Date): string { return new Intl.DateTimeFormat("en-CA", { @@ -27,6 +29,33 @@ function secondsUntilNextBeijingMidnight(now: Date): number { return Math.max(1, Math.ceil((next - ms) / 1000)); } +/** + * 按天缓存键。Cache API 只接受**绝对 URL** 作键:裸串(如 `bing-wallpaper:…`) + * 在 workerd 会以 “Invalid URL. Cache API keys must be fully-qualified” 拒绝并 500, + * 因此以当前请求的 origin 解析出同源绝对 URL。 + */ +function cacheKey(reqUrl: string, date: string): string { + return new URL(`/__cache/bing-wallpaper/${date}`, reqUrl).toString(); +} + +/** + * 构造图片响应:只放行 content-type / cache-control,**不透传** Bing 上游的 + * content-length、x-msedge-ref、nel、report-to 等内部头。 + */ +function buildImageResponse( + body: ReadableStream | null, + contentType: string, + maxAge: number, +): Response { + return new Response(body, { + status: 200, + headers: { + "content-type": contentType, + "cache-control": `public, max-age=${maxAge}`, + }, + }); +} + /** * 回源当日 Bing 壁纸:先取元信息,优先 UHD 变体,UHD 失败降回接口原图。 * 任何一步失败返回 null(交由上层走昨日缓存 / 502 回落)。 @@ -70,33 +99,60 @@ async function fetchBingWallpaper(): Promise { // GET /api/wallpaper/today — 同源代理当日 Bing 壁纸(无鉴权,公共页未登录也要取图)。 wallpaperRoutes.get("/today", async (c) => { const now = new Date(); - const todayKey = `bing-wallpaper:${beijingDate(now)}`; + const todayKey = cacheKey(c.req.url, beijingDate(now)); + const clientMaxAge = secondsUntilNextBeijingMidnight(now); - // 当天缓存命中直接返回(含存储时写好的 Cache-Control)。 + // 缓存命中:缓存条目存 2 天(见下方),但发给浏览器的 TTL 始终是「到次日零点」。 const cached = await caches.default.match(todayKey); - if (cached) return cached; + if (cached) { + return buildImageResponse( + cached.body, + cached.headers.get("content-type") ?? "image/jpeg", + clientMaxAge, + ); + } const image = await fetchBingWallpaper(); if (image) { - const headers = new Headers(image.headers); - headers.set( - "cache-control", - `public, max-age=${secondsUntilNextBeijingMidnight(now)}`, + const contentType = image.headers.get("content-type") ?? "image/jpeg"; + // 缓存条目多存一天(覆盖次日「昨日回退」窗口),与发给客户端的 TTL 分开: + // 客户端只缓存到次日零点,缓存条目保留到再下一个零点。 + const cacheMaxAge = clientMaxAge + DAY_SECONDS; + + if (!image.body) { + return c.json({ error: "wallpaper unavailable" }, 502); + } + const [clientBody, cacheBody] = image.body.tee(); + const clientResponse = buildImageResponse( + clientBody, + contentType, + clientMaxAge, + ); + const cacheResponse = buildImageResponse( + cacheBody, + contentType, + cacheMaxAge, ); - const response = new Response(image.body, { status: 200, headers }); try { - await caches.default.put(todayKey, response.clone()); + await caches.default.put(todayKey, cacheResponse); } catch { // 缓存是尽力而为:写失败不影响本次取图。 } - return response; + return clientResponse; } // 回源失败:宁用昨日缓存图,不用空白。 - const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000); - const yesterdayKey = `bing-wallpaper:${beijingDate(yesterday)}`; - const previous = await caches.default.match(yesterdayKey); - if (previous) return previous; + const yesterday = new Date(now.getTime() - DAY_SECONDS * 1000); + const previous = await caches.default.match( + cacheKey(c.req.url, beijingDate(yesterday)), + ); + if (previous) { + return buildImageResponse( + previous.body, + previous.headers.get("content-type") ?? "image/jpeg", + clientMaxAge, + ); + } return c.json({ error: "wallpaper unavailable" }, 502); }); diff --git a/worker/test/settings.test.ts b/worker/test/settings.test.ts index b9f8dfa..82bdf72 100644 --- a/worker/test/settings.test.ts +++ b/worker/test/settings.test.ts @@ -252,7 +252,9 @@ describe("settings wallpaperSource (wallpaper_source)", () => { }); it("round-trips custom/bing and mirrors into /api/public", async () => { - let res = await putSettings(app, env, cookie, { wallpaperSource: "custom" }); + let res = await putSettings(app, env, cookie, { + wallpaperSource: "custom", + }); expect(res.status).toBe(200); expect((await readJson(res)).wallpaperSource).toBe("custom"); expect(storedSetting(env, "wallpaper_source")).toBe("custom"); diff --git a/worker/test/wallpaper.test.ts b/worker/test/wallpaper.test.ts index 24f82e2..ea44209 100644 --- a/worker/test/wallpaper.test.ts +++ b/worker/test/wallpaper.test.ts @@ -8,14 +8,33 @@ const IMAGE_PATH = "/th?id=OHR.Test_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp"; const UHD_URL = `https://www.bing.com/th?id=OHR.Test_UHD.jpg&rf=LaDigue_1920x1080.jpg&pid=hp`; const ORIG_URL = `https://www.bing.com${IMAGE_PATH}`; +/** `app.request("/api/wallpaper/today")` 下 Hono 的 c.req.url origin。 */ +const ORIGIN = "http://localhost"; + +const DAY_SECONDS = 24 * 60 * 60; + +/** + * Cache API 替身:与 workerd 一致,**拒绝非 fully-qualified URL 的键**。 + * 裸串(如 `bing-wallpaper:…`)在 workerd 里会抛 “Invalid URL”,这里同步抛, + * 避免测试替身再次掩盖 P0。 + */ +function assertAbsoluteUrl(key: string): void { + const url = new URL(key); // 相对路径/裸串在这里就会抛 + if (!url.host) { + throw new TypeError( + "Invalid URL. Cache API keys must be fully-qualified, valid URLs.", + ); + } +} -/** 极简 Cache 替身:只实现端点用到的 match / put。 */ class MemoryCache { map = new Map(); async match(key: string): Promise { + assertAbsoluteUrl(key); return this.map.get(key); } async put(key: string, res: Response): Promise { + assertAbsoluteUrl(key); this.map.set(key, res); } } @@ -29,15 +48,27 @@ function beijingDate(d: Date): string { }).format(d); } +function maxAgeOf(res: Response): number { + const m = res.headers.get("cache-control")?.match(/max-age=(\d+)/); + return m ? Number(m[1]) : Number.NaN; +} + function jsonResponse(body: unknown): Response { return new Response(JSON.stringify(body), { headers: { "content-type": "application/json" }, }); } +/** 带 Bing 上游内部头的图片响应,用于验证响应头不透传。 */ function imageResponse(): Response { return new Response(new Uint8Array([1, 2, 3]), { - headers: { "content-type": "image/jpeg" }, + headers: { + "content-type": "image/jpeg", + "content-length": "3", + "x-msedge-ref": "Ref A: deadbeef", + nel: '{"report_to":"network-errors"}', + "report-to": '{"group":"network-errors"}', + }, }); } @@ -51,10 +82,12 @@ describe("GET /api/wallpaper/today", () => { let cache: MemoryCache; let app: Hono; - const todayKey = () => `bing-wallpaper:${beijingDate(new Date())}`; + // 缓存键与端点一致:同源绝对 URL(workerd 只接受 fully-qualified URL)。 + const todayKey = () => + `${ORIGIN}/__cache/bing-wallpaper/${beijingDate(new Date())}`; const yesterdayKey = () => - `bing-wallpaper:${beijingDate( - new Date(Date.now() - 24 * 60 * 60 * 1000), + `${ORIGIN}/__cache/bing-wallpaper/${beijingDate( + new Date(Date.now() - DAY_SECONDS * 1000), )}`; beforeEach(() => { @@ -67,7 +100,7 @@ describe("GET /api/wallpaper/today", () => { vi.unstubAllGlobals(); }); - it("当天缓存命中:不再回源,直接返回缓存响应", async () => { + it("当天缓存命中:不再回源,直接返回缓存响应(客户端 TTL 重写为到次日零点)", async () => { cache.map.set(todayKey(), imageResponse()); const fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock); @@ -77,6 +110,8 @@ describe("GET /api/wallpaper/today", () => { expect(fetchMock).not.toHaveBeenCalled(); expect(res.status).toBe(200); expect(res.headers.get("content-type")).toBe("image/jpeg"); + // 命中缓存也不能把「缓存条目 TTL(2 天)」透给浏览器。 + expect(maxAgeOf(res)).toBeLessThanOrEqual(DAY_SECONDS); }); it("当天首次请求回源并写入缓存,第二次请求命中缓存不回源", async () => { @@ -100,6 +135,41 @@ describe("GET /api/wallpaper/today", () => { expect(fetchMock.mock.calls.length).toBe(callsAfterFirst); }); + it("缓存条目 TTL 与客户端 TTL 分层:缓存存到次日之后,客户端只到次日零点", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(jsonResponse({ images: [{ url: IMAGE_PATH }] })) + .mockResolvedValueOnce(imageResponse()); + vi.stubGlobal("fetch", fetchMock); + + const res = await app.request("/api/wallpaper/today"); + const cached = cache.map.get(todayKey()); + expect(cached).toBeDefined(); + + const clientMaxAge = maxAgeOf(res); + const cacheMaxAge = maxAgeOf(cached as Response); + // 客户端 ≤ 到次日零点(≤ 24h);缓存条目至少多一天,才能撑到次日「昨日回退」。 + expect(clientMaxAge).toBeLessThanOrEqual(DAY_SECONDS); + expect(cacheMaxAge).toBeGreaterThanOrEqual(clientMaxAge + DAY_SECONDS); + }); + + it("不透传 Bing 上游响应头:只保留 content-type / cache-control", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(jsonResponse({ images: [{ url: IMAGE_PATH }] })) + .mockResolvedValueOnce(imageResponse()); + vi.stubGlobal("fetch", fetchMock); + + const res = await app.request("/api/wallpaper/today"); + + expect(res.headers.get("content-type")).toBe("image/jpeg"); + expect(res.headers.get("cache-control")).toMatch(/^public, max-age=\d+$/); + expect(res.headers.get("content-length")).toBeNull(); + expect(res.headers.get("x-msedge-ref")).toBeNull(); + expect(res.headers.get("nel")).toBeNull(); + expect(res.headers.get("report-to")).toBeNull(); + }); + it("UHD 回源失败时降回接口原图", async () => { const fetchMock = vi .fn() @@ -126,6 +196,21 @@ describe("GET /api/wallpaper/today", () => { expect(res.status).toBe(200); expect(res.headers.get("content-type")).toBe("image/jpeg"); + // 昨日图同样只给到次日零点的客户端 TTL。 + expect(maxAgeOf(res)).toBeLessThanOrEqual(DAY_SECONDS); + }); + + it("缓存条目已过 TTL(match 返回 miss)且回源失败:返回 502 而非抛异常", async () => { + // 模拟条目按 max-age 被驱逐:先写入再删除,等价于 match miss。 + cache.map.set(todayKey(), imageResponse()); + cache.map.delete(todayKey()); + const fetchMock = vi.fn().mockRejectedValue(new Error("offline")); + vi.stubGlobal("fetch", fetchMock); + + const res = await app.request("/api/wallpaper/today"); + + expect(res.status).toBe(502); + expect(await res.json()).toEqual({ error: "wallpaper unavailable" }); }); it("全链路失败(无缓存、回源失败):返回 502 JSON", async () => {