Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(csp): give HTML and SVG answered by API handlers the static pages' script CSP

nirholasdeff716eedee
diff --git a/server/csp-hashes.mjs b/server/csp-hashes.mjs
index 776299345..2eda2b099 100644
--- a/server/csp-hashes.mjs
+++ b/server/csp-hashes.mjs
@@ -201,3 +201,45 @@ export function hardenHeaderBag(headers, html) {
}
return headers;
}
+
+// Content types a browser runs script from when the response is opened as a
+// document. An API handler that renders a share page or an SVG card answers
+// with one of these.
+const ACTIVE_DOCUMENT = /^\s*(?:text\/html|image\/svg\+xml|application\/xhtml\+xml)\b/i;
+
+function bodyText(chunk) {
+ if (typeof chunk === 'string') return chunk;
+ if (chunk instanceof Uint8Array) return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength).toString('utf8');
+ return null;
+}
+
+/**
+ * Harden the CSP of a response written by an API handler, the same way static
+ * HTML is hardened, once the handler hands over its body.
+ *
+ * API handlers inherit the route table's policy, which still lists
+ * `'unsafe-inline'` so the static pipeline has something to rewrite. Without
+ * this, every server-rendered share page and SVG card went out with that
+ * keyword intact, so an attribute breakout in any of them (`onerror=`, a
+ * `javascript:` href) ran with nothing behind the escaping to stop it.
+ *
+ * Only a body delivered whole through `res.end()` before headers are sent is
+ * rewritten; a streamed response keeps the policy it was given.
+ *
+ * @param {import('node:http').ServerResponse} res
+ * @returns {import('node:http').ServerResponse}
+ */
+export function hardenOnEnd(res) {
+ const end = res.end;
+ res.end = function hardenedEnd(chunk, ...rest) {
+ if (!res.headersSent && chunk != null && typeof chunk !== 'function') {
+ const csp = res.getHeader('content-security-policy');
+ if (typeof csp === 'string' && ACTIVE_DOCUMENT.test(String(res.getHeader('content-type') || ''))) {
+ const html = bodyText(chunk);
+ if (html !== null) res.setHeader('content-security-policy', hardenInlineScripts(csp, html));
+ }
+ }
+ return end.call(this, chunk, ...rest);
+ };
+ return res;
+}
diff --git a/server/index.mjs b/server/index.mjs
index d8e8afe36..148c6a6b5 100644
--- a/server/index.mjs
+++ b/server/index.mjs
@@ -39,7 +39,7 @@ import { isSsrRoute, renderSsrPage } from './ssr-pages.mjs';
import { hasSeoRoute, renderSeoHead, CANONICAL_ORIGIN } from './seo-head.mjs';
import { renderCrawlerBody } from './crawler-body.mjs';
import { isMissingShellPage } from './shell-pages.mjs';
-import { hardenHeaderBag } from './csp-hashes.mjs';
+import { hardenHeaderBag, hardenOnEnd } from './csp-hashes.mjs';
import { cronEdgeAuth } from './cron-edge-auth.mjs';
// Route resolution lives in its own module so the audit scripts
// (scripts/audit-cron-liveness.mjs) exercise the SAME resolver production runs,
@@ -209,6 +209,9 @@ async function dispatchApi(req, res, pathname, extraQuery) {
res.status(500).json({ error: 'internal_error', message: 'Handler misconfigured.' });
return true;
}
+ // A handler that renders HTML or SVG gets the same inline-script CSP
+ // hardening a static page gets (server/csp-hashes.mjs).
+ hardenOnEnd(res);
await handler(req, res);
} catch (err) {
console.error(`[api] ${req.method} ${pathname} failed:`, err);
diff --git a/tests/csp-hashes.test.js b/tests/csp-hashes.test.js
index 2c1984634..20ea4da3b 100644
--- a/tests/csp-hashes.test.js
+++ b/tests/csp-hashes.test.js
@@ -11,6 +11,7 @@ import {
inlineScriptHashes,
hardenInlineScripts,
hardenHeaderBag,
+ hardenOnEnd,
} from '../server/csp-hashes.mjs';
const sha = (s) => `'sha256-${createHash('sha256').update(s, 'utf8').digest('base64')}'`;
@@ -224,3 +225,58 @@ describe('hardenHeaderBag', () => {
});
});
});
+
+describe('hardenOnEnd', () => {
+ // The slice of a Node ServerResponse the hook touches, with header names
+ // case-insensitive the way the real one keeps them.
+ function fakeRes(headers) {
+ const bag = new Map(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
+ const res = {
+ headersSent: false,
+ sent: null,
+ getHeader: (k) => bag.get(k.toLowerCase()),
+ setHeader: (k, v) => bag.set(k.toLowerCase(), v),
+ end(chunk) {
+ res.headersSent = true;
+ res.sent = chunk;
+ return res;
+ },
+ };
+ return res;
+ }
+
+ it('drops unsafe-inline from an API-rendered HTML page and hashes its own scripts', () => {
+ const res = hardenOnEnd(fakeRes({ 'content-security-policy': POLICY, 'content-type': 'text/html; charset=utf-8' }));
+ res.end('<p>hi</p><script>a()</script>');
+ const csp = res.getHeader('content-security-policy');
+ expect(csp).not.toContain("'unsafe-inline'");
+ expect(csp).toContain(sha('a()'));
+ expect(res.sent).toBe('<p>hi</p><script>a()</script>');
+ });
+
+ it('hardens an SVG card sent as a Buffer', () => {
+ const res = hardenOnEnd(fakeRes({ 'content-security-policy': POLICY, 'content-type': 'image/svg+xml; charset=utf-8' }));
+ res.end(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><text>x</text></svg>'));
+ expect(res.getHeader('content-security-policy')).not.toContain("'unsafe-inline'");
+ });
+
+ it('leaves JSON responses alone', () => {
+ const res = hardenOnEnd(fakeRes({ 'content-security-policy': POLICY, 'content-type': 'application/json' }));
+ res.end('{"ok":true}');
+ expect(res.getHeader('content-security-policy')).toBe(POLICY);
+ });
+
+ it('does not touch headers that have already gone out', () => {
+ const res = hardenOnEnd(fakeRes({ 'content-security-policy': POLICY, 'content-type': 'text/html' }));
+ res.headersSent = true;
+ res.end('<script>a()</script>');
+ expect(res.getHeader('content-security-policy')).toBe(POLICY);
+ });
+
+ it('passes a bodiless end straight through', () => {
+ const res = hardenOnEnd(fakeRes({ 'content-security-policy': POLICY, 'content-type': 'text/html' }));
+ res.end();
+ expect(res.getHeader('content-security-policy')).toBe(POLICY);
+ expect(res.headersSent).toBe(true);
+ });
+});