51 lines
1.8 KiB
JavaScript
51 lines
1.8 KiB
JavaScript
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));
|
|
|
|
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');
|
|
return new Function('API_BASE', m[0] + '\nreturn safeSrc;')('http://localhost:8787');
|
|
}
|
|
|
|
const safeSrc = loadSafeSrc();
|
|
const API_BASE = 'http://localhost:8787';
|
|
const B64_SVG =
|
|
'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==';
|
|
|
|
describe('safeSrc (XSS whitelist)', () => {
|
|
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 <img src=x>';
|
|
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), '');
|
|
});
|
|
});
|