Upstream/test/review-fixes.test.js
jvanvik 3c23c51902 Phase 4: close loot/refund leaks, landing-site garrisons, speed-scaled shipping, update/offsite tooling, broad e2e
Built:
- Economy: raid loot capped to the room the raiders have at home (rest stays with the victim, "lootLeft" in the report); trade escrow reserves its room so refunds always fit; trade accept refuses with no_room_for_goods when the goods would not fit. Loot destroyed per 30-day run 31-61k -> ~1k, refunds clipped ~27k -> 0 (docs/BALANCE.md, 3 seeds).
- End game: members of the holding alliance garrison landing sites (migration 005_site_garrison.sql), garrison counts in site defence, 72 h capture shield, withdraw route, POP view lists garrisoned units. Shipping capacity scales with world speed (3x world: winner 76-98 -> ~30-36 days after sites open). Bot runs show real contests (84-194 attacks on held sites at 1x).
- Ops: deploy/update.sh (backup, stop, ff-merge, npm ci --ignore-scripts, health check, rollback), deploy/upstream-offsite (rsync only), admin end-world snapshots results, EPIPE fix, docs/workflows/ filled in.
- e2e 62 -> 163 checks: units, raids/reports, alliance+messages, trade, end game, nb, PWA, reconnect, slow polling fallback (opt-in). Two app bugs found: message push ignored, "New" button stayed English.

Tested: npm test 274/274, openapi check, npm run e2e 163/163 (137 s), bot runs 50x30d seeds 1-3 and 140-day/60-day speed-3 end-game runs INVARIANTS OK, adversarial review pass (findings fixed or documented).
NOT tested: update.sh on a real box (systemd, real npm, runuser; stubs only, shellcheck not installed), garrison card/loot text on a phone, Node 22.13, humans. Known leaks left open and documented (BALANCE S6): loot/shipments can still overflow when stock arrives in flight, bounced backbone shipments lose overflow (reported to the sender). Garrison numbers (heldDefenceMult 2, shield 72 h) are first guesses from 2 seeds. Not claimed: balanced.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-12 00:58:12 +02:00

