[security] add a strict Content-Security-Policy to the HTML entry points

Defense-in-depth against XSS for a client that holds storage credentials in
memory. The critical directive is a strict script-src: 'self' + the hash of the
inline theme-bootstrap + the nostr-tools CDN fallbacks, with no 'unsafe-inline'
or 'unsafe-eval' (verified no bundle uses eval/Function/wasm). This blocks
injected script/object elements, inline handlers, and base-tag hijack, so an
injected payload cannot run and read the in-memory storage master key, the
signer, or DM plaintext. connect/img/media stay broad because relays, R2/S3
endpoints, and video/thumbnail URLs are user/content defined; worker-src allows
blob: for the WebTorrent module worker. Applied to index.html and embed.html.

Test (tests/csp-policy.test.mjs) locks the inline-script hash to script-src and
asserts script-src stays strict (no unsafe-inline/eval) with object-src 'none'
and base-uri 'self'.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
thePR0M3TH3ANandClaude Opus 4.8 committed 2026-06-18 12:15:14 -04:00
1 parent c5a91cb4d2
commit 577ea5af15
3 files changed
+133

No files matched your search

+11
View File
@@ -2,6 +2,17 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<!--
Content-Security-Policy for the embeddable player. Same strict script-src
as index.html (same inline theme-bootstrap hash). frame-ancestors is left
unset on purpose: this page is meant to be embedded anywhere. If you
change the inline theme script below, update the sha256 hash here
(tests/csp-policy.test.mjs enforces this).
-->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self' 'sha256-dnv/l3q8gLqdw0etekr5/atoIRbM/wSVSgQjZEsC7G0=' https://cdn.jsdelivr.net https://esm.sh; style-src 'self' 'unsafe-inline'; img-src 'self' https: data: blob:; media-src 'self' https: blob: mediastream:; connect-src 'self' https: wss: blob: data:; worker-src 'self' blob:; font-src 'self' data:; frame-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; manifest-src 'self'"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>bitvid | Embed</title>
+19
View File
@@ -2,6 +2,25 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<!--
Content-Security-Policy: defense-in-depth against XSS. The critical
directive is script-src, which is strict — only same-origin scripts, the
hash of the inline theme-bootstrap below, and the nostr-tools CDN
fallbacks (js/nostrToolsBootstrap.js). No 'unsafe-inline'/'unsafe-eval'
(verified: no bundle uses eval/Function/wasm). This blocks injected
script and object elements, inline handlers (none exist), and base-tag
hijack, so an injected payload cannot execute and read the in-memory
storage master key / signer / DM plaintext. connect/img/media stay broad
because relays, R2/S3 endpoints, and video/thumbnail URLs are
user/content defined. If you change the inline theme script below, update
the sha256 hash here (tests/csp-policy.test.mjs enforces this).
NOTE: any future view loaded by js/viewManager.js must use external-src
script tags (script-src 'self'), not inline scripts.
-->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self' 'sha256-dnv/l3q8gLqdw0etekr5/atoIRbM/wSVSgQjZEsC7G0=' https://cdn.jsdelivr.net https://esm.sh; style-src 'self' 'unsafe-inline'; img-src 'self' https: data: blob:; media-src 'self' https: blob: mediastream:; connect-src 'self' https: wss: blob: data:; worker-src 'self' blob:; font-src 'self' data:; frame-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; manifest-src 'self'"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>bitvid | Decentralized Video Sharing</title>
+103
View File
@@ -0,0 +1,103 @@
// Regression test for the Content-Security-Policy on the HTML entry points.
//
// SCN-csp-script-src-locks-inline-hash:
// Given index.html / embed.html ship a CSP whose security depends on a strict
// script-src (no 'unsafe-inline'),
// When the inline bootstrap <script> is hashed,
// Then that exact sha256 must be listed in script-src — otherwise the browser
// blocks our own bootstrap (app broken) or someone added 'unsafe-inline'
// (XSS protection silently gutted).
//
// This catches the most likely future regression: editing the inline script
// without updating the hash, or relaxing script-src to make it "work".
import { readFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { test } from "node:test";
import assert from "node:assert/strict";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
function extractCsp(html) {
// The content value itself contains single quotes ('self', 'none', hashes),
// so capture up to the same quote char that opens the attribute.
const meta = html.match(
/<meta\s+http-equiv=["']Content-Security-Policy["']\s+content=(["'])([\s\S]*?)\1/i,
);
return meta ? meta[2] : "";
}
function parseDirectives(csp) {
const map = new Map();
for (const part of csp.split(";")) {
const trimmed = part.trim();
if (!trimmed) continue;
const [name, ...values] = trimmed.split(/\s+/);
map.set(name.toLowerCase(), values);
}
return map;
}
function inlineScriptHashes(htmlRaw) {
// Browsers ignore content inside HTML comments; strip them so prose mentioning
// "script" in a comment is not mistaken for a real inline <script>.
const html = htmlRaw.replace(/<!--[\s\S]*?-->/g, "");
const re = /<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi;
const hashes = [];
let m;
while ((m = re.exec(html))) {
hashes.push(
"sha256-" + createHash("sha256").update(m[1], "utf8").digest("base64"),
);
}
return hashes;
}
for (const file of ["index.html", "embed.html"]) {
test(`${file}: CSP exists and script-src is strict`, () => {
const html = readFileSync(path.join(ROOT, file), "utf8");
const csp = extractCsp(html);
assert.ok(csp, `${file} must declare a Content-Security-Policy meta`);
const directives = parseDirectives(csp);
const scriptSrc = directives.get("script-src");
assert.ok(scriptSrc, "script-src must be set");
// The whole point: script execution must NOT be wide open.
assert.ok(
!scriptSrc.includes("'unsafe-inline'"),
"script-src must not allow 'unsafe-inline' (defeats XSS protection)",
);
assert.ok(
!scriptSrc.includes("'unsafe-eval'"),
"script-src must not allow 'unsafe-eval' (no bundle needs it)",
);
assert.ok(scriptSrc.includes("'self'"), "script-src must include 'self'");
// object-src/base-uri are cheap, high-value XSS hardening.
assert.deepEqual(
directives.get("object-src"),
["'none'"],
"object-src must be 'none'",
);
assert.deepEqual(
directives.get("base-uri"),
["'self'"],
"base-uri must be 'self'",
);
});
test(`${file}: every inline <script> is hash-allowlisted in script-src`, () => {
const html = readFileSync(path.join(ROOT, file), "utf8");
const scriptSrc = parseDirectives(extractCsp(html)).get("script-src") || [];
for (const hash of inlineScriptHashes(html)) {
assert.ok(
scriptSrc.includes(`'${hash}'`),
`inline <script> in ${file} has hash ${hash} which is not listed in ` +
`script-src — update the CSP meta after editing the inline script`,
);
}
});
}