Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions src/web/blogfeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,19 @@ let rootOverride: string | undefined;
let probedRoot: string | undefined;
let state: { items: BlogItem[] } | undefined;

/** Defense-in-depth on EVERY blog-asset response (#4958): asset bytes can
* come from GitHub master (remote overlay, #4906) and .svg is served as
* image/svg+xml — DIRECTLY NAVIGATED, that is active content on the panel
* origin (which also hosts the config editor and its provider API keys), so
* an embedded <script> would run same-origin. `sandbox` CSP strips
* script/origin powers from such a navigation; in-page <img> usage — the
* only way web/markdown.ts references these — is unaffected. nosniff pins
* the declared type. */
const ASSET_SECURITY_HEADERS: Record<string, string> = {
"content-security-policy": "sandbox",
"x-content-type-options": "nosniff",
};

/** One decoded-and-typed image served from the GitHub overlay (#4906), keyed
* by repo-relative POSIX path (e.g. "website/blog/posts/figures/x.png"). */
type RemoteAsset = { buf: Buffer; type: string };
Expand Down Expand Up @@ -512,11 +525,12 @@ function safeSegments(urlPath: string): string[] | undefined {
return out;
}

/** GET /__bili/blog-assets/<rel> — bundled image bytes only (extension gate +
* traversal gate); anything else is a plain-text 404. */
/** GET /__bili/blog-assets/<rel> — remote overlay bytes first (#4906), then
* bundled disk bytes (extension gate + traversal gate); anything else is a
* plain-text 404. EVERY response carries sandbox CSP + nosniff (#4958). */
export function handleBlogAssetGet(res: ServerResponse, urlPath: string): void {
const notFound = () => {
res.writeHead(404, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-cache" });
res.writeHead(404, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-cache", ...ASSET_SECURITY_HEADERS });
res.end(`404 Not Found: ${urlPath}\n`);
};
const clean = urlPath.split(/[?#]/)[0];
Expand All @@ -534,7 +548,7 @@ export function handleBlogAssetGet(res: ServerResponse, urlPath: string): void {
// frozen bundle bytes; a miss falls through to the package below.
const overlaid = getRemoteBlogAsset(segments.join("/"));
if (overlaid !== undefined) {
res.writeHead(200, { "content-type": overlaid.type, "cache-control": "no-cache" });
res.writeHead(200, { "content-type": overlaid.type, "cache-control": "no-cache", ...ASSET_SECURITY_HEADERS });
res.end(overlaid.buf);
return;
}
Expand All @@ -549,6 +563,6 @@ export function handleBlogAssetGet(res: ServerResponse, urlPath: string): void {
notFound();
return;
}
res.writeHead(200, { "content-type": type, "cache-control": "no-cache" });
res.writeHead(200, { "content-type": type, "cache-control": "no-cache", ...ASSET_SECURITY_HEADERS });
res.end(readFileSync(file));
}
45 changes: 43 additions & 2 deletions tests/web-blogfeed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
* every gate: dated/undated ordering, bilingual pairing, frontmatter titles,
* XSS-escaped rendering, image rewrite vs drop (incl. traversal refs),
* GFM tables, asset route (png allowed / md denied / traversal / encoding /
* missing), malformed manifest degradation, absent-root empty feed, and the
* missing / sandbox+nosniff on every asset response #4958), malformed
* manifest degradation, absent-root empty feed, and the
* real-tree probe finding the repository's website/blog/posts.
*/
import { test, beforeEach, afterEach } from "node:test";
Expand All @@ -13,7 +14,7 @@ import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { ServerResponse } from "node:http";
import { getBlogFeed, handleBlogGet, handleBlogAssetGet, _setBlogRootForTest } from "../src/web/blogfeed.ts";
import { getBlogFeed, handleBlogGet, handleBlogAssetGet, registerRemoteBlogFeed, _setBlogRootForTest } from "../src/web/blogfeed.ts";

let pkgRoot = "";
let outsideDir = "";
Expand Down Expand Up @@ -126,6 +127,37 @@ test("asset route: png allowed with exact bytes; md/traversal/encoding/missing a
assert.equal(md.status, 404);
});

test("asset responses pin sandbox CSP + nosniff on every path (#4958): remote overlay, disk fallback, 404", () => {
// Remote overlay: a GitHub-master .svg with an embedded <script> is served
// same-origin as image/svg+xml — the sandbox header is what keeps direct
// navigation from running that script on the panel origin.
const evilSvg = "<svg><script>alert(1)</script></svg>";
registerRemoteBlogFeed({ items: [], assets: new Map([["paper/figures/remote.svg", { buf: Buffer.from(evilSvg), type: "image/svg+xml" }]]) });
const overlay = fakeRes();
handleBlogAssetGet(overlay.res, "/__bili/blog-assets/paper/figures/remote.svg");
assert.equal(overlay.status, 200);
assert.equal(overlay.headers["content-security-policy"], "sandbox");
assert.equal(overlay.headers["x-content-type-options"], "nosniff");
assert.match(String(overlay.headers["content-type"]), /^image\/svg\+xml/);
assert.equal(overlay.body, evilSvg, "body bytes unchanged by the header fix");

// On-disk fallback branch keeps the same pair with its bytes/type intact.
const disk = fakeRes();
handleBlogAssetGet(disk.res, "/__bili/blog-assets/paper/figures/p.png");
assert.equal(disk.status, 200);
assert.equal(disk.headers["content-security-policy"], "sandbox");
assert.equal(disk.headers["x-content-type-options"], "nosniff");
assert.match(String(disk.headers["content-type"]), /^image\/png/);
assert.equal(disk.body, "PAPERPNG");

// 404s from the asset route carry the pair too — every response of the route.
const miss = fakeRes();
handleBlogAssetGet(miss.res, "/__bili/blog-assets/paper/figures/nope.png");
assert.equal(miss.status, 404);
assert.equal(miss.headers["content-security-policy"], "sandbox");
assert.equal(miss.headers["x-content-type-options"], "nosniff");
});

test("handleBlogGet answers 200 JSON always; broken manifest degrades to posts-only", () => {
const warm = fakeRes();
handleBlogGet(warm.res);
Expand All @@ -139,6 +171,15 @@ test("handleBlogGet answers 200 JSON always; broken manifest degrades to posts-o
assert.ok(data.items.every((i) => i.kind === "post"));
});

test("the sandbox/nosniff pair stays scoped to the asset route — the blog feed JSON route does not gain it (#4958)", () => {
const feed = fakeRes();
handleBlogGet(feed.res);
assert.equal(feed.status, 200);
assert.equal(feed.headers["content-security-policy"], undefined);
assert.equal(feed.headers["x-content-type-options"], undefined);
assert.match(String(feed.headers["content-type"]), /^application\/json/);
});

test("a root without content degrades to an empty list instead of throwing", () => {
_setBlogRootForTest(join(outsideDir, "does-not-exist"));
assert.deepEqual(getBlogFeed(), { items: [] });
Expand Down
7 changes: 6 additions & 1 deletion tests/web-routing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ test("Web UI exposes upstream controls without inline handlers", async () => {
const port = (proxy.address() as { port: number }).port;
const base = `http://127.0.0.1:${port}`;
try {
const ui = await (await fetch(`${base}/__bili/`)).text();
const uiRes = await fetch(`${base}/__bili/`);
const ui = await uiRes.text();
// #4958 negative direction: the sandbox CSP + nosniff pair is scoped to
// the blog ASSET route only — the panel HTML route must not gain it.
assert.equal(uiRes.headers.get("content-security-policy"), null);
assert.equal(uiRes.headers.get("x-content-type-options"), null);
assert.match(ui, /Codex(ChatGPT 登录)/);
assert.match(ui, /上游网络/);
assert.match(ui, /Fork me on GitHub/);
Expand Down
Loading