mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-06 21:44:09 +01:00
- Ratenbegrenzung galt nur je Verbindung: mit mehreren Verbindungen ließ sich das Limit vervielfachen. Neu: gemeinsamer Token-Bucket je Spieler für WebSocket und REST (Burst 60, 20/s) und höchstens 10 Verbindungen je Spieler. - Gleiche reqId einer verändernden Anfrage auf derselben Verbindung (doppelt zugestellt/wiederholt) wird nicht erneut ausgeführt, die Antwort wiederholt. - Nachrichten und REST-Bodys mit __proto__/constructor/prototype oder zu tiefer Verschachtelung werden abgewiesen; reqId auf 64 Zeichen begrenzt. - Einrichtungscode: höchstens 5 Fehlversuche je Spieler in 15 Minuten. - Login-Sperren: Aufräumen der Fehlversuchstabelle hob bisher alle Sperren auf (1000 Fehlversuche mit Fantasienamen genügten). Jetzt bleiben laufende Sperren erhalten. - Sprachmodell-Endpunkt aus ENV wird ebenfalls nur als http(s) verwendet. - Tests: alle Admin-Endpunkte (inkl. newstest) ohne Anmeldung 401, ohne Adminrechte 403. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
224 lines
12 KiB
JavaScript
224 lines
12 KiB
JavaScript
// Härtung: Eingabeprüfung, Geheimnisse, Prototype-Pollution, Buchhaltungsfehler (Regressionstests)
|
||
import { test } from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import os from 'node:os';
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
process.env.NODE_ENV = 'test';
|
||
process.env.TIME_MODE = 'turbo';
|
||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-sec-'));
|
||
process.env.LLM_API_KEY = 'sk-geheim-aus-env';
|
||
process.env.SMTP_PASS = 'smtp-geheim-aus-env';
|
||
const { settings, updateSettings, publicSettings } = await import('./settings.js');
|
||
const { Store } = await import('./store.js');
|
||
const { Game } = await import('./game.js');
|
||
|
||
Object.assign(settings.game, { dayMs: 60_000, tickMs: 1000, staticCorridor: 0.5, dynamicCorridor: 0.3, marketHaltPct: 0.5, recallsEnabled: false });
|
||
settings.news.enabled = false;
|
||
|
||
function setup(dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-s-')), t0 = Date.now()) {
|
||
const clock = { t: t0 };
|
||
const store = new Store(dir);
|
||
const g = new Game({ store, now: () => clock.t });
|
||
return { g, clock, dir, store };
|
||
}
|
||
const step = ({ g, clock }, n = 1) => { for (let i = 0; i < n; i++) { clock.t += 1000; g.tick(); } };
|
||
const until = (ctx, pred, max = 400) => { for (let i = 0; i < max && !pred(); i++) step(ctx); assert.ok(pred(), 'Bedingung nicht erreicht'); };
|
||
const toContinuous = (ctx) => until(ctx, () => ctx.g.market.phase === 'continuous');
|
||
const player = async (g, name) => (await g.register({ name, password: 'geheim123' })).player;
|
||
|
||
test('Einstellungen: Geheimnisse nie im Klartext (Werte und Vorgaben), maskiert = unverändert', () => {
|
||
updateSettings({ news: { llmKey: 'sk-neu-123' }, smtp: { pass: 'pw-neu' } });
|
||
const pub = JSON.stringify(publicSettings());
|
||
for (const secret of ['sk-neu-123', 'pw-neu', 'sk-geheim-aus-env', 'smtp-geheim-aus-env']) assert.ok(!pub.includes(secret), `${secret} darf nicht ausgeliefert werden`);
|
||
assert.equal(publicSettings().values.news.llmKey, '••••••');
|
||
assert.equal(publicSettings().schema.news.llmKey.default, '••••••');
|
||
updateSettings({ news: { llmKey: '••••••' } });
|
||
assert.equal(settings.news.llmKey, 'sk-neu-123', 'Maske lässt den Wert unverändert');
|
||
updateSettings({ news: { llmKey: '' } });
|
||
assert.equal(publicSettings().values.news.llmKey, '');
|
||
});
|
||
|
||
test('Einstellungen: Sprachmodell-Endpunkt, Feeds und Links nur http(s); Aufzählungen ohne Prototyp-Schlüssel', () => {
|
||
for (const bad of ['file:///etc/passwd', 'javascript:alert(1)', 'gopher://x', 'ftp://host/v1', 'http://user:pw@host/v1', 'http//kaputt']) {
|
||
assert.throws(() => updateSettings({ news: { llmUrl: bad } }), /Format ungültig|http/, bad);
|
||
}
|
||
updateSettings({ news: { llmUrl: 'http://192.168.178.30:11434/v1' } });
|
||
assert.equal(settings.news.llmUrl, 'http://192.168.178.30:11434/v1');
|
||
updateSettings({ news: { llmUrl: '' } });
|
||
assert.throws(() => updateSettings({ news: { feeds: ['https://example.org/rss', 'file:///etc/passwd'] } }), /http/);
|
||
assert.throws(() => updateSettings({ smtp: { baseUrl: 'javascript:alert(1)' } }), /http/);
|
||
for (const v of ['constructor', '__proto__', 'toString', 'hasOwnProperty']) {
|
||
assert.throws(() => updateSettings({ game: { timeMode: v } }), /ungültiger Wert/, v);
|
||
assert.throws(() => updateSettings({ game: { scenario: v } }), /ungültiger Wert/, v);
|
||
}
|
||
const before = JSON.stringify(settings);
|
||
const r = updateSettings(JSON.parse('{"game": {"__proto__": {"polluted": 1}, "constructor": {"x": 1}}}'));
|
||
assert.deepEqual(r.changed, []);
|
||
assert.equal(JSON.stringify(settings), before);
|
||
assert.equal(({}).polluted, undefined);
|
||
});
|
||
|
||
test('Bracket: Auslöser müssen endlich und marktnah sein (Infinity würde nach dem Neustart als null sofort auslösen)', async () => {
|
||
const ctx = setup();
|
||
const { g } = ctx;
|
||
const a = await player(g, 'Bracket');
|
||
toContinuous(ctx);
|
||
const last = g.stocks.get('RHBK').last;
|
||
for (const b of [{ tpTrigger: 'Infinity' }, { tpTrigger: 1e300 }, { stopTrigger: last * 0.001 }, { stopTrigger: '-Infinity' }]) {
|
||
assert.throws(() => g.placeOrder(a, { symbol: 'RHBK', side: 'buy', type: 'market', qty: 5, bracket: b }), /Bracket/, JSON.stringify(b));
|
||
}
|
||
assert.equal(g.ex.condOrders.length, 0);
|
||
assert.equal(a.positions.RHBK, undefined, 'abgelehnte Order wurde nicht ausgeführt');
|
||
g.placeOrder(a, { symbol: 'RHBK', side: 'buy', type: 'market', qty: 5, bracket: { stopTrigger: last * 0.9, tpTrigger: last * 1.1 } });
|
||
assert.equal(g.ex.condOrders.length, 2);
|
||
});
|
||
|
||
test('Andienung: angediente Aktien sind gesperrt, verkaufte nicht andienbar (kein ungewollter Leerverkauf)', async () => {
|
||
const ctx = setup();
|
||
const { g } = ctx;
|
||
settings.game.shortingEnabled = false;
|
||
try {
|
||
const a = await player(g, 'Andienerin');
|
||
toContinuous(ctx);
|
||
g.placeOrder(a, { symbol: 'GRNH', side: 'buy', type: 'market', qty: 100 });
|
||
assert.equal(a.positions.GRNH.qty, 100);
|
||
const o = g.corp.takeover('GRNH', 'HLIO');
|
||
const hi = Math.round(g.stocks.get('GRNH').last * 1.15 * 100) / 100;
|
||
// ruhende Verkaufsorder über 60 Stück → nur noch 40 andienbar
|
||
g.placeOrder(a, { symbol: 'GRNH', side: 'sell', type: 'limit', qty: 60, price: hi, tif: 'gtc' });
|
||
assert.throws(() => g.corp.tender(a, 'GRNH', 100), /nur 40/);
|
||
g.corp.tender(a, 'GRNH', 40);
|
||
// die angedienten 40 dürfen nicht zusätzlich verkauft werden (wäre nach der Abrechnung ein Leerverkauf)
|
||
assert.throws(() => g.placeOrder(a, { symbol: 'GRNH', side: 'sell', type: 'limit', qty: 10, price: hi, tif: 'gtc' }), /Leerverkäufe/);
|
||
o.p = 1; o.endDay = g.day;
|
||
g.corp.newDay();
|
||
assert.equal(a.positions.GRNH.qty, 60);
|
||
} finally { settings.game.shortingEnabled = true; }
|
||
});
|
||
|
||
test('Lobbyspende und Parteigründung: gebundene Leerverkaufserlöse sind kein freies Geld', async () => {
|
||
const ctx = setup();
|
||
const { g } = ctx;
|
||
const a = await player(g, 'Lobbyist');
|
||
toContinuous(ctx);
|
||
const s = g.stocks.get('RHBK');
|
||
g.placeOrder(a, { symbol: 'RHBK', side: 'sell', type: 'market', qty: Math.floor(150_000 / s.last) });
|
||
// Bargeld ≈ 250.000 €, davon ≈ 150.000 € als Sicherheit gebunden → frei ≈ 100.000 €
|
||
assert.ok(a.cash > 200_000);
|
||
const partyId = g.gov.view(a).parties.find((x) => x.npc).id;
|
||
assert.throws(() => g.gov.lobbyDonate(a, { partyId, amount: 200_000, sector: 'banks' }), /Nicht genug/);
|
||
for (const sector of ['__proto__', 'constructor', 'toString']) assert.throws(() => g.gov.lobbyDonate(a, { partyId, amount: 6000, sector }), /Sektor/);
|
||
g.gov.lobbyDonate(a, { partyId, amount: 6000, sector: 'banks' });
|
||
assert.ok(g.margin(a).equity > 0);
|
||
assert.equal(g.gov.interest.constructor, Object, 'keine Prototyp-Schlüssel im Lobbyregister');
|
||
});
|
||
|
||
test('Battles: Modus nur aus der Liste (keine Prototyp-Schlüssel)', async () => {
|
||
const ctx = setup();
|
||
const { g } = ctx;
|
||
const [a, b] = [await player(g, 'Modus1'), await player(g, 'Modus2')];
|
||
for (const mode of ['__proto__', 'constructor', 'toString', 'hasOwnProperty']) {
|
||
assert.throws(() => g.bat.queueJoin(a, mode, 5, true), /Battle-Modus/, mode);
|
||
assert.throws(() => g.bat.challenge(a, 'Modus2', 5, mode), /Battle-Modus/, mode);
|
||
assert.throws(() => g.tour.create(a, { name: 'Turnier', size: 4, mode, durationMin: 5, signupMin: 10 }), /Battle-Modus/, mode);
|
||
}
|
||
assert.equal(g.bat.active(a.id), undefined);
|
||
assert.equal(g.battleAccounts.size, 0);
|
||
void b;
|
||
});
|
||
|
||
test('Battles: Absturz kurz nach dem Start – Battle und Battle-Depot bleiben zusammen, verwaiste Depots werden entfernt', async () => {
|
||
const ctx = setup();
|
||
const { g, dir, clock } = ctx;
|
||
const a = await player(g, 'Absturz');
|
||
toContinuous(ctx);
|
||
g.flush(true); // Metadaten gerade gespeichert → nächster Meta-Schnappschuss erst in 60 s
|
||
g.bat.queueJoin(a, 'arena', 5, true);
|
||
const bt = g.bat.active(a.id);
|
||
const accId = bt.aAcc;
|
||
const s = g.stocks.get('RHBK');
|
||
g.placeOrder(a, { symbol: 'RHBK', side: 'buy', type: 'limit', qty: 5, price: Math.round(s.last * 0.9 * 100) / 100, tif: 'gtc', account: 'battle' });
|
||
g.flush(); // normaler Takt-Flush, dann „Absturz“ (kein flush(true))
|
||
const g2 = new Game({ store: new Store(dir), now: () => clock.t });
|
||
const bt2 = g2.bat.active(a.id);
|
||
assert.ok(bt2, 'laufendes Battle überlebt den Absturz');
|
||
assert.equal(bt2.aAcc, accId);
|
||
assert.ok(g2.battleAccounts.get(accId));
|
||
assert.equal(g2.portfolio(g2.battleAccounts.get(accId)).orders.length, 1);
|
||
|
||
// verwaistes Battle-Depot (Battle fehlt) wird beim Laden mitsamt Orders entfernt
|
||
g2.bat.list = g2.bat.list.filter((x) => x.id !== bt2.id);
|
||
g2.flush(true);
|
||
const g3 = new Game({ store: new Store(dir), now: () => clock.t });
|
||
assert.equal(g3.battleAccounts.get(accId), undefined, 'verwaistes Battle-Depot entfernt');
|
||
assert.equal(g3.stocks.get('RHBK').book.openOrdersOf(accId).length, 0, 'keine herrenlosen Orders im Buch');
|
||
g3.flush(true);
|
||
const g4 = new Game({ store: new Store(dir), now: () => clock.t });
|
||
assert.equal(g4.battleAccounts.get(accId), undefined, 'auch aus der Datenbank gelöscht');
|
||
});
|
||
|
||
test('Clan-Fonds: kein Einstieg zu NAV 0 (unendlich viele Anteile), Beträge nur endlich', async () => {
|
||
const { g } = setup();
|
||
const [m, x] = [await player(g, 'Managerin'), await player(g, 'Anlegerx')];
|
||
const c = g.clubs.create(m, { name: 'Nullfonds', tag: 'NUL', open: true });
|
||
g.clubs.join(x, c.id);
|
||
const acc = g.clubs.openFund(m);
|
||
g.clubs.invest(x, 1000);
|
||
for (const amount of ['Infinity', 1e400, NaN, -500, '1e999']) assert.throws(() => g.clubs.invest(x, amount), /Mindestbetrag/, String(amount));
|
||
acc.cash = 0; // Totalverlust: Eigenkapital 0 bei ausgegebenen Anteilen
|
||
assert.throws(() => g.clubs.invest(m, 1000), /Anteilswert/);
|
||
assert.ok(Number.isFinite(acc.totalUnits));
|
||
for (const u of Object.values(acc.units)) assert.ok(Number.isFinite(u));
|
||
});
|
||
|
||
test('Admin-Einrichtungscode: nach 5 Fehlversuchen gesperrt; Login-Sperren überleben das Aufräumen', async () => {
|
||
const { g } = setup();
|
||
const a = await player(g, 'Rater');
|
||
for (let i = 0; i < 5; i++) assert.throws(() => g.claimAdmin(a, `falsch${i}`), /falsch/);
|
||
assert.throws(() => g.claimAdmin(a, g.setupCode), /Fehlversuche/, 'auch der richtige Code hilft während der Sperre nicht');
|
||
const b = await player(g, 'Ehrlich');
|
||
g.claimAdmin(b, g.setupCode);
|
||
assert.equal(b.isAdmin, true);
|
||
// Sperre nach 10 Fehlversuchen bleibt, auch wenn ein Angreifer die Tabelle mit anderen Namen flutet
|
||
for (let i = 0; i < 10; i++) g.sessions.failed('Ehrlich');
|
||
for (let i = 0; i < 1200; i++) g.sessions.failed(`flut${i}`);
|
||
g.sessions.drain();
|
||
assert.equal(g.sessions.locked('Ehrlich'), true);
|
||
});
|
||
|
||
test('Sicherungen: Rotation und Wiederherstellung nach Alter, nicht nach Dateiname', () => {
|
||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-bk-'));
|
||
const store = new Store(dir, { backups: 3 });
|
||
const now = Date.now() / 1000;
|
||
['a', 'b', 'c'].forEach((x, i) => {
|
||
const f = store.backup(`manuell-${x}`);
|
||
fs.utimesSync(path.join(dir, 'backups', f), now - 1000 + i, now - 1000 + i); // älter als die Tagessicherung
|
||
});
|
||
const daily = store.backup('2026-12-03');
|
||
const list = store.backups();
|
||
assert.equal(list.length, 3);
|
||
assert.equal(list[0], daily, 'neueste Sicherung zuerst (wird bei defekter Datenbank wiederhergestellt)');
|
||
assert.ok(!list.includes('wibosim-manuell-a.db'), 'älteste Sicherung entfernt');
|
||
store.close();
|
||
});
|
||
|
||
test('Speichern schlägt fehl: Fills gehen nicht verloren, nächster Takt holt alles nach', async () => {
|
||
const ctx = setup();
|
||
const { g, dir, clock } = ctx;
|
||
const a = await player(g, 'Journal');
|
||
toContinuous(ctx);
|
||
g.flush(true);
|
||
g.placeOrder(a, { symbol: 'RHBK', side: 'buy', type: 'market', qty: 7 });
|
||
const write = g.store.write.bind(g.store);
|
||
g.store.write = () => { throw new Error('Datenträger voll'); };
|
||
assert.throws(() => g.flush(), /Datenträger voll/);
|
||
g.store.write = write;
|
||
g.flush(true);
|
||
const rows = g.store.journal(a.id, g.season.n);
|
||
assert.ok(rows.some((r) => r.symbol === 'RHBK' && r.side === 'buy' && r.qty > 0), 'Kauf im Journal');
|
||
const g2 = new Game({ store: new Store(dir), now: () => clock.t });
|
||
assert.equal(g2.players.get(a.id).positions.RHBK.qty, 7);
|
||
});
|