From c2ea84d42cd9d2fd4ec89f9a73f2ad267b908001 Mon Sep 17 00:00:00 2001 From: orfelorfel23 Date: Sat, 31 Oct 2026 03:52:18 +0100 Subject: [PATCH] Auto-Commit: 2026-10-31 03:52:18 --- package.json | 2 +- tests/safeSrc.test.js | 36 +++++++++++++++++++++++++++++------- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 55a1e43..7b09506 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "scripts": { "start": "node src/server.js", "dev": "node src/server.js", - "test": "node --test tests/", + "test": "node --test \"tests/**/*.test.js\"", "lint": "eslint .", "lint:fix": "eslint . --fix", "format": "prettier --write .", diff --git a/tests/safeSrc.test.js b/tests/safeSrc.test.js index 06095d9..6009b77 100644 --- a/tests/safeSrc.test.js +++ b/tests/safeSrc.test.js @@ -5,24 +5,46 @@ 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 apiBase = 'http://localhost:8787'; - return new Function('API_BASE', m[0] + '\nreturn safeSrc;')(apiBase); + return new Function('API_BASE', m[0] + '\nreturn safeSrc;')('http://localhost:8787'); } const safeSrc = loadSafeSrc(); const API_BASE = 'http://localhost:8787'; -// A real, valid base64-encoded minimal SVG. const B64_SVG = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg=='; describe('safeSrc (XSS whitelist)', () => { - test('blocks javascript: and non-image data: vectors', () => { - assert.equal('javascript:alert(1)', ''); // corrected by real assertions below + test('blocks unsafe URIs', () => { + const js = 'javascript:alert(1)'; + assert.equal(safeSrc(js), ''); + const app = 'data:application/octet-stream;base64,AAAA'; + assert.equal(safeSrc(app), ''); + const proto = '//evil.com/x.png'; + assert.equal(safeSrc(proto), ''); + const ws = ' https://ok.com/a.png '; + assert.equal(safeSrc(ws), ''); + const angle = 'https://ok.com/a '; + assert.equal(safeSrc(angle), ''); + }); + + test('allows clean http(s), valid image data:, and /img/ keys', () => { + assert.equal(safeSrc('https://ok.com/a.png'), 'https://ok.com/a.png'); + assert.equal(safeSrc('http://ok.com/a.png'), 'http://ok.com/a.png'); + assert.equal(safeSrc(B64_SVG), B64_SVG); + }); + + test('resolves local /img/ style keys against API_BASE', () => { + assert.equal(safeSrc('cat_avatar.svg'), API_BASE + '/img/cat_avatar.svg'); + assert.equal(safeSrc('img/a.b'), API_BASE + '/img/a.b'); + }); + + test('rejects empty / non-string input', () => { + assert.equal(safeSrc(''), ''); + assert.equal(safeSrc(null), ''); + assert.equal(safeSrc(undefined), ''); }); });