diff --git a/docs/api-contract.md b/docs/api-contract.md index bc1f683..6ef1503 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -60,6 +60,21 @@ - 回源失败时回退到昨日缓存图(同样 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 匿名可取;链接的可见性取**更严一方**(私有链接、或私有分类下的 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) => { + 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 跳,第 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: `https://loop.example/?hop=${hop + 1}` }, + }); + }); + + const res = await iconRequest(app, env, "https://loop.example/"); + expect(res.status).toBe(404); + + // 每个候选恰好 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 拒绝", () => { + 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); + 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("后台刷新失败不会把在用的图标改写成负缓存", 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" }, + { 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), }; }