Sandbox home and artifact files served on the app origin (H1)

GET /files and /artifacts/ now send the artifact sandbox CSP and nosniff
through one helper, and /files serves HTML, XHTML, SVG, XML, XSL,
JavaScript and multipart/x-mixed-replace as attachments, including when
the type is sniffed from an extensionless file. The web proxy adds the same
headers to every proxied /files and /artifacts/ response (defence in depth
against an older server), and the peer relay shares the helper.

show_html previews are unchanged by operator decision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 23:16:46 +00:00
parent 806b5eca46
commit e39a9560ba
9 changed files with 233 additions and 21 deletions
+11 -2
View File
@@ -45,6 +45,7 @@ import {
import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js";
import { accessPolicy, PLAIN_LAN_REFUSAL } from "./src/listenPolicy.js";
import { AppFiles, ISOLATION_HEADERS, VERSIONED_PREFIX } from "./src/appFiles.js";
import { untrustedHeaders } from "./src/untrustedContent.js";
// The proxy's own directory holds the sign-in page's icons.
const HERE = resolve(fileURLToPath(new URL(".", import.meta.url)));
@@ -465,7 +466,8 @@ async function serveIndex(res) {
function proxyArtifact(req, res) {
let headers;
// An upload is gated by the session's elevation on the server.
const upload = req.method === "POST" && (req.url ?? "").split("?")[0] === "/files";
const pathname = (req.url ?? "").split("?")[0];
const upload = req.method === "POST" && pathname === "/files";
try {
headers = withServerToken(req.headers, undefined, upload ? elevationSession(req) : "");
} catch {
@@ -477,7 +479,14 @@ function proxyArtifact(req, res) {
const upstream = request(
{ host: targetHost, port: targetPort, method: req.method, path: req.url, headers },
(reply) => {
res.writeHead(reply.statusCode ?? 502, reply.headers);
// Served files are untrusted content: always sandboxed, and a home file
// a browser could script is a download. Defence in depth: the server
// sets the same headers.
const served = req.method === "GET" || req.method === "HEAD";
res.writeHead(
reply.statusCode ?? 502,
served ? untrustedHeaders(reply.headers, { download: pathname === "/files" }) : reply.headers,
);
reply.pipe(res);
},
);
+11 -15
View File
@@ -8,11 +8,9 @@ import {
import { PeerRegistry } from "./peerRegistry.js";
import { withServerToken } from "./serverToken.js";
import { rememberDiscovered } from "./peerAddress.js";
// Peer files are untrusted content, never privileged control-UI documents.
// Apply this even for older peers whose /files endpoint has no sandbox header.
const contentPolicy =
"sandbox; default-src 'none'; script-src 'none'; connect-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
// Peer files are untrusted content, never privileged control-UI documents:
// the sandbox applies even for older peers whose /files has no such header.
import { untrustedHeaders } from "./untrustedContent.js";
const allowed = (path) =>
path === "/files" ||
@@ -98,23 +96,21 @@ export class PeerRelay extends PeerRegistry {
"content-range",
"accept-ranges",
"content-disposition",
"content-security-policy",
])
if (response.headers[name]) safe[name] = response.headers[name];
// Multiple CSP policies intersect: preserve a peer's stricter
// restrictions while always imposing the local sandbox boundary. A
// peer home file a browser could script is a download.
res.writeHead(
response.statusCode >= 300 && response.statusCode < 400
? 502
: response.statusCode,
{
...safe,
"Cache-Control": "private, no-store",
// Multiple CSP policies intersect: preserve a peer's stricter
// restrictions while always imposing the local sandbox boundary.
"Content-Security-Policy": response.headers[
"content-security-policy"
]
? [response.headers["content-security-policy"], contentPolicy]
: contentPolicy,
"X-Content-Type-Options": "nosniff",
...untrustedHeaders(safe, {
download: target.url.pathname === "/files",
}),
"cache-control": "private, no-store",
},
);
response.pipe(res);
+50
View File
@@ -0,0 +1,50 @@
// The response boundary for files the proxy relays but did not write: run
// artifacts, files under a home directory and a peer's files. `sandbox` gives
// such a document an opaque origin even when it is opened as a page, so a
// crafted HTML or SVG file cannot script the app origin. The Go server sets the
// same policy; the proxy adds it again so an older server, or a peer, cannot
// serve a document with the app's authority.
export const CONTENT_POLICY =
"sandbox; default-src 'none'; script-src 'none'; connect-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
const SCRIPT_CAPABLE = new Set([
"text/html",
"application/xhtml+xml",
"image/svg+xml",
"text/xml",
"application/xml",
"text/xsl",
"application/xslt+xml",
"application/javascript",
"text/javascript",
"application/ecmascript",
"text/ecmascript",
"multipart/x-mixed-replace",
]);
/** Whether a browser could run script in a page of this content type. */
export function scriptCapable(contentType) {
const media = String(contentType ?? "").split(";")[0].trim().toLowerCase();
return SCRIPT_CAPABLE.has(media) || media.endsWith("+xml") || media.endsWith("/xml");
}
/**
* Copies [headers] (a Node response's headers, lower-case names) with the
* sandbox policy added. Multiple CSP headers intersect, so an upstream policy
* is kept beside the local one. With [download], a script-capable type is
* forced to an attachment, keeping any filename the upstream named.
*/
export function untrustedHeaders(headers, { download = false } = {}) {
const out = { ...headers };
const upstream = out["content-security-policy"];
out["content-security-policy"] = upstream
? [...(Array.isArray(upstream) ? upstream : [upstream]), CONTENT_POLICY]
: CONTENT_POLICY;
out["x-content-type-options"] = "nosniff";
if (download && scriptCapable(out["content-type"])) {
const current = String(out["content-disposition"] ?? "").trim();
if (/^inline\b/i.test(current)) out["content-disposition"] = current.replace(/^inline/i, "attachment");
else if (!/^attachment\b/i.test(current)) out["content-disposition"] = "attachment";
}
return out;
}
+31
View File
@@ -214,6 +214,37 @@ test("files require sign-in and proxy query, ranges and attachment headers", asy
]);
});
test("files and artifacts are sandboxed and home HTML is a download even from an old server", async (t) => {
// An older server that sets none of the boundary headers.
const upstream = createServer((req, res) => {
const html = req.url.startsWith("/files") || req.url.startsWith("/artifacts/");
res.writeHead(200, {
"Content-Type": html ? "text/html; charset=utf-8" : "text/plain",
"Content-Disposition": 'inline; filename="x.html"',
});
res.end("<script>alert(1)</script>");
}).listen(0, "127.0.0.1");
await once(upstream, "listening");
t.after(() => new Promise((done) => upstream.close(done)));
const port = await freePort();
const child = spawn(process.execPath, ["serve.mjs", "--port", String(port),
"--pipelines", `127.0.0.1:${upstream.address().port}`], {
cwd: here,
env: { ...process.env, PIPELINES_WEB_AUTH: "disabled" },
stdio: ["ignore", "pipe", "inherit"],
});
t.after(async () => { const exited = once(child, "exit"); child.kill(); await exited; });
await once(child.stdout, "data");
const base = `http://127.0.0.1:${port}`;
const file = await fetch(base + "/files?path=~/Downloads/x.html");
assert.match(file.headers.get("content-security-policy"), /(^|, )sandbox; default-src 'none'; script-src 'none'/);
assert.equal(file.headers.get("x-content-type-options"), "nosniff");
assert.equal(file.headers.get("content-disposition"), 'attachment; filename="x.html"');
const artifact = await fetch(base + "/artifacts/r/s/report.html");
assert.match(artifact.headers.get("content-security-policy"), /sandbox; default-src 'none'/);
assert.equal(artifact.headers.get("content-disposition"), 'inline; filename="x.html"');
});
test("file uploads require sign-in and reach the server with their name header", async (t) => {
const requests = [];
const upstream = createServer(async (req, res) => {
+34
View File
@@ -0,0 +1,34 @@
import test from "node:test";
import assert from "node:assert/strict";
import { CONTENT_POLICY, scriptCapable, untrustedHeaders } from "../src/untrustedContent.js";
test("script-capable types cover HTML, SVG and every XML flavour", () => {
for (const type of [
"text/html; charset=utf-8",
"application/xhtml+xml",
"image/svg+xml",
"text/xml",
"application/xml",
"application/rss+xml",
"TEXT/HTML",
])
assert.equal(scriptCapable(type), true, type);
for (const type of ["text/plain", "image/png", "application/pdf", "application/octet-stream", "", undefined])
assert.equal(scriptCapable(type), false, String(type));
});
test("untrusted headers add the sandbox beside an upstream policy", () => {
assert.equal(untrustedHeaders({})["content-security-policy"], CONTENT_POLICY);
const both = untrustedHeaders({ "content-security-policy": "img-src 'none'" });
assert.deepEqual(both["content-security-policy"], ["img-src 'none'", CONTENT_POLICY]);
assert.equal(both["x-content-type-options"], "nosniff");
});
test("downloads force script-capable types to attachments and keep the name", () => {
const html = { "content-type": "text/html", "content-disposition": 'inline; filename="a.html"' };
assert.equal(untrustedHeaders(html, { download: true })["content-disposition"], 'attachment; filename="a.html"');
assert.equal(untrustedHeaders({ "content-type": "image/svg+xml" }, { download: true })["content-disposition"], "attachment");
assert.equal(untrustedHeaders(html)["content-disposition"], 'inline; filename="a.html"');
const text = { "content-type": "text/plain", "content-disposition": "inline" };
assert.equal(untrustedHeaders(text, { download: true })["content-disposition"], "inline");
});