diff --git a/scripts/gen-favicon.mjs b/scripts/gen-favicon.mjs new file mode 100644 index 0000000000..3c250b1a20 --- /dev/null +++ b/scripts/gen-favicon.mjs @@ -0,0 +1,138 @@ +#!/usr/bin/env node +// #4830: deterministic favicon generator. Draws the panel brand mark (∞ on an +// accent-blue rounded square, 4x4 supersampled), encodes 16px + 32px PNGs into +// one .ico container, and writes src/web/favicon.ts — the base64 const served +// at GET /favicon.ico (admin.ts) and declared by the panel head (page.ts). +// Re-run after changing the drawing below; output is deterministic (no +// timestamps, zlib level fixed). Node builtins only — no dependencies. +import { deflateSync } from "node:zlib"; +import { writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const ACCENT = [0x21, 0x85, 0xd0]; // styles.ts --accent (light theme, #2185d0) +const GLYPH = [0xff, 0xff, 0xff]; +const RING_R = 0.155; // loop radius, unit space +const RING_HW = 0.052; // ring half-stroke width +const RING_CX = [0.36, 0.64]; // loop centers (y is 0.5) +const CORNER_R = 0.17; // badge corner radius +const SS = 4; // supersamples per side + +function roundedRectInside(u, v) { + const qx = Math.abs(u - 0.5) - (0.5 - CORNER_R); + const qy = Math.abs(v - 0.5) - (0.5 - CORNER_R); + const ox = Math.max(qx, 0); + const oy = Math.max(qy, 0); + return Math.hypot(ox, oy) + Math.min(Math.max(qx, qy), 0) - CORNER_R <= 0; +} + +function sampleColor(u, v) { + if (!roundedRectInside(u, v)) return [0, 0, 0, 0]; + let onGlyph = false; + for (const cx of RING_CX) { + if (Math.abs(Math.hypot(u - cx, v - 0.5) - RING_R) <= RING_HW) { onGlyph = true; break; } + } + const c = onGlyph ? GLYPH : ACCENT; + return [c[0], c[1], c[2], 255]; +} + +function render(size) { + const px = Buffer.alloc(size * size * 4); + const step = 1 / size; + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + let r = 0, g = 0, b = 0, a = 0; + for (let sy = 0; sy < SS; sy++) { + for (let sx = 0; sx < SS; sx++) { + const u = (x + (sx + 0.5) / SS) * step; + const v = (y + (sy + 0.5) / SS) * step; + const s = sampleColor(u, v); + r += s[0]; g += s[1]; b += s[2]; a += s[3]; + } + } + const n = SS * SS; + const i = (y * size + x) * 4; + px[i] = Math.round(r / n); + px[i + 1] = Math.round(g / n); + px[i + 2] = Math.round(b / n); + px[i + 3] = Math.round(a / n); + } + } + return px; +} + +const CRC_TABLE = new Uint32Array(256).map((_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); + +function crc32(buf) { + let c = 0xffffffff; + for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + +function pngChunk(type, data) { + const len = Buffer.alloc(4); + len.writeUInt32BE(data.length, 0); + const body = Buffer.concat([Buffer.from(type, "ascii"), data]); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(body), 0); + return Buffer.concat([len, body, crc]); +} + +function encodePng(size, rgba) { + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(size, 0); + ihdr.writeUInt32BE(size, 4); + ihdr[8] = 8; // bit depth + ihdr[9] = 6; // color type RGBA + const rowBytes = size * 4; + const raw = Buffer.alloc(size * (rowBytes + 1)); + for (let y = 0; y < size; y++) { + raw[y * (rowBytes + 1)] = 0; // filter type none + rgba.copy(raw, y * (rowBytes + 1) + 1, y * rowBytes, (y + 1) * rowBytes); + } + return Buffer.concat([PNG_SIG, pngChunk("IHDR", ihdr), pngChunk("IDAT", deflateSync(raw, { level: 9 })), pngChunk("IEND", Buffer.alloc(0))]); +} + +function encodeIco(entries) { + const header = Buffer.alloc(6); + header.writeUInt16LE(0, 0); // reserved + header.writeUInt16LE(1, 2); // type: icon + header.writeUInt16LE(entries.length, 4); + const dataStart = 6 + entries.length * 16; + let offset = dataStart; + const dirs = []; + const payloads = []; + for (const e of entries) { + const d = Buffer.alloc(16); + d[0] = e.size >= 256 ? 0 : e.size; + d[1] = e.size >= 256 ? 0 : e.size; + d.writeUInt16LE(1, 4); // planes + d.writeUInt16LE(32, 6); // bit count + d.writeUInt32LE(e.png.length, 8); + d.writeUInt32LE(offset, 12); + offset += e.png.length; + dirs.push(d); + payloads.push(e.png); + } + return Buffer.concat([header, ...dirs, ...payloads]); +} + +const sizes = [16, 32]; +const entries = sizes.map((size) => ({ size, png: encodePng(size, render(size)) })); +const ico = encodeIco(entries); +const base64 = ico.toString("base64"); + +const out = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "src", "web", "favicon.ts"); +writeFileSync(out, `// #4830: generated by scripts/gen-favicon.mjs — re-run that script after +// changing its drawing code, do not edit this constant by hand. Served at +// GET /favicon.ico (src/server/admin.ts) and declared by the panel head +// (src/web/page.ts). +export const FAVICON_ICO_BASE64 = "${base64}"; +`); +console.log(`wrote ${out}: ico=${ico.length}B base64=${base64.length} chars (${entries.map((e) => `${e.size}px/${e.png.length}B`).join(", ")})`); diff --git a/src/server/admin.ts b/src/server/admin.ts index bd0fb963e9..3e64cf0a53 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -37,6 +37,7 @@ import { handleBlogAssetGet, handleBlogGet } from "../web/blogfeed.js"; import { buildSessionReportMd, buildSessionReportSvg } from "../web/report.js"; import { queryLogLines } from "../web/logs-query.js"; import { buildDiagnostics } from "../web/diagnostics.js"; +import { FAVICON_ICO_BASE64 } from "../web/favicon.js"; import { ackSplitBrainContest, storageStatusWire } from "../storage/runtime-status.js"; import { snapshotShadowStatusWire } from "../server/snapshot-render.js"; import { attributionStatusWire } from "./attribution-status.js"; @@ -258,17 +259,17 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv res.end(JSON.stringify({ ok: true, upstream: opts.upstream })); return; } - // #3536: browsers probing the proxy origin for a favicon (the dsh desktop - // settings panel frames /__bili/ and the frame fires GET /favicon.ico at - // the ORIGIN ROOT) must be answered locally with 204 — falling through to - // the relay would rewrite the host onto the configured upstream, burning a - // request there and logging a 403 for a static asset no model client ever - // asks for. The panel page itself also declares an empty icon (page.ts) so - // well-behaved browsers never send the probe at all; this is the backstop - // for browsers/timings that still do (probe before redirect, direct visits). + // #3536/#4830: browsers probing the proxy origin for a favicon (the dsh + // desktop settings panel frames /__bili/ and the frame fires GET + // /favicon.ico at the ORIGIN ROOT) must be answered locally — falling + // through to the relay rewrites the host onto the configured upstream, + // burning a request there and logging timeouts for a static asset no model + // client ever asks for. The panel page declares the bundled icon (page.ts) + // so well-behaved browsers fetch it once and cache it; this route is what + // serves those bytes (plus the backstop for probes that skip the page). if (req.method === "GET" && req.url?.split("?", 2)[0] === "/favicon.ico") { - res.writeHead(204); - res.end(); + res.writeHead(200, { "content-type": "image/x-icon", "cache-control": "no-cache" }); + res.end(Buffer.from(FAVICON_ICO_BASE64, "base64")); return; } if (req.method === "GET" && req.url === "/__bili/health") { diff --git a/src/web/favicon.ts b/src/web/favicon.ts new file mode 100644 index 0000000000..17f35d0189 --- /dev/null +++ b/src/web/favicon.ts @@ -0,0 +1,5 @@ +// #4830: generated by scripts/gen-favicon.mjs — re-run that script after +// changing its drawing code, do not edit this constant by hand. Served at +// GET /favicon.ico (src/server/admin.ts) and declared by the panel head +// (src/web/page.ts). +export const FAVICON_ICO_BASE64 = "AAABAAIAEBAAAAEAIAC8AAAAJgAAACAgAAABACAAOwEAAOIAAACJUE5HDQoaCgAAAA1JSERSAAAAEAAAABAIBgAAAB/z/2EAAACDSURBVHjaY2Di4BUQj+5fr9h64T8pGKQHpJeBHM3IhjCQqxmGqW+Afu/l/5FL7vz3nnMTLgZig8RAcngNKNn86D8yuPriGxgjA5AarAaAbIFpAimad+oVXBOIDRKDGYbsOrgBEw69wJCEAXRLQGqpbwDFXqA4EKkSjQOTEinOTJRmZwAbuKrrLI8EOwAAAABJRU5ErkJggolQTkcNChoKAAAADUlIRFIAAAAgAAAAIAgGAAAAc3p69AAAAQJJREFUeNpjYIACFkEpBdHgpvnytYffK7Ze+E8LDDIbZAfILgZkwGPkl0BLi7E5BGQn3Of0tBzZEeCQAAUJvS2HYZDdDAPhe+RQYBgoy2F41AFDwwFpq+//n3DoBRyD+OSoIdkBkUvu/H/84ed/bAAkDrIEhPGpAZlBlgNKNj/6Ty0AMoskB9hOufb/4/c/GL458fAzTt/iUwMyC2Qm0Q5Yc/EtigFNu54SDB10X4L0IAOQmUQ7ANn3uDQiqwGxCXkElxqsDkAG2BIRKDjRAbYgBulFBkPHAQMeBQOeCAc8Gw54QTQoiuJBURmNtgdGhgMGvFk+4B2TAe+aDXjndKC75wCG5a0fNzrnNwAAAABJRU5ErkJggg=="; diff --git a/src/web/page.ts b/src/web/page.ts index 35e6d7bf8a..0f1443275d 100644 --- a/src/web/page.ts +++ b/src/web/page.ts @@ -18,11 +18,12 @@ export function renderPage(origin: string, version: string, embed = false, theme const caPath = rootCaPath(); const caPathEsc = escapeHtml(caPath); const caReady = existsSync(caPath); - // #3536: declare an EMPTY icon so browsers (dsh desktop's Electron frame - // included) never fall back to probing /favicon.ico on the proxy origin — - // that request used to miss every admin route and get relayed onto the - // configured upstream (a wasted request + 403 noise in the log). - return `billion-context + // #3536/#4830: declare the bundled icon explicitly so browsers (dsh + // desktop's Electron frame included) fetch it from /favicon.ico — served + // locally by admin.ts — instead of falling back to a bare origin probe + // that used to miss every admin route and get relayed onto the configured + // upstream (a wasted request + timeout noise in the log). + return `billion-context
billion-contextv${version}
diff --git a/tests/issue3536-favicon-local.test.ts b/tests/issue3536-favicon-local.test.ts index fae7e08bb9..64250b43ed 100644 --- a/tests/issue3536-favicon-local.test.ts +++ b/tests/issue3536-favicon-local.test.ts @@ -11,15 +11,17 @@ import type { ProxyOptions } from "../src/config.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; import { renderPage } from "../src/web/page.ts"; +import { FAVICON_ICO_BASE64 } from "../src/web/favicon.ts"; import { rmrf } from "./tmp-rm.ts"; -// #3536: the dsh desktop settings panel frames /__bili/ and the browser fires -// GET /favicon.ico at the ORIGIN ROOT — which matched no admin route and fell -// through the relay onto the configured upstream (a wasted request + 403 noise -// in the log, upstream host visible in the panel's network tab). Two halves: -// the panel page declares an empty icon so well-behaved browsers never probe, -// and the proxy answers the probe locally (204) as a backstop — while every -// OTHER unknown path keeps the documented relay fallthrough. +// #3536/#4830: browsers probe the proxy origin for /favicon.ico (the dsh +// desktop settings panel frames /__bili/ and the frame fires the probe at +// the ORIGIN ROOT). Unanswered, the probe falls through the relay onto the +// configured upstream — a wasted request plus 403/timeout noise in the log +// for a static asset no model client ever asks for. Three halves: the panel +// page declares the bundled icon explicitly (page.ts), the proxy serves the +// bundled .ico bytes locally at /favicon.ico as the backstop (admin.ts), and +// every OTHER unknown path keeps the documented relay fallthrough. async function waitReady(port: number): Promise { for (let i = 0; i < 200; i++) { @@ -35,25 +37,26 @@ function close(server: http.Server): Promise { return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); } -function get(port: number, reqPath: string): Promise<{ status: number; body: string }> { - const { promise, resolve, reject } = Promise.withResolvers<{ status: number; body: string }>(); - const req = http.request({ host: "127.0.0.1", port, path: reqPath, signal: AbortSignal.timeout(5000) }, (res) => { - let body = ""; - res.on("data", (c: Buffer) => { body += c.toString("utf8"); }); - res.on("end", () => resolve({ status: res.statusCode ?? 0, body })); - }); - req.once("error", reject); - req.end(); - return promise; +function get(port: number, reqPath: string, init?: RequestInit): Promise<{ status: number; contentType: string | null; cacheControl: string | null; buf: Buffer }> { + return fetch(`http://127.0.0.1:${port}${reqPath}`, { ...init, signal: AbortSignal.timeout(5000) }).then(async (res) => ({ + status: res.status, + contentType: res.headers.get("content-type"), + cacheControl: res.headers.get("cache-control"), + buf: Buffer.from(await res.arrayBuffer()), + })); } /** Mock upstream shaped like the incident's Anthropic 403; records every hit. */ function startMockUpstream(): Promise<{ origin: string; hits: string[]; close: () => Promise }> { const hits: string[] = []; const server = http.createServer((req, res) => { - hits.push(`${req.method} ${req.url}`); - res.writeHead(403, { "content-type": "application/json" }); - res.end(JSON.stringify({ error: { type: "forbidden", message: "Request not allowed" } })); + let body = ""; + req.on("data", (c: Buffer) => { body += c.toString("utf8"); }); + req.on("end", () => { + hits.push(`${req.method} ${req.url}`); + res.writeHead(403, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: { type: "forbidden", message: "Request not allowed" } })); + }); }); return new Promise((resolve) => { server.listen(0, "127.0.0.1", () => { @@ -102,18 +105,46 @@ async function makeBili(upstream: string): Promise { return proxy; } -test("#3536: the panel page declares an empty icon so browsers never probe /favicon.ico", () => { +test("#4830: the panel page declares the bundled icon so browsers fetch it from /favicon.ico", () => { for (const embed of [false, true]) { const html = renderPage("http://127.0.0.1:8787", "0.0.0-test", embed); assert.ok( - html.includes(''), - `embed=${embed}: the head must declare the empty icon before `, + html.includes('<link rel="icon" type="image/x-icon" href="/favicon.ico">'), + `embed=${embed}: the head must declare the bundled icon before <title>`, ); assert.ok(html.indexOf('<link rel="icon"') < html.indexOf("<title>"), "icon link sits inside <head>"); } }); -test("#3536: GET /favicon.ico on the proxy origin answers 204 locally and never reaches the upstream; other unknown paths keep the relay fallthrough", async () => { +const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + +test("#4830: the embedded favicon constant decodes to a structurally valid .ico (16px + 32px PNG entries)", () => { + const ico = Buffer.from(FAVICON_ICO_BASE64, "base64"); + assert.equal(ico.readUInt16LE(0), 0, "reserved field"); + assert.equal(ico.readUInt16LE(2), 1, "container type must be icon"); + const count = ico.readUInt16LE(4); + assert.equal(count, 2, "one entry per shipped size"); + const sizes: number[] = []; + let end = 6 + count * 16; + for (let i = 0; i < count; i++) { + const e = 6 + i * 16; + const w = ico[e] === 0 ? 256 : ico[e]; + const h = ico[e + 1] === 0 ? 256 : ico[e + 1]; + assert.equal(w, h, `entry ${i}: square dimensions`); + sizes.push(w); + assert.equal(ico.readUInt16LE(e + 4), 1, `entry ${i}: planes`); + assert.equal(ico.readUInt16LE(e + 6), 32, `entry ${i}: bit count`); + const len = ico.readUInt32LE(e + 8); + const off = ico.readUInt32LE(e + 12); + assert.ok(off + len <= ico.length, `entry ${i}: payload inside buffer`); + assert.ok(ico.subarray(off, off + 8).equals(PNG_MAGIC), `entry ${i}: PNG-compressed payload`); + end = Math.max(end, off + len); + } + assert.deepEqual([...sizes].sort((a, b) => a - b), [16, 32], "shipped sizes"); + assert.equal(end, ico.length, "no trailing bytes after the last entry"); +}); + +test("#3536/#4830: GET /favicon.ico answers with the bundled icon locally and never reaches the upstream; other unknown paths keep the relay fallthrough", async () => { _setStoreForTest(new SessionStore({ enabled: false })); setRegistryForTest({}); const root = path.join(tmpdir(), `bili-issue3536-${process.pid}-${Date.now()}`); @@ -123,31 +154,38 @@ test("#3536: GET /favicon.ico on the proxy origin answers 204 locally and never const prevConfig = process.env.BILI_CONFIG_FILE; process.env.BILI_CONFIG_FILE = biliConfig; + const expected = Buffer.from(FAVICON_ICO_BASE64, "base64"); const up = await startMockUpstream(); const bili = await makeBili(up.origin); const port = (bili.address() as { port: number }).port; try { await waitReady(port); + // Positive gate: the probe is answered locally with the bundled bytes. const fav = await get(port, "/favicon.ico"); - assert.equal(fav.status, 204, `favicon probe must be answered locally (got ${fav.status}: ${fav.body.slice(0, 200)})`); - assert.equal(fav.body, ""); + assert.equal(fav.status, 200, `favicon probe must be answered locally (got ${fav.status})`); + assert.equal(fav.contentType, "image/x-icon"); + assert.equal(fav.cacheControl, "no-cache", "same cache posture as the page shell"); + assert.ok(fav.buf.equals(expected), "served bytes are exactly the bundled icon"); const favQuery = await get(port, "/favicon.ico?v=1"); - assert.equal(favQuery.status, 204, "the query form is the same asset"); + assert.equal(favQuery.status, 200, "the query form is the same asset"); + assert.ok(favQuery.buf.equals(expected), "query form serves identical bytes"); assert.deepEqual(up.hits, [], "no favicon probe may reach the configured upstream"); // Both halves of the fix over real HTTP: the served panel page carries - // the declaration that stops well-behaved browsers from probing at all. + // the declaration that points well-behaved browsers at the asset. const page = await get(port, "/__bili/?embed=1"); assert.equal(page.status, 200); - assert.ok(page.body.includes('<link rel="icon" href="data:,">'), "served panel HTML declares the empty icon"); + assert.ok(page.buf.toString("utf8").includes('<link rel="icon" type="image/x-icon" href="/favicon.ico">'), "served panel HTML declares the bundled icon"); - // Regression guard: ONLY the favicon path is pinned local — every other - // unknown path still falls through the relay onto the configured - // upstream (the documented zero-config tunnel behavior). + // Negative gates: ONLY GET /favicon.ico is pinned local. A non-GET on + // the same path and every other unknown path still fall through the + // relay onto the configured upstream (documented zero-config tunnel). + const post = await get(port, "/favicon.ico", { method: "POST", body: "{}" }); + assert.equal(post.status, 403, `POST on the favicon path keeps the relay fallthrough (got ${post.status})`); const other = await get(port, "/definitely/not/an/admin/path"); - assert.equal(other.status, 403, `unknown non-favicon paths keep the relay fallthrough (got ${other.status}: ${other.body.slice(0, 200)})`); - assert.deepEqual(up.hits, ["GET /definitely/not/an/admin/path"], "exactly the non-favicon request was relayed"); + assert.equal(other.status, 403, `unknown non-favicon paths keep the relay fallthrough (got ${other.status})`); + assert.deepEqual(up.hits, ["POST /favicon.ico", "GET /definitely/not/an/admin/path"], "exactly the non-asset requests were relayed"); } finally { process.env.BILI_CONFIG_FILE = prevConfig; bili.closeAllConnections?.();