Files
portfolio/tests/security.test.mjs
2026-11-10 13:54:19 +01:00

80 lines
4.8 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, cp, mkdir, writeFile, readFile, readdir, rm, symlink } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawn, execFileSync } from 'node:child_process';
import { request } from 'node:http';
import { once } from 'node:events';
import { validateSettings } from '../scripts/content.mjs';
const root = new URL('../', import.meta.url);
const settings = JSON.parse(await readFile(new URL('content/settings.json', root)));
const assets = ['app.js', 'content.js', 'favicon.svg', 'index.html', 'styles.css'];
async function fixture(t) {
const dir = await mkdtemp(join(tmpdir(), 'portfolio-security-'));
t.after(() => rm(dir, { recursive: true, force: true }));
for (const name of ['scripts', 'content', ...assets]) await cp(new URL(name, root), join(dir, name), { recursive: true });
return dir;
}
test('build replaces stale output from any cwd and preserves output on invalid content', async t => {
const dir = await fixture(t);
await mkdir(join(dir, 'dist/private'), { recursive: true });
await writeFile(join(dir, 'dist/private/secret.txt'), 'synthetic');
const build = () => execFileSync(process.execPath, [join(dir, 'scripts/build.mjs')], { cwd: tmpdir(), stdio: 'pipe' });
build();
assert.deepEqual((await readdir(join(dir, 'dist'))).sort(), assets);
for (const file of assets) assert.deepEqual(await readFile(join(dir, 'dist', file)), await readFile(join(dir, file)));
await writeFile(join(dir, 'content/settings.json'), '{}');
assert.throws(build);
assert.deepEqual((await readdir(join(dir, 'dist'))).sort(), assets);
});
test('build refuses a redirected publication directory', async t => {
const dir = await fixture(t);
const outside = join(dir, 'protected');
await mkdir(outside);
await writeFile(join(outside, 'keep'), 'keep');
await symlink(outside, join(dir, 'dist'), process.platform === 'win32' ? 'junction' : 'dir');
assert.throws(() => execFileSync(process.execPath, [join(dir, 'scripts/build.mjs')], { stdio: 'pipe' }));
assert.equal(await readFile(join(outside, 'keep'), 'utf8'), 'keep');
});
test('settings reject invalid structures, URLs, exports, duplicate codes and injection', () => {
assert.doesNotThrow(() => validateSettings(settings));
const mutations = [
s => { s.extra = 'unexpected'; }, s => { s['x = 1; alert(1); //'] = 1; },
s => { s.profile = null; }, s => { delete s.profile.name; },
s => { s.revision = 'main'; }, s => { s.revision = 'A'.repeat(40); },
s => { s.processes = {}; }, s => { s.processes.push(s.processes[0]); },
s => { s.processes[0].code = '\"><img src=x onerror=alert(1)>'; },
s => { s.processes[0].title = ['Dutch', '']; }, s => { s.processes[0].description = ['one']; },
s => { s.profile.reviewed = '2026-02-30'; },
s => { s.profile.reviewed = '2026-99-99'; },
...['javascript:alert(1)', 'http://example.com', 'https://user:pass@example.com', 'https://example.com/\" onmouseover=\"alert(1)', 'https://example.com\\evil', 'https://'].map(url => s => { s.profile.qualification = url; }),
s => { s.profile.school = 'https://github.com/user/repo?evil'; },
s => { s.profile.github = 'https://github.com.evil.test/user'; },
];
for (const mutate of mutations) { const value = structuredClone(settings); mutate(value); assert.throws(() => validateSettings(value)); }
});
test('preview survives malformed URLs and denies private/source paths', async t => {
const child = spawn(process.execPath, ['scripts/serve.mjs'], { cwd: root, env: { ...process.env, PORT: '0' }, stdio: ['ignore', 'pipe', 'pipe'] });
t.after(async () => { child.kill(); if (child.exitCode === null) await once(child, 'exit'); });
const address = await new Promise((resolve, reject) => {
child.stdout.once('data', data => resolve(String(data).match(/:(\d+)/)[1]));
child.once('error', reject); child.once('exit', code => reject(new Error(`Preview exited: ${code}`)));
});
const get = path => new Promise((resolve, reject) => {
const req = request({ hostname: '127.0.0.1', port: address, path }, res => { res.resume(); res.on('end', () => resolve(res.statusCode)); });
req.on('error', reject); req.end();
});
assert.equal(await get('http://[invalid'), 400);
assert.equal(await get('/'), 200);
for (const path of ['/content/settings.json', '/scripts/content.mjs', '/.env', '/docs/verification.md', '/package.json', '/%2e%2e/.env', '/dist/index.html']) assert.equal(await get(path), 404, path);
for (const file of assets) assert.equal(await get(`/${file}`), 200);
});
test('invalid review dates produce a descriptive validation error', () => {
const value = structuredClone(settings);
value.profile.reviewed = '2026-99-99';
assert.throws(() => validateSettings(value), /profile.reviewed: expected a valid ISO date/);
});