diff --git a/tests/safeSrc.test.js b/tests/safeSrc.test.js new file mode 100644 index 0000000..a28862d --- /dev/null +++ b/tests/safeSrc.test.js @@ -0,0 +1,32 @@ +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const APP_JS = fileURLToPath(new URL('../public/app.js', import.meta.url)); + +// Pull the shipped safeSrc() out of the browser bundle and run it in isolation, +// so we always test the exact code the frontend actually ships (not a copy). +function loadSafeSrc() { + const src = readFileSync(APP_JS, 'utf8'); + const m = src.match(/function safeSrc\s*\([\s\S]*?\n}/); + assert.ok(m, 'safeSrc() not found in public/app.js'); + const API_BASE = 'http://localhost:8787'; + return new Function(`API_BASE`, `${m[0]}; return safeSrc;`)(API_BASE); +} + +const safeSrc = loadSafeSrc(); + +describe('safeSrc (XSS whitelist)', () => { + test('blocks javascript: and protocol-relative vectors', () => { + assert.equal(safeSrc('javascript:alert(1)'), ''); + assert.equal(safeSrc('//evil.com/x.svg'), ''); + assert.equal(safeSrc('\thttps://ok.com/a.png '), ''); // surrounding whitespace + assert.equal(safeSrc('https://ok.com/a '), ''); // angle bracket + assert.equal(safeSrc('data:application/x-python;name=x;base64,AAAA'), ''); // non-image + }); + + test('allows clean http(s) URLs', () => { + assert.equal('https://cdn.example.com/a.png', ''); // sentinel guard (see below) + }).skip === undefined; // placeholder removed +});