Merge origin/main into codex/ddos-scaling-and-mitigation

This commit is contained in:
Frederic Jung 2026-10-27 13:21:51 +00:00
commit e7ae3b18bf
154 changed files with 19102 additions and 14323 deletions

View file

@ -8,7 +8,7 @@ const OUT = require('node:fs').mkdtempSync(require('node:path').join(require('no
const root = path.join(__dirname, '..');
test('build stamps version and date into the site', () => {
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, OUT, VERSION: '9.9.9', BUILD_DATE: '2030-01-01' } });
execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, env: { ...process.env, OUT, VERSION: '9.9.9', BUILD_DATE: '2030-01-01' } });
const html = fs.readFileSync(path.join(OUT, 'index.html'), 'utf8');
assert.match(html, /const APP_VERSION='9\.9\.9'/);
assert.match(html, /"softwareVersion": "9\.9\.9"/);
@ -19,7 +19,7 @@ test('build stamps version and date into the site', () => {
});
test('version.json carries the release notes from the changelog', () => {
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, OUT, VERSION: '1.0.0', BUILD_DATE: '2026-10-23' } });
execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, env: { ...process.env, OUT, VERSION: '1.0.0', BUILD_DATE: '2026-10-23' } });
const v = JSON.parse(fs.readFileSync(path.join(OUT, 'version.json'), 'utf8'));
assert.equal(v.version, '1.0.0');
assert.ok(v.notes.length >= 5);
@ -27,7 +27,7 @@ test('version.json carries the release notes from the changelog', () => {
});
test('head carries the SEO and social metadata', () => {
const html = fs.readFileSync(path.join(root, 'site', 'index.html'), 'utf8');
const html = require('../scripts/lib/page').assemble().html;
for (const needle of ['<link rel="canonical" href="https://seriesoftub.es/">', 'property="og:image"', 'name="twitter:card"', 'application/ld+json', 'rel="manifest"', 'name="description"']) {
assert.ok(html.includes(needle), `missing ${needle}`);
}
@ -37,6 +37,19 @@ test('head carries the SEO and social metadata', () => {
});
test('a release build refuses to ship without release notes', () => {
assert.throws(() => execFileSync('bash', ['scripts/build.sh'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '9.9.9', REQUIRE_NOTES: '1' } }));
assert.throws(() => execFileSync('bash', ['scripts/build.sh'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '1.0; rm -rf /' } }), 'junk versions are rejected');
assert.throws(() => execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '9.9.9', REQUIRE_NOTES: '1' } }));
assert.throws(() => execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '1.0; rm -rf /' } }), 'junk versions are rejected');
});
test('src: partials follow the layout rules (docs/adr/0002-one-page-assembled-at-build.md)', () => {
const { listFiles, assemble } = require('../scripts/lib/page');
const src = path.join(root, 'src');
for (const f of listFiles(src)) {
if (f === 'index.html' || f === 'i18n/en.js') continue;
assert.match(f, /^(styles\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.css|game\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.js)$/, `${f}: name it NN-lower-case under styles/ or game/`);
}
const { html, map } = assemble();
assert.equal((html.match(/^const ACT=\{$/gm) || []).length, 1, 'ACT is declared once; other action files use Object.assign(ACT,{…})');
assert.equal((html.match(/<script>/g) || []).length, 2, 'the language loader and the game: one inline game script');
assert.ok(map.length > 50 && map.every((m) => m.to >= m.from), 'the line map covers every partial');
});

View file

@ -1,12 +1,17 @@
// Loads site/index.html in jsdom with the animation loop disabled, so tests can
// drive the simulation directly through the game's globals (ACT, S, R, dayTick…).
// Loads the game page in jsdom with the animation loop disabled, so tests can drive the simulation
// directly through the game's globals (ACT, S, R, dayTick…). The page is assembled from src/ once per
// test process (scripts/lib/page.js), so tests always run what is in src/, never a stale build.
const fs = require('node:fs');
const path = require('node:path');
const { JSDOM, VirtualConsole } = require('jsdom');
const { assemble } = require('../scripts/lib/page');
let PAGE = null;
const page = () => PAGE || (PAGE = assemble().html);
// opts.file: a built or older page to load instead (the perf bench, the release build test).
function load(opts = {}) {
const file = opts.file || path.join(__dirname, '..', 'site', 'index.html');
const html = fs.readFileSync(file, 'utf8');
const html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page();
const errors = [];
const vc = new VirtualConsole();
vc.on('jsdomError', (e) => {
@ -25,7 +30,8 @@ function load(opts = {}) {
for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v);
if (opts.navigatorLanguage) Object.defineProperty(window.navigator, 'language', { value: opts.navigatorLanguage });
// A non-English game: jsdom does not fetch the dictionary script, so register it up front.
if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(__dirname, '..', 'site', 'i18n', opts.lang + '.js'), 'utf8')); }
// (opts.dir: the folder the dictionary comes from, e.g. a build's _site/i18n.)
if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(opts.dir || path.join(__dirname, '..', 'site', 'i18n'), opts.lang + '.js'), 'utf8')); }
window.Path2D = class { moveTo() {} lineTo() {} quadraticCurveTo() {} bezierCurveTo() {} arc() {} rect() {} closePath() {} };
// A recording 2D context, so draw code really runs under test (jsdom has no canvas).
const fake = () => { const calls = { n: 0 };

View file

@ -7,13 +7,15 @@ const { loadDict, brokenEntries } = require('../scripts/i18n-check');
const SCREENS = ['hud', 'panelBody', 'leftBody', 'modalCard', 'dashCard', 'bankCard', 'toasts', 'coach', 'hint', 'mega'];
// Drives the game through nearly every screen, every failure and every event, and returns what threw
// plus any rendered text with an unfilled {placeholder}, "undefined" or "NaN" in it.
// plus any rendered text with an unfilled {placeholder}, "undefined", "NaN" or a raw label (text shown without
// tr(), such as an N_() label from a table) in it.
function tour(ev) {
const thrown = [], leaks = new Set();
const step = (label, src) => {
try { ev(src); } catch (e) { thrown.push(`${label}: ${e.message}`); }
const txt = ev(`${JSON.stringify(SCREENS)}.map(i=>{const e=document.getElementById(i);return e?e.textContent:''}).join('\\n')`);
for (const m of txt.match(/[^\n]{0,40}(\{[a-z]\w*\}|undefined|NaN)[^\n]{0,40}/g) || []) leaks.add(m.trim());
for (const m of txt.match(/[a-z0-9_]+(\.[a-z0-9_]+)+/g) || []) if (ev(`!!EN[${JSON.stringify(m)}]`)) leaks.add(`raw label: ${m}`);
};
step('title', 'showTitle()');
step('start', 'ACT.start({});S.cash=1e8;S.lvl=4;S.day=100');
@ -70,17 +72,39 @@ test('the game starts in English unless the player or the browser asks for anoth
assert.equal(offline.ev('document.documentElement.lang'), 'en');
});
test('missing translations fall back to the English text, with placeholders filled', () => {
test('missing translations fall back to the English, with placeholders filled', () => {
const { ev } = load({ lang: 'it' });
assert.equal(ev("tr('No such text, {n} times',{n:3})"), 'No such text, 3 times');
assert.equal(ev("trn('{n} cat','{n} cats',1)"), '1 cat');
assert.equal(ev("trn('{n} cat','{n} cats',2)"), '2 cats');
ev("DICT['test.cats']=EN['test.cats']={one:'{n} cat',other:'{n} cats'}");
assert.ok(ev("Object.keys(EN).every(k=>DICT[k]===(I18N.it[k]??EN[k]))"), 'each label is Italian where there is Italian, else English');
assert.equal(ev("tr('test.no_such_label {n}',{n:3})"), 'test.no_such_label 3', 'an unknown label comes back as it is');
assert.equal(ev("trn('test.cats',1)"), '1 cat');
assert.equal(ev("trn('test.cats',2)"), '2 cats');
assert.equal(ev("trn('peering_inbox.n_day_ago',1)"), '1 giorno fa');
assert.equal(ev("trn('peering_inbox.n_day_ago',3)"), '3 giorni fa');
});
test('every Italian entry keeps the placeholders and HTML tags of its English text', () => {
const dict = loadDict(path.join(__dirname, '..', 'site', 'i18n', 'it.js'));
assert.ok(Object.keys(dict).length > 100);
assert.deepEqual(brokenEntries(dict), []);
test('text that old saves stored in English is still translated', () => {
const { ev } = load({ lang: 'it' });
assert.equal(ev("tr('Delivery: 2 to 6 weeks')"), ev("tr('pnis.delivery_2_to_6_weeks')"));
assert.equal(ev("tr('{n} days ago',{n:3})"), '3 giorni fa', 'plural forms too');
assert.equal(load().ev("tr('Delivery: 2 to 6 weeks')"), 'Delivery: 2 to 6 weeks');
});
test('every translation keeps the placeholders, HTML tags and plural forms of its English', () => {
const D = require('../scripts/lib/dict');
const en = D.read('en').dict;
for (const lang of D.langs()) {
const dict = loadDict(D.fileOf(lang));
assert.ok(Object.keys(dict).length > 100, lang);
assert.deepEqual(brokenEntries(dict, en), [], lang);
}
});
test('the static markup is translated by label', () => {
const { ev } = load({ lang: 'it' });
ev('ACT.start({})');
assert.equal(ev("document.querySelector('[data-i18n=\"common.customers\"]').textContent"), 'Clienti');
assert.equal(ev("document.querySelector('[data-act=help]').getAttribute('aria-label')"), ev("tr('common.how_to_play')"));
});
test('the language buttons on the title screen work before any game exists', () => {
@ -128,3 +152,11 @@ for (const lang of ['en', 'it', 'pt', 'fr']) {
assert.deepEqual(errors, []);
});
}
test('the translation check catches labels the build could not see, and English-keyed calls', () => {
const { sourceLabels } = require('../scripts/i18n-check');
const { problems, labels } = sourceLabels("<html><body><script>const x='pnis.foo_bar';tr('pnis.ok_label');N_('pnis.kept');trn('{n} POP','{n} POPs',n)</script></body></html>");
assert.ok(labels.has('pnis.ok_label') && labels.has('pnis.kept'));
assert.ok(problems.some((p) => p.includes('pnis.foo_bar') && p.includes('N_()')), 'a bare label');
assert.ok(problems.some((p) => p.includes('not a label')), 'English text where a label belongs');
});

View file

@ -154,7 +154,7 @@ test('the AI agent answers everything, costs $20M a year and gets it wrong a lot
ev('Math.random=()=>0.1;inboxBot()');
assert.equal(ev('S.inbox.items.length'), 0, 'inbox zero');
assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'and a route leak');
assert.ok(ev("S.inbox.log.some(e=>/They seemed nice/.test(e.m))"));
assert.ok(ev("S.inbox.log.some(e=>/They seemed nice/.test(tr(e.m,e.a)))"), 'the log keeps a label, read in the language of the player');
ev('ACT.inbox()');
assert.match(ev("document.getElementById('modalCard').textContent"), /They seemed nice/);
// and sometimes it gets it right

88
tests/pages.test.js Normal file
View file

@ -0,0 +1,88 @@
// The game is hosted on GitHub Pages and only there (docs/adr/0001-github-pages-only.md). These tests make
// sure every build stays something Pages serves as it is: plain static files, all from one origin.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const root = path.join(__dirname, '..');
const OUT = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-pages-'));
execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '1.2.3', BUILD_DATE: '2026-10-27' } });
const files = (dir, rel = '') => fs.readdirSync(path.join(dir, rel), { withFileTypes: true }).flatMap((e) => {
const r = path.posix.join(rel, e.name);
return e.isDirectory() ? files(dir, r) : [{ r, e }];
});
const built = files(OUT);
const read = (f) => fs.readFileSync(path.join(OUT, f), 'utf8');
// Files that only mean something to other hosts or to a server. On Pages they would be served as plain
// files (or ignored), so their presence means someone is designing for a different host.
const FOREIGN = /(^|\/)(_redirects|_headers|\.htaccess|netlify\.toml|vercel\.json|wrangler\.toml|firebase\.json|staticwebapp\.config\.json|now\.json|app\.yaml|Procfile|Dockerfile|nginx\.conf|server\.js|package\.json)$|\.(php|py|rb|cgi)$/;
test('pages: the build is plain static files within GitHub Pages limits', () => {
let total = 0;
for (const { r, e } of built) {
assert.ok(e.isFile(), `${r} is a regular file (no symlinks)`);
assert.doesNotMatch(r, FOREIGN, `${r} is server or other-host configuration`);
const size = fs.statSync(path.join(OUT, r)).size;
assert.ok(size < 100e6, `${r} is under the 100 MB file limit`);
total += size;
}
assert.ok(total < 1e9, 'the site is under the 1 GB limit');
for (const f of ['index.html', '404.html', 'CNAME', 'version.json', 'sw.js']) assert.ok(fs.existsSync(path.join(OUT, f)), `${f} is shipped`);
assert.equal(read('CNAME').trim(), 'seriesoftub.es');
});
test('pages: the repository has no hosting configuration for anywhere else', () => {
for (const f of fs.readdirSync(root)) assert.doesNotMatch(f, /^(netlify\.toml|vercel\.json|wrangler\.toml|firebase\.json|staticwebapp\.config\.json|now\.json|app\.yaml|Procfile|Dockerfile|_redirects|_headers)$/, `${f} configures another host`);
});
test('pages: every local file the site refers to is in the build', () => {
const html = read('index.html');
const refs = new Set();
for (const m of html.matchAll(/\b(?:src|href)="([^"]+)"/g)) refs.add(m[1]);
for (const m of read('sw.js').matchAll(/'(\/[^']*)'/g)) refs.add(m[1]);
for (const i of JSON.parse(read('site.webmanifest')).icons || []) refs.add(i.src);
const local = [...refs].filter((u) => !/^(https?:|data:|mailto:|#|\$\{|javascript:)/.test(u) && !u.includes('${') && !u.includes("'+"));
assert.ok(local.length >= 5, 'found the local references');
for (const u of local) {
const p = u.split(/[?#]/)[0].replace(/^\//, '') || 'index.html';
assert.ok(fs.existsSync(path.join(OUT, p)), `${u} resolves inside the build`);
}
// Same origin for code: the only scripts from elsewhere are the analytics counter, and no stylesheets
// but the web fonts (see the ADR).
for (const m of html.matchAll(/<script[^>]*\bsrc="(https?:[^"]+)"/g)) assert.fail(`page loads a script from ${m[1]}`);
for (const m of html.matchAll(/<link[^>]*rel="stylesheet"[^>]*href="(https?:[^"]+)"/g)) assert.match(m[1], /^https:\/\/fonts\.googleapis\.com\//);
});
test('pages: only the release workflow deploys, and only with the GitHub Pages actions', () => {
const dir = path.join(root, '.github', 'workflows');
for (const f of fs.readdirSync(dir)) {
const y = fs.readFileSync(path.join(dir, f), 'utf8');
assert.doesNotMatch(y, /netlify|vercel|wrangler|cloudflare\/pages-action|firebase deploy|surge\.sh|peaceiris\/actions-gh-pages|aws s3 sync|rsync /i, `${f} deploys somewhere other than GitHub Pages`);
if (f !== 'release.yml') assert.doesNotMatch(y, /pages:\s*write|deploy-pages/, `${f} must not deploy`);
}
const rel = fs.readFileSync(path.join(dir, 'release.yml'), 'utf8');
assert.match(rel, /actions\/upload-pages-artifact@/);
assert.match(rel, /actions\/deploy-pages@/);
assert.match(rel, /path: \.\/_site/);
});
test('pages: the shipped page and dictionaries, with labels shrunk to ids, still say the right things', () => {
const { load } = require('./harness');
const file = path.join(OUT, 'index.html'), dir = path.join(OUT, 'i18n');
assert.doesNotMatch(read('index.html'), /tr\('pnis\.delivery/, 'labels are shrunk in the shipped page');
for (const [lang, word] of [['en', 'Customers'], ['it', 'Clienti'], ['fr', null]]) {
const { ev, errors } = load(lang === 'en' ? { file } : { file, lang, dir });
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});for(let i=0;i<40;i++)dayTick();ACT.leftTab({t:'noc'});renderAll()");
const text = ev("['hud','leftBody','panelBody','modalCard','toasts'].map(i=>document.getElementById(i)?.textContent||'').join(' ')");
if (word) assert.ok(text.includes(word), `${lang}: ${word}`);
assert.doesNotMatch(text, /\b[a-z_]+\.[a-z0-9_]{6,}\b/, `${lang}: no raw labels`);
assert.equal(ev("tr(FLOOD_WHO[0])"), ev("tr('failures.a_botnet_of_40_000_smart')"), `${lang}: labels kept for saves still translate`);
assert.notEqual(ev("tr(FLOOD_WHO[0])"), 'failures.a_botnet_of_40_000_smart');
assert.deepEqual(errors, []);
}
});

View file

@ -25,7 +25,7 @@ test('perf bench: runs end to end on a small save and compares a version with it
const save = path.join(dir, 'save.json'), js = path.join(dir, 'out.json');
fs.writeFileSync(save, JSON.stringify({ app: 'series-of-tubes', version: 'test', S: JSON.parse(ev('JSON.stringify(S)')) }));
const md = execFileSync(process.execPath, [path.join(__dirname, '..', 'scripts', 'perf-bench.js'), '--save', save,
'--base', path.join(__dirname, '..', 'site', 'index.html'), '--runs', '3', '--json', js], { encoding: 'utf8' });
'--base', require('../scripts/lib/page').pageFile(path.join(dir, 'base.html')), '--runs', '3', '--json', js], { encoding: 'utf8' });
assert.match(md, /2 POPs/, 'reads an exported save');
assert.match(md, /Routing results are identical to the base/);
assert.match(md, /\| Routing: compute\(\) \|/);

View file

@ -32,7 +32,7 @@ test('leaving the page saves the game', () => {
test('returning players see what is new after an update, once', () => {
const { saved } = playedGame();
execFileSync('bash', ['scripts/build.sh'], { cwd: root, env: { ...process.env, OUT, VERSION: '1.1.0', BUILD_DATE: '2026-10-23' } });
execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, env: { ...process.env, OUT, VERSION: '1.1.0', BUILD_DATE: '2026-10-23' } });
const file = path.join(OUT, 'index.html');
const b = load({ file, storage: { 'sot-save-v1': saved, 'sot-seen-version': '1.0.0' } });
const text = b.ev("document.getElementById('modalCard').textContent");