From 12f90e50d0a6146bae1e77c1203977127548d32d Mon Sep 17 00:00:00 2001 From: Todos Date: Thu, 5 Nov 2026 16:00:01 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(icon):=20=E6=96=B0=E5=A2=9E=20worker?= =?UTF-8?q?=20=E7=AB=AF=E5=9B=BE=E6=A0=87=E8=A7=A3=E6=9E=90=E5=99=A8?= =?UTF-8?q?=E4=B8=8E=20GET=20/api/icon=20=E7=AB=AF=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 服务端读目标站 HTML 的 link rel=icon 并探测根文件,抓到后写入既有 R2 桶缓存(_cache/favicons/{host},不建表、不加绑定、不加定时任务),按字节嗅探类型后直接回图;请求 host 必须在站点注册表内,内网/回环/保留地址与非默认端口一律拒绝,不跟随重定向。私有链接域名需会话。保留前缀不经 /assets/* 公开。 Checkpoint: iYqIt-dY49HRMA7WT4W6_ --- docs/api-contract.md | 15 +- worker/src/index.ts | 3 + worker/src/middleware/auth.ts | 27 +- worker/src/routes/assets.ts | 6 + worker/src/routes/icon.ts | 76 ++++ worker/src/services/assets.ts | 6 + worker/src/services/favicon.ts | 607 +++++++++++++++++++++++++++++ worker/test/favicon.test.ts | 681 +++++++++++++++++++++++++++++++++ worker/test/helpers.ts | 23 +- 9 files changed, 1433 insertions(+), 11 deletions(-) create mode 100644 worker/src/routes/icon.ts create mode 100644 worker/src/services/favicon.ts create mode 100644 worker/test/favicon.test.ts diff --git a/docs/api-contract.md b/docs/api-contract.md index bc1f683..ce36730 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -60,6 +60,19 @@ - 回源失败时回退到昨日缓存图(同样 200);连昨日缓存也无 → `502 {"error":"wallpaper unavailable"}`。 - 服务端按北京时间自然日缓存当天图(内部缓存条目多保留一天以支持次日回退);不向上游透传 `content-length` / `x-msedge-ref` / `nel` / `report-to` 等头。 +### GET /api/icon + +worker 端图标解析器:服务端读目标站 HTML 的 `` 声明、探测根文件,抓到后缓存并**直接回图字节**。无鉴权(公共页未登录也要显示图标)。前端在 `iconUrl` 非空时直接用它、不请求本端点;首字圆仍是最终兜底。 +- 入参 `url`:必填,`encodeURIComponent` 后的绝对 URL(链接的 `url` 或搜索引擎 `urlTemplate` 去掉 `{q}`)。服务端只用它的 host 与 scheme,**不使用 path/query**。 +- 缺失/非法(非 http/https、带账号密码、非默认端口)→ `400 {"error":"url must be an absolute http(s) URL"}`,`Cache-Control: no-store`。 +- **站点注册表**:host 必须已登记在本站数据里 —— 公开链接与搜索引擎的 host 匿名可取;只出现在私有链接里的 host 需要有效会话,否则按未登记处理。未登记(含内网/回环/保留地址,它们永远不入表)→ `404 {"error":"icon not found"}`,`Cache-Control: public, max-age=3600`,**不发起任何外部请求**(本端点不是开放代理)。 +- **解析顺序**(全部限定在登记的 origin):`GET https://{host}/` 读 HTML 里 `rel` 含 `icon` / `apple-touch-icon` 的 ``(svg > png > ico,`sizes` 大者优先;声明落在其他 host 的一律忽略)→ 命中即取该图 → 否则依次探测 `/favicon.ico`、`/favicon.svg`、`/favicon.png`、`/apple-touch-icon.png` → 全失败记为「无图」。 +- **出网约束**:只请求上述 origin 的根路径与固定根文件;`redirect: "manual"`,3xx 一律视为该候选失败;单次 5s 超时、一次解析总预算 8s;HTML 读 256KB、图标读 512KB 上限;带 `user-agent: nav-favicon/1`。 +- 成功 `200`:图标原始字节,`content-type` 为按魔数嗅探出的真实类型(`image/png` / `image/jpeg` / `image/webp` / `image/gif` / `image/svg+xml` / `image/x-icon`),`cache-control: public, max-age=86400`,`x-content-type-options: nosniff`;**不透传任何上游响应头**。 +- 无图标 `404 {"error":"icon not found"}` + `cache-control: public, max-age=3600`。 +- **缓存**:R2 对象 `_cache/favicons/{host}`(保留前缀,不经 `GET /assets/*` 公开),`customMetadata` 记 `{status:"ok"|"none", fetchedAt, mime?, sourceUrl?}`。「有图」30 天、「无图」7 天视为新鲜;过期时先回旧结果、后台重抓(`waitUntil`),**不用定时任务**;同一 host 的并发解析合并为一次。R2 未绑定或读写失败时降级为「现抓现发、不缓存」。 +- 不读也不改写 `links.icon_url`。 + ## 私有 ### GET /api/private @@ -168,6 +181,6 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14): ## 说明 -- favicon 自动抓取不在后端做:前端直接请求目标站 / 公共 favicon 服务,失败回退首字圆;后端只存 `iconUrl` 字段。 +- 图标自动抓取由 worker 做:见上方 `GET /api/icon`(服务端解析 + R2 缓存 + 直接回图)。前端只在 `iconUrl` 为空时请求该端点,失败回退首字圆;后端仍只存 `iconUrl` 字段。 - 点击计数、服务健康状态为预留字段,v1 不实现(SPEC 第 5 节)。 - 会话 Cookie `nav_session`:HS256 JWT 签名 + `sessions` 表吊销,7 天有效。 diff --git a/worker/src/index.ts b/worker/src/index.ts index d10badf..1ce2644 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -8,6 +8,7 @@ import { privateRoutes } from "./routes/private"; import { adminRoutes } from "./routes/admin"; import { setupRoutes } from "./routes/setup"; import { wallpaperRoutes } from "./routes/wallpaper"; +import { iconRoutes } from "./routes/icon"; import { assetPublicRoutes } from "./routes/assets"; import { getSetting } from "./db/queries/settings"; import { deleteExpiredSessions } from "./db/queries/users"; @@ -51,6 +52,8 @@ app.route("/api/public", publicRoutes); app.route("/api/private", privateRoutes); app.route("/api/admin", adminRoutes); app.route("/api/wallpaper", wallpaperRoutes); +// Worker 端图标解析器:回图由 R2 缓存直出(契约 docs/api-contract.md §GET /api/icon)。 +app.route("/api/icon", iconRoutes); // 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/middleware/auth.ts b/worker/src/middleware/auth.ts index cf6b473..4c13e95 100644 --- a/worker/src/middleware/auth.ts +++ b/worker/src/middleware/auth.ts @@ -23,21 +23,34 @@ export function unauthorized(): Response { }); } -export async function authMiddleware(c: Context, next: Next) { +/** + * 会话探测:有效会话返回 user id,否则 null(不抛、不写响应)。`authMiddleware` + * 与需要「有会话则放宽」的端点(`GET /api/icon` 的私有 host)共用这一条判断。 + */ +export async function getSessionUserId( + c: Context, +): Promise { const token = getCookie(c, SESSION_COOKIE); - if (!token) return unauthorized(); + if (!token) return null; const payload = await verifyJWT(token, c.env.SESSION_SECRET); - if (!payload) return unauthorized(); + if (!payload) return null; const prefix = getTablePrefix(c.env); const session = await findSession(c.env.DB, prefix, payload.sid); - if (!session || session.expires_at < nowIso()) return unauthorized(); - if (session.user_id !== payload.sub) return unauthorized(); + if (!session || session.expires_at < nowIso()) return null; + if (session.user_id !== payload.sub) return null; const user = await findUserById(c.env.DB, prefix, session.user_id); - if (!user?.is_active) return unauthorized(); + if (!user?.is_active) return null; + + return user.id; +} + +export async function authMiddleware(c: Context, next: Next) { + const userId = await getSessionUserId(c); + if (!userId) return unauthorized(); - c.set("userId", user.id); + c.set("userId", userId); await next(); } diff --git a/worker/src/routes/assets.ts b/worker/src/routes/assets.ts index 9568c9b..254857b 100644 --- a/worker/src/routes/assets.ts +++ b/worker/src/routes/assets.ts @@ -10,6 +10,7 @@ import { assetSizeError, isAssetPurpose, mimeForExt, + RESERVED_ASSET_KEY_PREFIX, validateImageUpload, } from "../services/assets"; @@ -35,7 +36,12 @@ assetPublicRoutes.get("/*", async (c) => { if (!bucket) return c.json({ error: "not found" }, 404); const key = c.req.path.slice(ASSET_PUBLIC_PREFIX.length); + // 保留前缀是 worker 内部缓存(图标等)。它们不是用户上传物,也不该被 + // 按 key 猜出来(猜得到「这个站在主人链接里」这类关联)。 if (!key || key.includes("..")) return c.json({ error: "not found" }, 404); + if (key.startsWith(RESERVED_ASSET_KEY_PREFIX)) { + return c.json({ error: "not found" }, 404); + } const object = await bucket.get(key); if (!object) return c.json({ error: "not found" }, 404); diff --git a/worker/src/routes/icon.ts b/worker/src/routes/icon.ts new file mode 100644 index 0000000..08f3598 --- /dev/null +++ b/worker/src/routes/icon.ts @@ -0,0 +1,76 @@ +import { Hono } from "hono"; +import type { Context } from "hono"; +import { getTablePrefix, type HonoEnv } from "../types"; +import { getSessionUserId } from "../middleware/auth"; +import { + getIcon, + loadIconRegistry, + parseIconTarget, + type CachedIcon, +} from "../services/favicon"; + +/** + * `GET /api/icon?url=…` —— worker 端图标解析器的唯一边界(契约见 + * docs/api-contract.md §GET /api/icon)。回图按字节返回,前端不与第三方站 + * 直连;抓不到就是 404,由前端回退首字圆。 + */ +export const iconRoutes = new Hono(); + +const ICON_CACHE_CONTROL = "public, max-age=86400"; +const MISS_CACHE_CONTROL = "public, max-age=3600"; + +function iconNotFound(c: Context): Response { + c.header("cache-control", MISS_CACHE_CONTROL); + return c.json({ error: "icon not found" }, 404); +} + +/** 后台刷新:有 ExecutionContext 就托管,没有(单测)就让它在 isolate 里跑完。 */ +function schedule(c: Context, task: Promise): void { + const settled = task.catch(() => undefined); + try { + c.executionCtx.waitUntil(settled); + } catch { + // 没有 ExecutionContext 的环境(app.request)无需额外处理。 + } +} + +function iconResponse(icon: CachedIcon): Response { + return new Response(icon.bytes, { + status: 200, + headers: { + "content-type": icon.mime ?? "application/octet-stream", + "cache-control": ICON_CACHE_CONTROL, + // 第三方图片一律当不可信内容:禁止浏览器重新嗅探类型。 + "x-content-type-options": "nosniff", + }, + }); +} + +iconRoutes.get("/", async (c) => { + const requested = parseIconTarget(c.req.query("url") ?? ""); + if (!requested) { + c.header("cache-control", "no-store"); + return c.json({ error: "url must be an absolute http(s) URL" }, 400); + } + + const prefix = getTablePrefix(c.env); + // 私有链接的 host 需要有效会话;会话查询失败按匿名处理,端点不因未初始化 + // 的库变成 500。 + const userId = await getSessionUserId(c).catch(() => null); + const registry = await loadIconRegistry(c.env, prefix, { + includePrivate: Boolean(userId), + }); + + // 出网目标取自注册表里的 origin,而不是请求参数里的 path/query。 + const entry = registry.get(requested.host); + if (!entry) return iconNotFound(c); + + const icon = await getIcon( + c.env, + { host: requested.host, origin: entry.origin }, + (task) => schedule(c, task), + ); + if (icon.status !== "ok" || !icon.bytes) return iconNotFound(c); + + return iconResponse(icon); +}); diff --git a/worker/src/services/assets.ts b/worker/src/services/assets.ts index 2178dca..32a9236 100644 --- a/worker/src/services/assets.ts +++ b/worker/src/services/assets.ts @@ -66,6 +66,12 @@ export const ASSET_CACHE_CONTROL = "public, max-age=31536000, immutable"; /** Objects are keyed `assets/…` and publicly served at `/assets/{key}`. */ export const ASSET_PUBLIC_PREFIX = "/assets/"; +/** + * 保留 key 前缀:worker 内部缓存(如图标)落在这里,`GET /assets/*` 一律 + * 拒绝 —— 它们不是用户上传物,也不该被按 key 猜出来。 + */ +export const RESERVED_ASSET_KEY_PREFIX = "_cache/"; + export function mimeForExt(ext: string): string | null { const entry = Object.entries(EXT_BY_KIND).find(([, value]) => value === ext); return entry ? MIME_BY_KIND[entry[0] as ImageKind] : null; diff --git a/worker/src/services/favicon.ts b/worker/src/services/favicon.ts new file mode 100644 index 0000000..07324c7 --- /dev/null +++ b/worker/src/services/favicon.ts @@ -0,0 +1,607 @@ +/** + * Worker 端图标解析器:读目标站 HTML 的 `` 声明、探测根文件 + * favicon.ico / .svg / .png / apple-touch-icon.png,抓到后写入 R2 缓存,由 + * `GET /api/icon` 直接回图。契约见 docs/api-contract.md §GET /api/icon。 + * + * 设计取舍: + * - 缓存不建表:图标字节与「有图 / 无图」状态都落在既有 R2 桶的保留前缀 + * `_cache/favicons/{host}` 下,新鲜度写在对象的 customMetadata.fetchedAt 里。 + * 因此本功能不产生 D1 迁移、不新增绑定,也不需要定时任务刷新。 + * - 出网边界:只访问注册表(本站链接与搜索引擎的 host)登记过的 origin, + * 且只碰 origin 根路径与四个固定根文件;任何重定向一律不跟随。 + */ +import type { Env } from "../types"; +import { listLinks, listSearchEngines } from "../db/queries/content"; +import { + detectBinaryImageKind, + isSvgDocument, + RESERVED_ASSET_KEY_PREFIX, + type ImageKind, +} from "./assets"; + +/** 图标缓存对象 key = 保留前缀 + favicons/ + host。 */ +export const ICON_CACHE_PREFIX = `${RESERVED_ASSET_KEY_PREFIX}favicons/`; + +/** 「有图」结果的保鲜期:30 天。 */ +const ICON_TTL_MS = 30 * 24 * 60 * 60 * 1000; +/** 「无图」结果的保鲜期:7 天。 */ +const ICON_MISS_TTL_MS = 7 * 24 * 60 * 60 * 1000; + +/** 单次抓取上限:HTML 256KB、图标 512KB。 */ +const HTML_MAX_BYTES = 256 * 1024; +const ICON_MAX_BYTES = 512 * 1024; + +/** 单次请求超时,以及一次解析的总预算(防止端点挂住)。 */ +const FETCH_TIMEOUT_MS = 5000; +const RESOLVE_BUDGET_MS = 8000; + +/** 站点的 HTML 里最多认几个 `` 声明。 */ +const MAX_DECLARED_ICONS = 3; + +const USER_AGENT = "nav-favicon/1"; + +/** 根文件探测顺序(与契约一致)。 */ +export const ROOT_ICON_PATHS = [ + "/favicon.ico", + "/favicon.svg", + "/favicon.png", + "/apple-touch-icon.png", +] as const; + +const MIME_BY_KIND: Record = { + png: "image/png", + jpg: "image/jpeg", + webp: "image/webp", + gif: "image/gif", + svg: "image/svg+xml", + ico: "image/x-icon", +}; + +// ─── 目标与出网边界 ────────────────────────────────────────────────────────── + +export interface IconTarget { + /** 小写 host(URL 解析后的值,IPv6 带方括号)。 */ + host: string; + /** `scheme://host[:port]`,不带尾部斜杠。 */ + origin: string; +} + +/** + * 解析并校验一个图标目标 URL。只放行 http/https、无账号密码、默认端口、 + * 且 host 不是内网/回环/保留地址的目标;其余返回 null。 + */ +export function parseIconTarget(value: string): IconTarget | null { + let url: URL; + try { + url = new URL(value.trim()); + } catch { + return null; + } + if (url.protocol !== "http:" && url.protocol !== "https:") return null; + if (url.username || url.password) return null; + const port = url.port; + if (port !== "" && port !== "80" && port !== "443") return null; + + const host = url.hostname.toLowerCase(); + if (!isPublicHostname(host)) return null; + + return { host, origin: `${url.protocol}//${host}${port ? `:${port}` : ""}` }; +} + +const BLOCKED_HOST_SUFFIXES = [ + ".localhost", + ".local", + ".internal", + ".home.arpa", +]; + +/** 内网名字、单标签主机名与私网/保留 IP 字面量一律拒绝。 */ +export function isPublicHostname(host: string): boolean { + if (!host) return false; + + // WHATWG URL 把 IPv6 字面量放在方括号里(`[::1]`)。 + if (host.startsWith("[") && host.endsWith("]")) { + return isPublicIpv6(host.slice(1, -1)); + } + if (host === "localhost") return false; + if (BLOCKED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) { + return false; + } + // 单标签(intranet、printer …)只能是内网名字。 + if (!host.includes(".")) return false; + + const ipv4 = parseIpv4(host); + if (ipv4) return isPublicIpv4(ipv4); + + return true; +} + +function parseIpv4(host: string): [number, number, number, number] | null { + const parts = host.split("."); + if (parts.length !== 4) return null; + const octets: number[] = []; + for (const part of parts) { + if (!/^\d{1,3}$/.test(part)) return null; + const value = Number(part); + if (value > 255) return null; + octets.push(value); + } + return octets as [number, number, number, number]; +} + +function isPublicIpv4([a, b, c]: [number, number, number, number]): boolean { + if (a === 0 || a === 10 || a === 127) return false; // 本网 / 内网 / 环回 + if (a === 100 && b >= 64 && b <= 127) return false; // CGNAT + if (a === 169 && b === 254) return false; // 链路本地(云元数据) + if (a === 172 && b >= 16 && b <= 31) return false; // 内网 + if (a === 192 && b === 168) return false; // 内网 + if (a === 192 && b === 0 && (c === 0 || c === 2)) return false; + if (a === 198 && (b === 18 || b === 19)) return false; // 基准测试 + if (a === 198 && b === 51 && c === 100) return false; // 文档 + if (a === 203 && b === 0 && c === 113) return false; // 文档 + if (a >= 224) return false; // 组播 / 保留 / 广播 + return true; +} + +function isPublicIpv6(raw: string): boolean { + const host = raw.toLowerCase(); + if (host === "::" || host === "::1") return false; // 未指定 / 环回 + if (/^f[cd]/.test(host)) return false; // fc00::/7 唯一本地 + if (/^fe[89ab]/.test(host)) return false; // fe80::/10 链路本地 + if (/^ff/.test(host)) return false; // 组播 + // IPv4 映射 / NAT64 可能藏一个私网 v4 地址。 + if (host.startsWith("::ffff:") || host.startsWith("64:ff9b:")) return false; + return true; +} + +// ─── HTML 中的图标声明 ────────────────────────────────────────────────────── + +const LINK_TAG_RE = /]*>/gi; +const ATTR_RE = + /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g; + +/** + * 纯函数:从 HTML 里取 `` 类声明,按偏好排序后返回绝对 URL。 + * + * 不引 HTML 解析依赖:worker 现有依赖(hono、webauthn)无一覆盖 DOM 解析, + * 而 `HTMLRewriter` 在 node 测试环境不存在;这里只关心 `` 标签,正则 + * 足够且可被现有 vitest(environment: node)直接单测。 + * + * 只接受与 `origin` 同 host 的声明(跨 host/CDN 的图标一律忽略,不扩大出网 + * 边界),并统一用注册表的 origin 重建 URL(丢掉声明里的端口与 scheme 差异)。 + */ +export function parseIconLinks(html: string, origin: string): string[] { + const base = `${origin}/`; + const baseHost = new URL(base).hostname.toLowerCase(); + const found: Array<{ url: string; score: number }> = []; + const seen = new Set(); + + for (const tag of html.match(LINK_TAG_RE) ?? []) { + const attrs: Record = {}; + for (const match of tag.matchAll(ATTR_RE)) { + const name = match[1].toLowerCase(); + if (name in attrs) continue; + attrs[name] = match[2] ?? match[3] ?? match[4] ?? ""; + } + + const rel = (attrs.rel ?? "").toLowerCase().split(/\s+/).filter(Boolean); + if (!rel.some((t) => t === "icon" || t.startsWith("apple-touch-icon"))) { + continue; + } + // mask-icon 是 Safari 的单色钉住图标,不适合当站点图标。 + if (rel.includes("mask-icon")) continue; + + const href = (attrs.href ?? "").trim(); + if (!href) continue; + + let resolved: URL; + try { + resolved = new URL(href, base); + } catch { + continue; + } + if (resolved.hostname.toLowerCase() !== baseHost) continue; + if (!resolved.pathname || resolved.pathname === "/") continue; + + const url = `${origin}${resolved.pathname}${resolved.search}`; + if (seen.has(url)) continue; + seen.add(url); + found.push({ url, score: iconLinkScore(attrs, resolved) }); + } + + return found + .sort((a, b) => b.score - a.score) + .slice(0, MAX_DECLARED_ICONS) + .map((entry) => entry.url); +} + +/** 越大越优先:svg > png/webp > ico,再按 sizes 加分。 */ +function iconLinkScore(attrs: Record, resolved: URL): number { + const type = (attrs.type ?? "").toLowerCase(); + const ext = resolved.pathname.split(".").pop()?.toLowerCase() ?? ""; + const hint = type || ext; + + let score = 10; + if (hint.includes("svg")) score = 40; + else if (hint.includes("png")) score = 30; + else if (["webp", "gif", "jpg", "jpeg"].some((v) => hint.includes(v))) { + score = 25; + } else if (hint.includes("icon") || hint === "ico") score = 20; + + return score + sizeBonus(attrs.sizes); +} + +function sizeBonus(sizes: string | undefined): number { + const value = (sizes ?? "").trim().toLowerCase(); + if (!value) return 0; + if (value === "any") return 32; // 可缩放(svg) + let max = 0; + for (const match of value.matchAll(/(\d+)\s*x\s*(\d+)/g)) { + max = Math.max(max, Number(match[1]), Number(match[2])); + } + return Math.min(Math.floor(max / 10), 32); +} + +// ─── 抓取与类型嗅探 ────────────────────────────────────────────────────────── + +interface FetchedBody { + bytes: Uint8Array; + /** 小写、无参数部分的 Content-Type;缺失时为空串。 */ + contentType: string; +} + +/** HTML 错误页 / JSON 一律不认(XHTML 同样以 `]/i.test(head) && + !/]/i.test(head) + ) { + return { kind: "svg", mime: MIME_BY_KIND.svg }; + } + return null; +} + +/** 读响应体,超过上限就放弃(返回 null),避免把大文件拖进内存。 */ +async function readCapped( + res: Response, + limit: number, +): Promise { + const declared = Number(res.headers.get("content-length")); + if (Number.isFinite(declared) && declared > limit) return null; + if (!res.body) return new Uint8Array(0); + + const reader = res.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + total += value.byteLength; + if (total > limit) { + try { + await reader.cancel(); + } catch { + // 取消失败无关紧要,反正这份响应已经弃用。 + } + return null; + } + chunks.push(value); + } + + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return bytes; +} + +/** + * 单次抓取:只认 200,`redirect: "manual"` —— 3xx 视为该候选失败,绝不跟着 + * 重定向离开登记过的 origin。 + */ +async function fetchLimited( + url: string, + accept: string, + maxBytes: number, + timeoutMs: number, +): Promise { + let res: Response; + try { + res = await fetch(url, { + headers: { accept, "user-agent": USER_AGENT }, + redirect: "manual", + signal: AbortSignal.timeout(timeoutMs), + }); + } catch { + return null; + } + if (res.status !== 200) return null; + + let bytes: Uint8Array | null; + try { + bytes = await readCapped(res, maxBytes); + } catch { + return null; + } + if (!bytes) return null; + + return { + bytes, + contentType: (res.headers.get("content-type") ?? "") + .split(";")[0] + .trim() + .toLowerCase(), + }; +} + +/** 尝试时长:单个请求上限 5s,且不超过本次解析的剩余预算。 */ +function attemptTimeout(deadline: number): number { + return Math.min(FETCH_TIMEOUT_MS, deadline - Date.now()); +} + +// ─── 解析结果与 R2 缓存 ────────────────────────────────────────────────────── + +export interface CachedIcon { + status: "ok" | "none"; + bytes?: Uint8Array; + mime?: string; + /** 抓取时间(ISO),缓存新鲜度的唯一依据。 */ + fetchedAt: string; + /** 图标来源 URL(诊断用,仅存 customMetadata)。 */ + sourceUrl?: string; +} + +function cacheKey(host: string): string { + return `${ICON_CACHE_PREFIX}${host}`; +} + +async function readCache( + bucket: R2Bucket, + host: string, +): Promise { + try { + const object = await bucket.get(cacheKey(host)); + if (!object) return null; + + const meta = object.customMetadata ?? {}; + const uploaded = + object.uploaded instanceof Date ? object.uploaded.toISOString() : ""; + const fetchedAt = meta.fetchedAt ?? uploaded; + + if (meta.status === "none") return { status: "none", fetchedAt }; + if (meta.status !== "ok") return null; + + const bytes = await object.bytes(); + const mime = + meta.mime ?? + object.httpMetadata?.contentType ?? + "application/octet-stream"; + return { + status: "ok", + bytes, + mime, + fetchedAt, + sourceUrl: meta.sourceUrl || undefined, + }; + } catch { + // 缓存读取失败等同未命中:重新抓一次即可。 + return null; + } +} + +async function writeCache( + bucket: R2Bucket | undefined, + host: string, + icon: CachedIcon, +): Promise { + if (!bucket) return; + const bytes = icon.status === "ok" ? icon.bytes : undefined; + const hasImage = Boolean(bytes && icon.mime); + + const customMetadata: Record = { + status: icon.status, + fetchedAt: icon.fetchedAt, + }; + if (hasImage) { + customMetadata.mime = icon.mime as string; + customMetadata.sourceUrl = icon.sourceUrl ?? ""; + } + + try { + await bucket.put(cacheKey(host), bytes ?? new Uint8Array(0), { + httpMetadata: { + contentType: hasImage ? (icon.mime as string) : "application/json", + cacheControl: "no-store", + }, + customMetadata, + }); + } catch (err) { + // 缓存是尽力而为:写失败不影响本次回图。 + console.warn(`failed to cache icon for "${host}"`, err); + } +} + +function isFresh(icon: CachedIcon, now: number): boolean { + const at = Date.parse(icon.fetchedAt); + if (!Number.isFinite(at)) return false; + const ttl = icon.status === "ok" ? ICON_TTL_MS : ICON_MISS_TTL_MS; + return now - at < ttl; +} + +// ─── 站点注册表 ────────────────────────────────────────────────────────────── + +export interface IconRegistryEntry { + /** 注册表里登记的 origin,图标一律只从这里取。 */ + origin: string; +} + +/** host → 登记信息。 */ +export type IconRegistry = Map; + +/** + * 用本站数据建注册表:搜索引擎的 host 恒公开,链接按可见性(私有链接的 host + * 只有带会话时才入表)。库未初始化/查询失败按空注册表处理,端点回 404 而不 + * 是 500。 + */ +export async function loadIconRegistry( + env: Env, + prefix: string, + options: { includePrivate: boolean }, +): Promise { + const registry: IconRegistry = new Map(); + + const add = (rawUrl: string | null | undefined): void => { + if (!rawUrl) return; + const target = parseIconTarget(rawUrl); + if (!target) return; // 内网/非法 URL 永远进不了注册表 + if (!registry.has(target.host)) { + registry.set(target.host, { origin: target.origin }); + } + }; + + try { + const [engines, links] = await Promise.all([ + listSearchEngines(env.DB, prefix), + listLinks(env.DB, prefix), + ]); + for (const engine of engines) { + add(engine.url_template.replace("{q}", "")); + } + for (const link of links) { + if (!options.includePrivate && link.visibility !== "public") continue; + add(link.url); + } + } catch { + // 库还没建表:注册表为空,调用方回 404。 + } + + return registry; +} + +// ─── 解析与取图 ────────────────────────────────────────────────────────────── + +/** 抓 HTML + 逐个候选取图;全失败则记为「无图」。 */ +export async function resolveIcon(target: IconTarget): Promise { + const fetchedAt = new Date().toISOString(); + const deadline = Date.now() + RESOLVE_BUDGET_MS; + + const candidates: string[] = []; + const html = await fetchLimited( + `${target.origin}/`, + "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8", + HTML_MAX_BYTES, + attemptTimeout(deadline), + ); + if (html) { + candidates.push( + ...parseIconLinks( + new TextDecoder("utf-8").decode(html.bytes), + target.origin, + ), + ); + } + for (const path of ROOT_ICON_PATHS) { + candidates.push(`${target.origin}${path}`); + } + + for (const url of candidates) { + const timeout = attemptTimeout(deadline); + if (timeout <= 0) break; + + const candidate = await fetchLimited( + url, + "image/*,*/*;q=0.8", + ICON_MAX_BYTES, + timeout, + ); + if (!candidate) continue; + + const image = sniffIcon(candidate.bytes, candidate.contentType); + if (!image) continue; + + return { + status: "ok", + bytes: candidate.bytes, + mime: image.mime, + fetchedAt, + sourceUrl: url, + }; + } + + return { status: "none", fetchedAt }; +} + +/** 同一 host 的并发解析合并:一次页面加载不会对同一个站重复开抓。 */ +const inflight = new Map>(); + +function resolveAndCache(env: Env, target: IconTarget): Promise { + const existing = inflight.get(target.host); + if (existing) return existing; + + const task = resolveIcon(target) + .then(async (icon) => { + await writeCache(env.R2, target.host, icon); + return icon; + }) + .finally(() => { + inflight.delete(target.host); + }); + + inflight.set(target.host, task); + return task; +} + +/** 后台任务调度器:路由传 `ctx.waitUntil`,测试环境可以什么都不做。 */ +export type IconScheduler = (task: Promise) => void; + +/** + * 取某个 host 的图标: + * - 缓存新鲜 → 直接用; + * - 缓存过期 → 先回旧结果,后台重抓(无定时任务); + * - 没缓存 → 现抓并写缓存。R2 未绑定或读写失败时降级为「现抓现发、不缓存」。 + */ +export async function getIcon( + env: Env, + target: IconTarget, + schedule: IconScheduler, +): Promise { + const bucket = env.R2; + const cached = bucket ? await readCache(bucket, target.host) : null; + + if (cached && isFresh(cached, Date.now())) return cached; + if (cached) { + schedule(resolveAndCache(env, target).catch(() => undefined)); + return cached; + } + return resolveAndCache(env, target); +} diff --git a/worker/test/favicon.test.ts b/worker/test/favicon.test.ts new file mode 100644 index 0000000..7623e0e --- /dev/null +++ b/worker/test/favicon.test.ts @@ -0,0 +1,681 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Hono } from "hono"; +import { runMigrations } from "../src/lib/migrations-runner"; +import { assetPublicRoutes } from "../src/routes/assets"; +import { iconRoutes } from "../src/routes/icon"; +import { + ICON_CACHE_PREFIX, + loadIconRegistry, + parseIconLinks, + parseIconTarget, + sniffIcon, +} from "../src/services/favicon"; +import { signJWT } from "../src/core/auth"; +import { createOwner, insertSession } from "../src/db/queries/users"; +import { getTablePrefix, type Env } from "../src/types"; +import { MemoryR2, makeEnv, readJson, type SqliteD1 } from "./helpers"; + +// ─── 夹具 ──────────────────────────────────────────────────────────────────── + +const PNG_BYTES = new Uint8Array([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, + 0x48, 0x44, 0x52, +]); + +const ICO_BYTES = new Uint8Array([ + 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, +]); + +const SVG_BYTES = new TextEncoder().encode( + '', +); + +function htmlResponse( + html: string, + headers: Record = {}, +): Response { + return new Response(html, { + status: 200, + headers: { "content-type": "text/html; charset=utf-8", ...headers }, + }); +} + +function bytesResponse( + bytes: Uint8Array, + contentType: string, + headers: Record = {}, +): Response { + return new Response(bytes, { + status: 200, + headers: { "content-type": contentType, ...headers }, + }); +} + +const NOT_FOUND = () => new Response("", { status: 404 }); + +function makeApp(): Hono { + const app = new Hono(); + app.route("/api/icon", iconRoutes); + app.route("/assets", assetPublicRoutes); + return app; +} + +function sql(env: Env) { + return (env.DB as unknown as SqliteD1).db; +} + +function seedContent( + env: Env, + links: Array<{ id: string; url: string; visibility?: string }> = [], + engines: Array<{ id: string; urlTemplate: string }> = [], +): void { + const db = sql(env); + const now = new Date().toISOString(); + db.prepare( + "INSERT OR IGNORE INTO categories (id, name, icon, sort_order, visibility, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)", + ).run("cat-1", "Cat", null, 0, "public", now, now); + + for (const link of links) { + db.prepare( + "INSERT INTO links (id, category_id, title, url, icon_url, description, sort_order, visibility, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + ).run( + link.id, + "cat-1", + link.id, + link.url, + null, + null, + 0, + link.visibility ?? "public", + now, + now, + ); + } + + for (const engine of engines) { + db.prepare( + "INSERT INTO search_engines (id, name, url_template, icon, sort_order, is_default, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + ).run(engine.id, engine.id, engine.urlTemplate, null, 0, 0, now, now); + } +} + +/** 伪造一个有效会话 Cookie(不依赖 setup 流程与密钥)。 */ +async function makeSessionCookie(env: Env): Promise { + const prefix = getTablePrefix(env); + const userId = "user-1"; + const sid = "sid-1"; + const now = Math.floor(Date.now() / 1000); + + await createOwner(env.DB, prefix, { + id: userId, + username: "owner", + password_hash: "not-used-here", + }); + await insertSession(env.DB, prefix, { + id: sid, + user_id: userId, + expires_at: new Date((now + 3600) * 1000).toISOString(), + ip: null, + user_agent: null, + }); + const token = await signJWT( + { + typ: "access", + sub: userId, + jti: "jti-1", + sid, + iat: now, + exp: now + 3600, + }, + env.SESSION_SECRET, + ); + return `nav_session=${token}`; +} + +function iconRequest( + app: Hono, + env: Env, + target: string, + headers: Record = {}, +): Promise { + return app.request( + `/api/icon?url=${encodeURIComponent(target)}`, + { headers }, + env, + ); +} + +// ─── 目标校验(SSRF) ──────────────────────────────────────────────────────── + +describe("parseIconTarget", () => { + it("拒绝内网、回环、保留地址与非 http(s) 目标", () => { + const blocked = [ + "http://127.0.0.1/", + "http://127.0.0.1:8080/admin", + "http://localhost/", + "http://LOCALHOST/", + "http://10.0.0.5/x", + "http://172.16.0.1/", + "http://172.31.255.255/", + "http://192.168.1.1/", + "http://169.254.169.254/latest/meta-data/", + "http://100.64.0.1/", + "http://0.0.0.0/", + "http://224.0.0.1/", + "http://[::1]/", + "http://[fd00::1]/", + "http://[fe80::1]/", + "http://[::ffff:127.0.0.1]/", + "http://intranet/", + "http://printer.local/", + "http://metadata.internal/", + "http://box.home.arpa/", + "ftp://example.com/", + "file:///etc/passwd", + "https://user:pw@example.com/", + "http://example.com:8080/", + ]; + for (const target of blocked) { + expect(parseIconTarget(target), target).toBeNull(); + } + }); + + it("放行公网目标,只保留 host 与 scheme(丢掉 path/query)", () => { + expect(parseIconTarget("https://Example.COM/docs?q=1")).toEqual({ + host: "example.com", + origin: "https://example.com", + }); + expect(parseIconTarget("https://example.com:443/")?.origin).toBe( + "https://example.com", + ); + expect(parseIconTarget("http://news.ycombinator.com/item?id=1")).toEqual({ + host: "news.ycombinator.com", + origin: "http://news.ycombinator.com", + }); + expect(parseIconTarget("not a url")).toBeNull(); + }); +}); + +// ─── HTML 图标声明 ─────────────────────────────────────────────────────────── + +describe("parseIconLinks", () => { + it("按 svg > png > ico 排序,忽略跨 host 声明与 mask-icon", () => { + const html = ` + + + + + + + + `; + expect(parseIconLinks(html, "https://example.com")).toEqual([ + "https://example.com/static/icon.svg", + "https://example.com/static/icon-32.png", + "https://example.com/favicon-16.ico", + ]); + }); + + it("协议相对与 http 声明都收敛到注册表 origin,重复的只留一条", () => { + const html = + '' + + '' + + ""; + expect(parseIconLinks(html, "https://example.com")).toEqual([ + "https://example.com/a.png", + "https://example.com/b.ico", + ]); + }); + + it("没有声明时返回空数组", () => { + expect( + parseIconLinks("", "https://a.com"), + ).toEqual([]); + }); +}); + +// ─── 字节嗅探 ──────────────────────────────────────────────────────────────── + +describe("sniffIcon", () => { + it("只认真正的图片字节,HTML 错误页冒充 SVG 会被拒", () => { + const xhtml = new TextEncoder().encode( + 'not found', + ); + expect(sniffIcon(xhtml, "image/svg+xml")).toBeNull(); + expect( + sniffIcon(new TextEncoder().encode("404"), "text/html"), + ).toBeNull(); + expect(sniffIcon(new Uint8Array(0), "image/png")).toBeNull(); + expect(sniffIcon(new Uint8Array([1, 2, 3, 4]), "image/png")).toBeNull(); + }); + + it("按魔数判定类型,不看声明的 Content-Type", () => { + expect(sniffIcon(PNG_BYTES, "application/octet-stream")).toEqual({ + kind: "png", + mime: "image/png", + }); + expect(sniffIcon(ICO_BYTES, "")).toEqual({ + kind: "ico", + mime: "image/x-icon", + }); + expect(sniffIcon(SVG_BYTES, "image/svg+xml")).toEqual({ + kind: "svg", + mime: "image/svg+xml", + }); + }); +}); + +// ─── 站点注册表 ────────────────────────────────────────────────────────────── + +describe("loadIconRegistry", () => { + let env: Env; + + beforeEach(async () => { + env = makeEnv(); + await runMigrations(env); + }); + + it("只收公网 origin:内网/非法 URL 永远进不了注册表", async () => { + seedContent(env, [ + { id: "l1", url: "http://127.0.0.1:8080/admin" }, + { id: "l2", url: "https://ok.example/" }, + { id: "l3", url: "not a url" }, + { id: "l4", url: "https://secret.example/", visibility: "private" }, + ]); + const registry = await loadIconRegistry(env, getTablePrefix(env), { + includePrivate: false, + }); + expect([...registry.keys()]).toEqual(["ok.example"]); + expect(registry.get("ok.example")).toEqual({ + origin: "https://ok.example", + }); + + const withPrivate = await loadIconRegistry(env, getTablePrefix(env), { + includePrivate: true, + }); + expect([...withPrivate.keys()].sort()).toEqual([ + "ok.example", + "secret.example", + ]); + }); + + it("搜索引擎的 urlTemplate 也入表", async () => { + seedContent( + env, + [], + [{ id: "e1", urlTemplate: "https://www.google.com/search?q={q}" }], + ); + const registry = await loadIconRegistry(env, getTablePrefix(env), { + includePrivate: false, + }); + expect(registry.get("www.google.com")).toEqual({ + origin: "https://www.google.com", + }); + }); + + it("库还没初始化时退化为空注册表(不抛)", async () => { + const fresh = makeEnv(); + const registry = await loadIconRegistry(fresh, getTablePrefix(fresh), { + includePrivate: true, + }); + expect(registry.size).toBe(0); + }); +}); + +// ─── 端点 ──────────────────────────────────────────────────────────────────── + +describe("GET /api/icon", () => { + let env: Env; + let r2: MemoryR2; + let app: Hono; + let fetchMock: ReturnType; + + beforeEach(async () => { + r2 = new MemoryR2(); + env = makeEnv({ R2: r2 as unknown as R2Bucket }); + await runMigrations(env); + app = makeApp(); + fetchMock = vi.fn(); + vi.stubGlobal("fetch", fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + it("冷启动按声明取图、按真实类型回图并写入 R2,二次请求不再回源", async () => { + seedContent(env, [{ id: "l1", url: "https://example.com/docs" }]); + fetchMock.mockImplementation(async (input: string) => { + if (input === "https://example.com/") { + return htmlResponse( + '', + ); + } + if (input === "https://example.com/icon.svg") { + return bytesResponse(SVG_BYTES, "image/svg+xml", { + "x-upstream-secret": "leak", + "set-cookie": "upstream=1", + }); + } + return NOT_FOUND(); + }); + + const res = await iconRequest(app, env, "https://example.com/docs"); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/svg+xml"); + expect(res.headers.get("cache-control")).toBe("public, max-age=86400"); + expect(res.headers.get("x-content-type-options")).toBe("nosniff"); + // 上游响应头一概不透传。 + expect(res.headers.get("x-upstream-secret")).toBeNull(); + expect(res.headers.get("set-cookie")).toBeNull(); + expect(Array.from(new Uint8Array(await res.arrayBuffer()))).toEqual( + Array.from(SVG_BYTES), + ); + + // 出网一律 redirect: manual(绝不跟去别的 origin)。 + for (const call of fetchMock.mock.calls) { + expect((call[1] as RequestInit).redirect).toBe("manual"); + } + + const cached = r2.objects.get(`${ICON_CACHE_PREFIX}example.com`); + expect(cached?.customMetadata).toMatchObject({ + status: "ok", + mime: "image/svg+xml", + sourceUrl: "https://example.com/icon.svg", + }); + expect(cached?.httpMetadata?.contentType).toBe("image/svg+xml"); + + const callsAfterFirst = fetchMock.mock.calls.length; + const again = await iconRequest(app, env, "https://example.com/docs"); + expect(again.status).toBe(200); + expect(fetchMock.mock.calls.length).toBe(callsAfterFirst); + }); + + it("抓不到图标时 404 并写负缓存,二次请求不再回源", async () => { + seedContent(env, [{ id: "l1", url: "https://nope.example/" }]); + fetchMock.mockImplementation(async () => NOT_FOUND()); + + const res = await iconRequest(app, env, "https://nope.example/"); + expect(res.status).toBe(404); + expect(await readJson(res)).toEqual({ error: "icon not found" }); + expect(res.headers.get("cache-control")).toBe("public, max-age=3600"); + expect( + r2.objects.get(`${ICON_CACHE_PREFIX}nope.example`)?.customMetadata + ?.status, + ).toBe("none"); + // 1 次 HTML + 4 次根文件探测 + expect(fetchMock.mock.calls.length).toBe(5); + + const again = await iconRequest(app, env, "https://nope.example/"); + expect(again.status).toBe(404); + expect(fetchMock.mock.calls.length).toBe(5); + }); + + it("未登记的 host 直接 404,且不发起任何外部请求", async () => { + seedContent(env, [{ id: "l1", url: "https://example.com/" }]); + const res = await iconRequest(app, env, "https://unknown.example/"); + expect(res.status).toBe(404); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("只出现在私有链接里的 host:匿名 404,带会话 200", async () => { + seedContent(env, [ + { id: "l1", url: "https://secret.example/", visibility: "private" }, + ]); + fetchMock.mockImplementation(async (input: string) => { + if (input === "https://secret.example/") return htmlResponse(""); + if (input === "https://secret.example/favicon.ico") { + return bytesResponse(ICO_BYTES, "image/x-icon"); + } + return NOT_FOUND(); + }); + + const anonymous = await iconRequest(app, env, "https://secret.example/"); + expect(anonymous.status).toBe(404); + expect(fetchMock).not.toHaveBeenCalled(); + + const cookie = await makeSessionCookie(env); + const authed = await iconRequest(app, env, "https://secret.example/", { + cookie, + }); + expect(authed.status).toBe(200); + expect(authed.headers.get("content-type")).toBe("image/x-icon"); + }); + + it("搜索引擎的 host 匿名也能取图", async () => { + seedContent( + env, + [], + [{ id: "e1", urlTemplate: "https://www.google.com/search?q={q}" }], + ); + fetchMock.mockImplementation(async (input: string) => { + if (input === "https://www.google.com/") return htmlResponse(""); + if (input === "https://www.google.com/favicon.ico") { + return bytesResponse(PNG_BYTES, "image/png"); + } + return NOT_FOUND(); + }); + + const res = await iconRequest(app, env, "https://www.google.com/search?q="); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/png"); + }); + + it("跨 host 的图标声明被忽略,回落到根文件", async () => { + seedContent(env, [{ id: "l1", url: "https://cdn.example/" }]); + fetchMock.mockImplementation(async (input: string) => { + if (input === "https://cdn.example/") { + return htmlResponse( + '', + ); + } + if (input === "https://cdn.example/favicon.ico") { + return bytesResponse(ICO_BYTES, "image/x-icon"); + } + return NOT_FOUND(); + }); + + const res = await iconRequest(app, env, "https://cdn.example/"); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/x-icon"); + const urls = fetchMock.mock.calls.map((call) => String(call[0])); + expect(urls).not.toContain("https://assets.other.net/i.png"); + for (const url of urls) { + expect(url.startsWith("https://cdn.example/")).toBe(true); + } + }); + + it("声明指向 HTML 页时跳过,继续试下一个候选", async () => { + seedContent(env, [{ id: "l1", url: "https://page.example/" }]); + fetchMock.mockImplementation(async (input: string) => { + if (input === "https://page.example/") { + return htmlResponse(''); + } + if (input === "https://page.example/soft-404.png") { + return htmlResponse("not an image"); + } + if (input === "https://page.example/favicon.png") { + return bytesResponse(PNG_BYTES, "image/png"); + } + return NOT_FOUND(); + }); + + const res = await iconRequest(app, env, "https://page.example/"); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/png"); + }); + + it("超过体积上限的响应被丢弃,最终 404", async () => { + seedContent(env, [{ id: "l1", url: "https://big.example/" }]); + const huge = new Uint8Array(600 * 1024).fill(7); + fetchMock.mockImplementation( + async () => + new Response(huge, { + status: 200, + headers: { "content-type": "image/png" }, + }), + ); + + const res = await iconRequest(app, env, "https://big.example/"); + expect(res.status).toBe(404); + expect( + r2.objects.get(`${ICON_CACHE_PREFIX}big.example`)?.customMetadata?.status, + ).toBe("none"); + }); + + it("3xx 视为候选失败,绝不跟随重定向", async () => { + seedContent(env, [{ id: "l1", url: "https://redirect.example/" }]); + fetchMock.mockImplementation(async (input: string) => + input === "https://redirect.example/" + ? new Response("", { + status: 301, + headers: { location: "http://127.0.0.1/" }, + }) + : NOT_FOUND(), + ); + + const res = await iconRequest(app, env, "https://redirect.example/"); + expect(res.status).toBe(404); + for (const call of fetchMock.mock.calls) { + expect(String(call[0]).startsWith("https://redirect.example/")).toBe( + true, + ); + } + }); + + it("缓存过期时先回旧图,后台重抓并更新缓存", async () => { + seedContent(env, [{ id: "l1", url: "https://stale.example/" }]); + const staleAt = new Date(Date.now() - 40 * 24 * 60 * 60 * 1000); + r2.objects.set(`${ICON_CACHE_PREFIX}stale.example`, { + bytes: PNG_BYTES, + httpMetadata: { contentType: "image/png" }, + customMetadata: { + status: "ok", + mime: "image/png", + sourceUrl: "https://stale.example/old.png", + fetchedAt: staleAt.toISOString(), + }, + uploaded: staleAt, + }); + fetchMock.mockImplementation(async (input: string) => { + if (input === "https://stale.example/") { + return htmlResponse(''); + } + if (input === "https://stale.example/new.ico") { + return bytesResponse(ICO_BYTES, "image/x-icon"); + } + return NOT_FOUND(); + }); + + const res = await iconRequest(app, env, "https://stale.example/"); + expect(res.status).toBe(200); + // 过期也先回旧结果,页面不等重抓。 + expect(res.headers.get("content-type")).toBe("image/png"); + + await vi.waitFor(() => { + expect( + r2.objects.get(`${ICON_CACHE_PREFIX}stale.example`)?.customMetadata + ?.sourceUrl, + ).toBe("https://stale.example/new.ico"); + }); + }); + + it("同一 host 的并发请求只抓一次", async () => { + seedContent(env, [ + { id: "l1", url: "https://example.com/a" }, + { id: "l2", url: "https://example.com/b" }, + ]); + fetchMock.mockImplementation(async (input: string) => { + if (input === "https://example.com/") return htmlResponse(""); + if (input === "https://example.com/favicon.ico") { + return bytesResponse(ICO_BYTES, "image/x-icon"); + } + return NOT_FOUND(); + }); + + const [a, b] = await Promise.all([ + iconRequest(app, env, "https://example.com/a"), + iconRequest(app, env, "https://example.com/b"), + ]); + expect(a.status).toBe(200); + expect(b.status).toBe(200); + const htmlCalls = fetchMock.mock.calls.filter( + (call) => call[0] === "https://example.com/", + ); + expect(htmlCalls.length).toBe(1); + }); + + it("不读也不改写 links.icon_url(手动图标仍由前端直连)", async () => { + seedContent(env, [{ id: "l1", url: "https://manual.example/" }]); + sql(env) + .prepare("UPDATE links SET icon_url = ? WHERE id = ?") + .run("https://manual.example/hand.png", "l1"); + fetchMock.mockImplementation(async (input: string) => + input === "https://manual.example/" + ? htmlResponse('') + : input === "https://manual.example/real.ico" + ? bytesResponse(ICO_BYTES, "image/x-icon") + : NOT_FOUND(), + ); + + const res = await iconRequest(app, env, "https://manual.example/"); + expect(res.status).toBe(200); + expect( + r2.objects.get(`${ICON_CACHE_PREFIX}manual.example`)?.customMetadata + ?.sourceUrl, + ).toBe("https://manual.example/real.ico"); + const row = sql(env) + .prepare("SELECT icon_url FROM links WHERE id = ?") + .get("l1") as { icon_url: string }; + expect(row.icon_url).toBe("https://manual.example/hand.png"); + }); + + it("R2 未绑定时仍然回图(不缓存)", async () => { + const noR2 = makeEnv({ R2: undefined as unknown as R2Bucket }); + await runMigrations(noR2); + seedContent(noR2, [{ id: "l1", url: "https://example.com/" }]); + fetchMock.mockImplementation(async (input: string) => + input === "https://example.com/" + ? htmlResponse('') + : input === "https://example.com/i.png" + ? bytesResponse(PNG_BYTES, "image/png") + : NOT_FOUND(), + ); + + const res = await iconRequest(makeApp(), noR2, "https://example.com/"); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/png"); + }); + + it("缺 url / 非法 url 返回 400", async () => { + const missing = await app.request("/api/icon", {}, env); + expect(missing.status).toBe(400); + expect(await readJson(missing)).toEqual({ + error: "url must be an absolute http(s) URL", + }); + + const ftp = await app.request( + `/api/icon?url=${encodeURIComponent("ftp://example.com/")}`, + {}, + env, + ); + expect(ftp.status).toBe(400); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("内部缓存的保留前缀不经 /assets/* 公开", async () => { + r2.objects.set(`${ICON_CACHE_PREFIX}example.com`, { + bytes: PNG_BYTES, + httpMetadata: { contentType: "image/png" }, + customMetadata: { status: "ok", mime: "image/png", fetchedAt: "now" }, + }); + + const res = await app.request( + `/assets/${ICON_CACHE_PREFIX}example.com`, + {}, + env, + ); + expect(res.status).toBe(404); + }); +}); diff --git a/worker/test/helpers.ts b/worker/test/helpers.ts index 951adc3..8271985 100644 --- a/worker/test/helpers.ts +++ b/worker/test/helpers.ts @@ -69,14 +69,22 @@ export function makeEnv(overrides: Partial = {}): Env { export class MemoryR2 { readonly objects = new Map< string, - { bytes: Uint8Array; httpMetadata?: Record } + { + bytes: Uint8Array; + httpMetadata?: Record; + customMetadata?: Record; + uploaded?: Date; + } >(); readonly deleted: string[] = []; async put( key: string, value: Uint8Array | ArrayBuffer | ArrayBufferView | string, - options?: { httpMetadata?: Record }, + options?: { + httpMetadata?: Record; + customMetadata?: Record; + }, ): Promise { const bytes = typeof value === "string" @@ -90,18 +98,27 @@ export class MemoryR2 { this.objects.set(key, { bytes: new Uint8Array(bytes), httpMetadata: options?.httpMetadata, + customMetadata: options?.customMetadata, + uploaded: new Date(), }); return { key }; } + /** R2ObjectBody 的最小替身:图标缓存读 customMetadata / uploaded / bytes()。 */ async get(key: string): Promise { const object = this.objects.get(key); if (!object) return null; return { key, size: object.bytes.byteLength, + etag: "etag", + uploaded: object.uploaded ?? new Date(0), httpMetadata: object.httpMetadata, - body: object.bytes, + customMetadata: object.customMetadata, + body: new Response(object.bytes).body, + bytes: async () => new Uint8Array(object.bytes), + arrayBuffer: async () => object.bytes.slice().buffer, + text: async () => new TextDecoder().decode(object.bytes), }; } From c43eb0c3ed27cd8f02a0c994677e3f7569c9c4c6 Mon Sep 17 00:00:00 2001 From: Todos Date: Thu, 5 Nov 2026 17:10:51 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(icon):=20=E8=B7=9F=E9=9A=8F=E5=90=8C=20?= =?UTF-8?q?host=20=E5=86=85=203xx=20=E9=87=8D=E5=AE=9A=E5=90=91=EF=BC=8C?= =?UTF-8?q?=E8=B7=A8=E5=9F=9F=E4=BB=8D=E6=8B=92=E7=BB=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 302 过去的候选直接作废会让「icon 由同域跳转给出」的站(含 http→https 升级)退首字圆并写 7 天负缓存。改为自己管重定向:同一 host、默认端口、无账号密码、仅允许 http→https 升级,最多 2 跳;跨域/超跳数仍按候选失败处理,出网边界不变。缓存 sourceUrl 记最终地址,契约文档同步。 --- docs/api-contract.md | 2 +- worker/src/services/favicon.ts | 126 +++++++++++++++++++++++++-------- worker/test/favicon.test.ts | 104 ++++++++++++++++++++++++++- 3 files changed, 200 insertions(+), 32 deletions(-) diff --git a/docs/api-contract.md b/docs/api-contract.md index ce36730..f417465 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -67,7 +67,7 @@ worker 端图标解析器:服务端读目标站 HTML 的 `` - 缺失/非法(非 http/https、带账号密码、非默认端口)→ `400 {"error":"url must be an absolute http(s) URL"}`,`Cache-Control: no-store`。 - **站点注册表**:host 必须已登记在本站数据里 —— 公开链接与搜索引擎的 host 匿名可取;只出现在私有链接里的 host 需要有效会话,否则按未登记处理。未登记(含内网/回环/保留地址,它们永远不入表)→ `404 {"error":"icon not found"}`,`Cache-Control: public, max-age=3600`,**不发起任何外部请求**(本端点不是开放代理)。 - **解析顺序**(全部限定在登记的 origin):`GET https://{host}/` 读 HTML 里 `rel` 含 `icon` / `apple-touch-icon` 的 ``(svg > png > ico,`sizes` 大者优先;声明落在其他 host 的一律忽略)→ 命中即取该图 → 否则依次探测 `/favicon.ico`、`/favicon.svg`、`/favicon.png`、`/apple-touch-icon.png` → 全失败记为「无图」。 -- **出网约束**:只请求上述 origin 的根路径与固定根文件;`redirect: "manual"`,3xx 一律视为该候选失败;单次 5s 超时、一次解析总预算 8s;HTML 读 256KB、图标读 512KB 上限;带 `user-agent: nav-favicon/1`。 +- **出网约束**:只请求上述 origin 的根路径与固定根文件;`redirect: "manual"` 自己管重定向 —— **只跟随同一个 host 内的 3xx(最多 2 跳;允许 http→https 升级,禁止降级到 http)**,`Location` 落到别的 host(含子域、CDN)、非默认端口、带账号密码、解析失败或超出跳数,一律视为该候选失败(不扩大出网边界);单次 5s 超时、一次解析总预算 8s;HTML 读 256KB、图标读 512KB 上限;带 `user-agent: nav-favicon/1`。 - 成功 `200`:图标原始字节,`content-type` 为按魔数嗅探出的真实类型(`image/png` / `image/jpeg` / `image/webp` / `image/gif` / `image/svg+xml` / `image/x-icon`),`cache-control: public, max-age=86400`,`x-content-type-options: nosniff`;**不透传任何上游响应头**。 - 无图标 `404 {"error":"icon not found"}` + `cache-control: public, max-age=3600`。 - **缓存**:R2 对象 `_cache/favicons/{host}`(保留前缀,不经 `GET /assets/*` 公开),`customMetadata` 记 `{status:"ok"|"none", fetchedAt, mime?, sourceUrl?}`。「有图」30 天、「无图」7 天视为新鲜;过期时先回旧结果、后台重抓(`waitUntil`),**不用定时任务**;同一 host 的并发解析合并为一次。R2 未绑定或读写失败时降级为「现抓现发、不缓存」。 diff --git a/worker/src/services/favicon.ts b/worker/src/services/favicon.ts index 07324c7..1cf7c28 100644 --- a/worker/src/services/favicon.ts +++ b/worker/src/services/favicon.ts @@ -8,7 +8,8 @@ * `_cache/favicons/{host}` 下,新鲜度写在对象的 customMetadata.fetchedAt 里。 * 因此本功能不产生 D1 迁移、不新增绑定,也不需要定时任务刷新。 * - 出网边界:只访问注册表(本站链接与搜索引擎的 host)登记过的 origin, - * 且只碰 origin 根路径与四个固定根文件;任何重定向一律不跟随。 + * 且只碰 origin 根路径与四个固定根文件;重定向只在同一个 host 内最多跟 2 跳 + * (允许 http→https 升级),跨域/超跳数一律当该候选失败。 */ import type { Env } from "../types"; import { listLinks, listSearchEngines } from "../db/queries/content"; @@ -35,6 +36,9 @@ const ICON_MAX_BYTES = 512 * 1024; const FETCH_TIMEOUT_MS = 5000; const RESOLVE_BUDGET_MS = 8000; +/** 同一个 origin 内最多跟随几跳重定向(302 多来自 UA/地区差异)。 */ +const MAX_REDIRECTS = 2; + /** 站点的 HTML 里最多认几个 `` 声明。 */ const MAX_DECLARED_ICONS = 3; @@ -248,6 +252,8 @@ interface FetchedBody { bytes: Uint8Array; /** 小写、无参数部分的 Content-Type;缺失时为空串。 */ contentType: string; + /** 跟随同域重定向后的最终 URL(用作 sourceUrl 诊断)。 */ + finalUrl: string; } /** HTML 错误页 / JSON 一律不认(XHTML 同样以 ` { - let res: Response; +export function sameHostRedirect( + location: string | null, + currentUrl: string, + allowedHost: string, +): string | null { + if (!location) return null; + let next: URL; try { - res = await fetch(url, { - headers: { accept, "user-agent": USER_AGENT }, - redirect: "manual", - signal: AbortSignal.timeout(timeoutMs), - }); + next = new URL(location, currentUrl); } catch { return null; } - if (res.status !== 200) return null; + if (next.protocol !== "http:" && next.protocol !== "https:") return null; + if (next.hostname.toLowerCase() !== allowedHost) return null; + if (next.port !== "" && next.port !== "80" && next.port !== "443") { + return null; + } + if (next.username || next.password) return null; - let bytes: Uint8Array | null; + // 不允许从 https 降回 http(明文)。 + let currentSecure = false; try { - bytes = await readCapped(res, maxBytes); + currentSecure = new URL(currentUrl).protocol === "https:"; } catch { return null; } - if (!bytes) return null; - - return { - bytes, - contentType: (res.headers.get("content-type") ?? "") - .split(";")[0] - .trim() - .toLowerCase(), - }; + if (currentSecure && next.protocol !== "https:") return null; + + return next.toString(); +} + +/** + * 单次抓取:`redirect: "manual"` 自己管重定向 —— 只有 Location 仍在 `allowedHost` + * 内才跟(最多 {@link MAX_REDIRECTS} 跳),跨域 3xx 当该候选失败。最终只认 200。 + */ +async function fetchLimited( + url: string, + accept: string, + maxBytes: number, + timeoutMs: number, + allowedHost: string, +): Promise { + const deadline = Date.now() + timeoutMs; + let current = url; + + for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) { + const remaining = Math.min(FETCH_TIMEOUT_MS, deadline - Date.now()); + if (remaining <= 0) return null; + + let res: Response; + try { + res = await fetch(current, { + headers: { accept, "user-agent": USER_AGENT }, + redirect: "manual", + signal: AbortSignal.timeout(remaining), + }); + } catch { + return null; + } + + if (REDIRECT_STATUSES.has(res.status)) { + const next = sameHostRedirect( + res.headers.get("location"), + current, + allowedHost, + ); + if (!next || hop === MAX_REDIRECTS) return null; + current = next; + continue; + } + if (res.status !== 200) return null; + + let bytes: Uint8Array | null; + try { + bytes = await readCapped(res, maxBytes); + } catch { + return null; + } + if (!bytes) return null; + + return { + bytes, + contentType: (res.headers.get("content-type") ?? "") + .split(";")[0] + .trim() + .toLowerCase(), + finalUrl: current, + }; + } + + return null; } /** 尝试时长:单个请求上限 5s,且不超过本次解析的剩余预算。 */ @@ -521,6 +588,7 @@ export async function resolveIcon(target: IconTarget): Promise { "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8", HTML_MAX_BYTES, attemptTimeout(deadline), + target.host, ); if (html) { candidates.push( @@ -543,6 +611,7 @@ export async function resolveIcon(target: IconTarget): Promise { "image/*,*/*;q=0.8", ICON_MAX_BYTES, timeout, + target.host, ); if (!candidate) continue; @@ -554,7 +623,8 @@ export async function resolveIcon(target: IconTarget): Promise { bytes: candidate.bytes, mime: image.mime, fetchedAt, - sourceUrl: url, + // 记跟随同域重定向后的最终地址,方便排查。 + sourceUrl: candidate.finalUrl, }; } diff --git a/worker/test/favicon.test.ts b/worker/test/favicon.test.ts index 7623e0e..c9c4398 100644 --- a/worker/test/favicon.test.ts +++ b/worker/test/favicon.test.ts @@ -8,6 +8,7 @@ import { loadIconRegistry, parseIconLinks, parseIconTarget, + sameHostRedirect, sniffIcon, } from "../src/services/favicon"; import { signJWT } from "../src/core/auth"; @@ -524,13 +525,13 @@ describe("GET /api/icon", () => { ).toBe("none"); }); - it("3xx 视为候选失败,绝不跟随重定向", async () => { + it("跨域 3xx 不跟随:Location 落到别的 host 就当该候选失败", async () => { seedContent(env, [{ id: "l1", url: "https://redirect.example/" }]); fetchMock.mockImplementation(async (input: string) => input === "https://redirect.example/" ? new Response("", { - status: 301, - headers: { location: "http://127.0.0.1/" }, + status: 302, + headers: { location: "https://cdn.elsewhere.net/favicon.ico" }, }) : NOT_FOUND(), ); @@ -544,6 +545,103 @@ describe("GET /api/icon", () => { } }); + it("同域 302 跟随:Location 仍在同一 origin 时跟过去取图", async () => { + seedContent(env, [{ id: "l1", url: "https://www.engine.example/" }]); + fetchMock.mockImplementation(async (input: string) => { + if (input === "https://www.engine.example/") { + return new Response("", { + status: 302, + headers: { location: "/home?hl=zh-CN" }, + }); + } + if (input === "https://www.engine.example/home?hl=zh-CN") { + return htmlResponse(""); + } + if (input === "https://www.engine.example/favicon.ico") { + return new Response("", { + status: 302, + headers: { location: "https://www.engine.example/v2/favicon.ico" }, + }); + } + if (input === "https://www.engine.example/v2/favicon.ico") { + return bytesResponse(ICO_BYTES, "image/x-icon"); + } + return NOT_FOUND(); + }); + + const res = await iconRequest(app, env, "https://www.engine.example/"); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/x-icon"); + // 落缓存的来源记的是跟随重定向后的最终地址。 + expect( + r2.objects.get(`${ICON_CACHE_PREFIX}www.engine.example`)?.customMetadata + ?.sourceUrl, + ).toBe("https://www.engine.example/v2/favicon.ico"); + }); + + it("同域重定向超过 2 跳就停,不再继续跟", async () => { + seedContent(env, [{ id: "l1", url: "https://loop.example/" }]); + fetchMock.mockImplementation(async (input: string) => { + const hop = Number(new URL(String(input)).searchParams.get("hop") ?? 0); + return new Response("", { + status: 302, + headers: { + location: String(input).includes("?") + ? String(input) + : `${input}?hop=${hop + 1}`, + }, + }); + }); + + const res = await iconRequest(app, env, "https://loop.example/"); + expect(res.status).toBe(404); + // 每个候选最多 1 + 2 次请求,不会无限循环。 + expect(fetchMock.mock.calls.length).toBeLessThanOrEqual(5 * 3); + }); + + it("重定向目标只放行同一个 host:相对路径放行,跨域 / 降级 http 拒绝", () => { + const current = "https://example.com/favicon.ico"; + expect(sameHostRedirect("/next/icon.png", current, "example.com")).toBe( + "https://example.com/next/icon.png", + ); + // http → https 升级允许 + expect( + sameHostRedirect( + "https://example.com/icon.ico", + "http://example.com/favicon.ico", + "example.com", + ), + ).toBe("https://example.com/icon.ico"); + // https → http 降级拒绝 + expect( + sameHostRedirect("http://example.com/icon.ico", current, "example.com"), + ).toBeNull(); + // 跨 host(含子域 / CDN)一律拒绝 + expect( + sameHostRedirect( + "https://other.example/icon.png", + current, + "example.com", + ), + ).toBeNull(); + expect( + sameHostRedirect( + "https://cdn.example.com/icon.png", + current, + "example.com", + ), + ).toBeNull(); + // 非默认端口、缺 location + expect( + sameHostRedirect( + "https://example.com:8443/i.png", + current, + "example.com", + ), + ).toBeNull(); + expect(sameHostRedirect(null, current, "example.com")).toBeNull(); + }); + it("缓存过期时先回旧图,后台重抓并更新缓存", async () => { seedContent(env, [{ id: "l1", url: "https://stale.example/" }]); const staleAt = new Date(Date.now() - 40 * 24 * 60 * 60 * 1000); From 73535c2cca88b73fed99d1a7d1ec2629dee702d0 Mon Sep 17 00:00:00 2001 From: Todos Date: Thu, 5 Nov 2026 18:16:57 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix(icon):=20=E4=BF=AE=E6=AD=A3=E8=AF=84?= =?UTF-8?q?=E5=AE=A1=E6=8C=87=E5=87=BA=E7=9A=84=E5=8F=AF=E8=A7=81=E6=80=A7?= =?UTF-8?q?=E3=80=81=E7=BC=93=E5=AD=98=E5=9B=9E=E9=80=80=E4=B8=8E=E5=A4=B4?= =?UTF-8?q?=E9=83=A8=E9=98=B2=E6=8A=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 注册表按「更严一方」过滤:私有分类下的 public 链接对匿名不再暴露(与 /api/public 同口径),同一 host 优先 https。 - 后台刷新失败不再把在用的好图改写成负缓存,只顺延 fetchedAt。 - 图标声明的相对路径按跟随重定向后的 HTML 真实地址解析。 - 主机名末尾根点先规范化,`localhost.` 之类不再绕过内网黑名单。 - 图标响应加 `content-security-policy: default-src 'none'; sandbox`(第三方 SVG 不做本站脚本)与 `vary: Cookie`(会话相关结果不被共享缓存复用)。 - 收紧跳数上限用例断言;契约文档同步 400/404 语义与上述头部。 --- docs/api-contract.md | 10 +- worker/src/routes/icon.ts | 15 +++ worker/src/services/favicon.ts | 82 +++++++++--- worker/test/favicon.test.ts | 228 +++++++++++++++++++++++++++++++-- 4 files changed, 302 insertions(+), 33 deletions(-) diff --git a/docs/api-contract.md b/docs/api-contract.md index f417465..6ef1503 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -64,13 +64,15 @@ worker 端图标解析器:服务端读目标站 HTML 的 `` 声明、探测根文件,抓到后缓存并**直接回图字节**。无鉴权(公共页未登录也要显示图标)。前端在 `iconUrl` 非空时直接用它、不请求本端点;首字圆仍是最终兜底。 - 入参 `url`:必填,`encodeURIComponent` 后的绝对 URL(链接的 `url` 或搜索引擎 `urlTemplate` 去掉 `{q}`)。服务端只用它的 host 与 scheme,**不使用 path/query**。 -- 缺失/非法(非 http/https、带账号密码、非默认端口)→ `400 {"error":"url must be an absolute http(s) URL"}`,`Cache-Control: no-store`。 -- **站点注册表**:host 必须已登记在本站数据里 —— 公开链接与搜索引擎的 host 匿名可取;只出现在私有链接里的 host 需要有效会话,否则按未登记处理。未登记(含内网/回环/保留地址,它们永远不入表)→ `404 {"error":"icon not found"}`,`Cache-Control: public, max-age=3600`,**不发起任何外部请求**(本端点不是开放代理)。 -- **解析顺序**(全部限定在登记的 origin):`GET https://{host}/` 读 HTML 里 `rel` 含 `icon` / `apple-touch-icon` 的 ``(svg > png > ico,`sizes` 大者优先;声明落在其他 host 的一律忽略)→ 命中即取该图 → 否则依次探测 `/favicon.ico`、`/favicon.svg`、`/favicon.png`、`/apple-touch-icon.png` → 全失败记为「无图」。 +- 缺失/非法(非 http/https、带账号密码、非默认端口、**内网/回环/保留地址**)→ `400 {"error":"url must be an absolute http(s) URL"}`,`Cache-Control: no-store` —— 这类目标在参数校验阶段就被拒,不进注册表。 +- **站点注册表**:host 必须已登记在本站数据里 —— 公开链接与搜索引擎的 host 匿名可取;链接的可见性取**更严一方**(私有链接、或私有分类下的 public 链接,都需要有效会话),否则按未登记处理。未登记 → `404 {"error":"icon not found"}`,`Cache-Control: public, max-age=3600`,**不发起任何外部请求**(本端点不是开放代理)。同一 host 有多条链接时注册表优先 https。 +- **解析顺序**(全部限定在登记的 origin):`GET https://{host}/` 读 HTML 里 `rel` 含 `icon` / `apple-touch-icon` 的 ``(svg > png > ico,`sizes` 大者优先;相对路径按该 HTML 的真实地址解,含跟随重定向后的路径;声明落在其他 host 的一律忽略)→ 命中即取该图 → 否则依次探测 `/favicon.ico`、`/favicon.svg`、`/favicon.png`、`/apple-touch-icon.png` → 全失败记为「无图」。 - **出网约束**:只请求上述 origin 的根路径与固定根文件;`redirect: "manual"` 自己管重定向 —— **只跟随同一个 host 内的 3xx(最多 2 跳;允许 http→https 升级,禁止降级到 http)**,`Location` 落到别的 host(含子域、CDN)、非默认端口、带账号密码、解析失败或超出跳数,一律视为该候选失败(不扩大出网边界);单次 5s 超时、一次解析总预算 8s;HTML 读 256KB、图标读 512KB 上限;带 `user-agent: nav-favicon/1`。 - 成功 `200`:图标原始字节,`content-type` 为按魔数嗅探出的真实类型(`image/png` / `image/jpeg` / `image/webp` / `image/gif` / `image/svg+xml` / `image/x-icon`),`cache-control: public, max-age=86400`,`x-content-type-options: nosniff`;**不透传任何上游响应头**。 +- 成功与失败响应均带 `vary: Cookie`:同一 URL 匿名可能是 404、带会话才是 200,共享缓存不得把会话结果回给匿名访客。 +- **SVG 防护**:第三方 SVG 可能带 `', + ); + fetchMock.mockImplementation(async (input: string) => { + if (input === "https://evil.example/") return htmlResponse(""); + if (input === "https://evil.example/favicon.svg") { + return bytesResponse(sneaky, "image/svg+xml"); + } + return NOT_FOUND(); + }); + + const res = await iconRequest(app, env, "https://evil.example/"); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toBe("image/svg+xml"); + expect(res.headers.get("content-security-policy")).toBe( + "default-src 'none'; sandbox", + ); + expect(res.headers.get("x-content-type-options")).toBe("nosniff"); + }); + it("同域 302 跟随:Location 仍在同一 origin 时跟过去取图", async () => { seedContent(env, [{ id: "l1", url: "https://www.engine.example/" }]); fetchMock.mockImplementation(async (input: string) => { @@ -579,24 +737,27 @@ describe("GET /api/icon", () => { ).toBe("https://www.engine.example/v2/favicon.ico"); }); - it("同域重定向超过 2 跳就停,不再继续跟", async () => { + it("同域重定向最多跟 2 跳,第 3 次响应就停", async () => { seedContent(env, [{ id: "l1", url: "https://loop.example/" }]); fetchMock.mockImplementation(async (input: string) => { const hop = Number(new URL(String(input)).searchParams.get("hop") ?? 0); return new Response("", { status: 302, - headers: { - location: String(input).includes("?") - ? String(input) - : `${input}?hop=${hop + 1}`, - }, + headers: { location: `https://loop.example/?hop=${hop + 1}` }, }); }); const res = await iconRequest(app, env, "https://loop.example/"); expect(res.status).toBe(404); - // 每个候选最多 1 + 2 次请求,不会无限循环。 - expect(fetchMock.mock.calls.length).toBeLessThanOrEqual(5 * 3); + + // 每个候选恰好 1 次原始请求 + 2 跳 = 3 次;共 1 个 HTML + 4 个根文件。 + expect(fetchMock.mock.calls.length).toBe(5 * 3); + const urls = fetchMock.mock.calls.map((call) => String(call[0])); + // 第 4 次(hop=3)从未发生,说明跳数上限确实生效。 + expect(urls.some((url) => url.includes("hop=3"))).toBe(false); + expect(urls.filter((url) => url === "https://loop.example/")).toHaveLength( + 1, + ); }); it("重定向目标只放行同一个 host:相对路径放行,跨域 / 降级 http 拒绝", () => { @@ -679,6 +840,47 @@ describe("GET /api/icon", () => { }); }); + it("后台刷新失败不会把在用的图标改写成负缓存", async () => { + seedContent(env, [{ id: "l1", url: "https://flaky.example/" }]); + const staleAt = new Date(Date.now() - 40 * 24 * 60 * 60 * 1000); + const key = `${ICON_CACHE_PREFIX}flaky.example`; + r2.objects.set(key, { + bytes: PNG_BYTES, + httpMetadata: { contentType: "image/png" }, + customMetadata: { + status: "ok", + mime: "image/png", + sourceUrl: "https://flaky.example/old.png", + fetchedAt: staleAt.toISOString(), + }, + uploaded: staleAt, + }); + // 站点这会儿挂了:所有候选都 503。 + fetchMock.mockImplementation(async () => new Response("", { status: 503 })); + + const first = await iconRequest(app, env, "https://flaky.example/"); + expect(first.status).toBe(200); + + // 后台刷新跑完:抓取失败,但缓存必须还是那张好图(不是 none)。 + await vi.waitFor(() => { + expect(r2.objects.get(key)?.customMetadata?.fetchedAt).not.toBe( + staleAt.toISOString(), + ); + }); + const cached = r2.objects.get(key); + expect(cached?.customMetadata?.status).toBe("ok"); + expect(cached?.customMetadata?.mime).toBe("image/png"); + expect(cached?.customMetadata?.sourceUrl).toBe( + "https://flaky.example/old.png", + ); + expect(Array.from(cached?.bytes ?? [])).toEqual(Array.from(PNG_BYTES)); + + // 紧随其后的请求仍然拿得到图,而不是 404。 + const second = await iconRequest(app, env, "https://flaky.example/"); + expect(second.status).toBe(200); + expect(second.headers.get("content-type")).toBe("image/png"); + }); + it("同一 host 的并发请求只抓一次", async () => { seedContent(env, [ { id: "l1", url: "https://example.com/a" },