97 lines
5.7 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/* Regression tests for the adversarial review findings (each failed before its fix). */
const test = require('node:test');
const assert = require('node:assert');
const { createTestServer } = require('./helpers');
const { validate } = require('../server/validate');
const { limitKey, Limiter } = require('../server/http');
test('validate: __proto__ / constructor keys are rejected, also inside pass-through objects', () => {
const s = { type: 'object', properties: { cargo: { type: 'object', additionalProperties: true } }, additionalProperties: false };
assert.ok(!validate(s, JSON.parse('{"__proto__": {"x": 1}}')).ok);
assert.ok(!validate(s, JSON.parse('{"cargo": {"fiber": 1, "__proto__": {"hardware": 50000}}}')).ok);
assert.ok(!validate(s, JSON.parse('{"cargo": {"a": {"constructor": 1}}}')).ok);
assert.ok(validate(s, { cargo: { fiber: 1 } }).ok);
});
test('transport: a prototype-smuggled cargo cannot dodge the capacity limit over HTTP', async () => {
const t = await createTestServer();
try {
const a = await t.signup('alice'), b = await t.signup('bobby');
const raw = '{"fromTownId":' + a.townId + ',"toTownId":' + b.townId + ',"type":"transport","cargo":{"fiber":1,"__proto__":{"hardware":50000,"capital":50000}}}';
const r = await fetch('http://127.0.0.1:' + t.srv.port + '/api/v1/movements', { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + a.token }, body: raw });
assert.ok(r.status === 422 || r.status === 400, 'got ' + r.status);
} finally { await t.close(); }
});
test('trade legs cannot be recalled (either side could otherwise keep both halves of the deal)', async () => {
const t = await createTestServer();
try {
const a = await t.signup('alice'), b = await t.signup('bobby');
for (const u of [a, b]) t.setBuilding(u.townId, 'internet_exchange', 3);
const made = await t.api('/trade/offers', { method: 'POST', body: { townId: a.townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 60 } }, a.token);
assert.equal(made.status, 201, JSON.stringify(made.body));
t.srv.db.run('UPDATE towns SET fiber = 0 WHERE id = ?', b.townId); // room for the goods (accept refuses a full hall)
const acc = await t.api('/trade/offers/' + made.body.offer.id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token);
assert.equal(acc.status, 201, JSON.stringify(acc.body));
const legs = t.srv.db.all("SELECT id, owner_id FROM movements WHERE type = 'transport' AND status = 'out'");
assert.equal(legs.length, 2);
for (const leg of legs) {
const token = leg.owner_id === a.operatorId ? a.token : b.token;
const r = await t.api('/movements/' + leg.id + '/recall', { method: 'POST' }, token);
assert.equal(r.status, 409, 'leg ' + leg.id + ' -> ' + JSON.stringify(r.body));
}
} finally { await t.close(); }
});
test('limiter: IPv6 clients share one bucket per /64; a throttled key is not forgotten when many others appear', () => {
assert.equal(limitKey('2001:db8:1:2:aaaa:bbbb:cccc:dddd'), limitKey('2001:db8:1:2::1'));
assert.notEqual(limitKey('2001:db8:1:3::1'), limitKey('2001:db8:1:2::1'));
assert.equal(limitKey('203.0.113.9'), '203.0.113.9');
const l = new Limiter(0.0001, 2, 50);
assert.ok(l.take('bad')); assert.ok(l.take('bad')); assert.ok(!l.take('bad'));
for (let i = 0; i < 200; i++) { l.take('k' + i); l.take('bad'); } // 'bad' keeps knocking: stays recent, stays throttled
assert.ok(!l.take('bad'));
});
test('static files carry CSP, nosniff and no-referrer; connect-src is self only', async () => {
const t = await createTestServer();
try {
for (const p of ['/', '/js/main.js', '/css/style.css', '/nope']) {
const r = await fetch('http://127.0.0.1:' + t.srv.port + p);
assert.ok(r.headers.get('content-security-policy'), p + ' has a CSP');
assert.equal(r.headers.get('x-content-type-options'), 'nosniff');
assert.equal(r.headers.get('referrer-policy'), 'no-referrer');
assert.ok(!/ws:|wss:/.test(r.headers.get('content-security-policy')));
}
} finally { await t.close(); }
});
test('rename: invisible and bidi characters are stripped like every other player text', async () => {
const t = await createTestServer();
try {
const a = await t.signup('alice');
const r = await t.api('/towns/' + a.townId + '/rename', { method: 'POST', body: { name: 'A‮BC​D' } }, a.token);
assert.equal(r.status, 200);
assert.equal(r.body.name, 'ABCD');
const blank = await t.api('/towns/' + a.townId + '/rename', { method: 'POST', body: { name: '​​​' } }, a.token);
assert.equal(blank.status, 422);
} finally { await t.close(); }
});
test('trade escrow refund never lifts stock above the Rack hall cap', async () => {
const t = await createTestServer();
try {
const a = await t.signup('alice');
t.setBuilding(a.townId, 'internet_exchange', 3);
const R = require('../public/js/rules.js');
const mk = () => t.api('/trade/offers', { method: 'POST', body: { townId: a.townId, giveRes: 'fiber', giveAmount: 350, wantRes: 'hardware', wantAmount: 300, maxDistance: 40 } }, a.token);
const o1 = await mk(), o2 = await mk();
assert.equal(o1.status, 201); assert.equal(o2.status, 201, JSON.stringify(o2.body));
t.clock.advance(100 * 3600e3); // production refills the stock to the cap
for (const o of [o1, o2]) await t.api('/trade/offers/' + o.body.offer.id, { method: 'DELETE' }, a.token);
const town = require('../server/state').loadTown(t.srv.db, a.townId);
const cap = R.storageCap(town);
assert.ok(R.resourcesAt(town, t.clock.now()).amounts.fiber <= cap + 1e-6, 'fiber stays <= cap ' + cap);
} finally { await t.close(); }
});