Files
wibosim/server/src/gateway.test.js
T
db9979andClaude Opus 5.5 477b5f1ff8 Bot-Erkennung: Skripte und ferngesteuerte Browser erkennen, Menschen-Bestätigung, Admin-Ansicht
- botguard.js: Signale (ohne Browser, Skript-/Headless-UA, WebDriver, ohne Eingaben, Tempo, Gleichmäßigkeit,
  Dauerbetrieb, REST) mit abklingenden Punkten; Maßnahmen melden/prüfen/bremsen/pausieren
- Client zählt echte Eingaben, meldet sich nach der Anmeldung, zeigt die Bestätigung mit zufällig platziertem Knopf
- Admin-Menü „Bot-Erkennung“ mit Gründen, unbedenklich/zurücksetzen/sperren; Benachrichtigung per E-Mail
- Rivalen-Test: nur Zukäufe nach dem Lagebild zählen (war wackelig)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
2026-12-03 22:20:09 +00:00

190 lines
10 KiB
JavaScript

import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import WebSocket from 'ws';
const PORT = 18_000 + Math.floor(Math.random() * 2000);
const BASE = `http://127.0.0.1:${PORT}`;
let proc;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const json = async (url, opt = {}) => {
const r = await fetch(BASE + url, { ...opt, headers: { 'content-type': 'application/json', ...(opt.headers ?? {}) } });
return { status: r.status, body: await r.json().catch(() => null) };
};
function connect(headers = {}) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers });
const msgs = [];
ws.on('message', (d) => msgs.push(JSON.parse(d.toString())));
ws.on('open', () => resolve({ ws, msgs }));
ws.on('error', reject);
ws.on('unexpected-response', (_req, res) => reject(new Error(`HTTP ${res.statusCode}`)));
});
}
const waitFor = async (msgs, pred, ms = 3000) => {
const end = Date.now() + ms;
while (Date.now() < end) { const m = msgs.find(pred); if (m) return m; await sleep(20); }
throw new Error('Nachricht nicht erhalten');
};
before(async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-gw-'));
const src = path.dirname(fileURLToPath(import.meta.url));
proc = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', path.join(src, 'index.js')], {
env: { ...process.env, PORT: String(PORT), DATA_DIR: dir, TIME_MODE: 'turbo', NODE_ENV: 'test', ADMIN_SETUP_CODE: 'testcode' },
stdio: 'ignore',
});
for (let i = 0; i < 100; i++) {
try { const r = await fetch(`${BASE}/api/health`); if (r.ok) return; } catch { /* startet noch */ }
await sleep(100);
}
throw new Error('Server startet nicht');
});
after(() => proc?.kill('SIGTERM'));
test('REST: Registrierung, Anmeldung, Schutz der Admin-API', async () => {
const r = await json('/api/register', { method: 'POST', body: JSON.stringify({ name: 'Gateway', password: 'geheim123' }) });
assert.equal(r.status, 200);
assert.ok(r.body.token);
const bad = await json('/api/login', { method: 'POST', body: JSON.stringify({ name: 'Gateway', password: 'nein' }) });
assert.equal(bad.status, 400);
const adm = await json('/api/admin/overview', { headers: { authorization: `Bearer ${r.body.token}` } });
assert.equal(adm.status, 403);
const claim = await json('/api/action/claimAdmin', { method: 'POST', body: JSON.stringify({ code: 'testcode' }), headers: { authorization: `Bearer ${r.body.token}` } });
assert.equal(claim.status, 200);
const adm2 = await json('/api/admin/overview', { headers: { authorization: `Bearer ${r.body.token}` } });
assert.equal(adm2.status, 200);
const m = await fetch(`${BASE}/metrics`).then((x) => x.text());
assert.match(m, /wibosim_players 1/);
});
test('WebSocket: kaputte Nachrichten bringen den Server nicht zu Fall', async () => {
const { ws, msgs } = await connect();
await waitFor(msgs, (m) => m.type === 'hello');
for (const raw of ['null', '[]', '"x"', '{"type":1}', '{', '{"type":"order"}', '{"type":"__proto__"}', '{"type":"constructor"}', JSON.stringify({ type: 'x'.repeat(100) })]) ws.send(raw);
ws.send(JSON.stringify({ type: 'leaderboard', reqId: 7 }));
const rep = await waitFor(msgs, (m) => m.type === 'reply' && m.reqId === 7);
assert.equal(rep.ok, true);
const unk = msgs.find((m) => m.type === 'reply' && m.ok === false);
assert.ok(unk, 'unbekannte Befehle werden abgelehnt');
ws.close();
const h = await fetch(`${BASE}/api/health`);
assert.equal(h.status, 200);
});
test('WebSocket: zu große Nachricht trennt die Verbindung, Flut wird gebremst', async () => {
const a = await connect();
const closed = new Promise((r) => a.ws.on('close', r));
a.ws.send('x'.repeat(20_000));
await closed;
const b = await connect();
for (let i = 0; i < 100; i++) b.ws.send(JSON.stringify({ type: 'leaderboard', reqId: i }));
await waitFor(b.msgs, (m) => m.type === 'error' && /langsamer/.test(m.error));
b.ws.close();
});
test('WebSocket: fremde Herkunft (Origin) wird abgewiesen', async () => {
await assert.rejects(connect({ origin: 'https://boese.example' }), /HTTP 401|HTTP 403|Unexpected/);
const ok = await connect({ origin: `http://127.0.0.1:${PORT}` });
ok.ws.close();
});
test('WebSocket: Anmeldung, Order und Antwort', async () => {
const r = await json('/api/register', { method: 'POST', body: JSON.stringify({ name: 'Trader', password: 'geheim123' }) });
const { ws, msgs } = await connect();
ws.send(JSON.stringify({ type: 'auth', token: r.body.token, reqId: 1 }));
const auth = await waitFor(msgs, (m) => m.reqId === 1);
assert.equal(auth.ok, true);
assert.equal(auth.profile.name, 'Trader');
ws.send(JSON.stringify({ type: 'order', symbol: 'RHBK', side: 'buy', orderType: 'limit', qty: 1, price: 1, reqId: 2 }));
const o = await waitFor(msgs, (m) => m.reqId === 2);
assert.equal(o.ok, false, 'Limit zu weit vom Kurs');
assert.match(o.error, /20 %/);
ws.close();
});
test('Admin-Endpunkte (inkl. Nachrichtentest mit ausgehendem Aufruf) nur für Admins', async () => {
const r = await json('/api/register', { method: 'POST', body: JSON.stringify({ name: 'Kein Admin', password: 'geheim123' }) });
const h = { authorization: `Bearer ${r.body.token}` };
for (const [method, url] of [['POST', '/api/admin/newstest'], ['GET', '/api/admin/settings'], ['PUT', '/api/admin/settings'], ['GET', '/api/admin/audit'],
['POST', '/api/admin/action'], ['POST', '/api/admin/testmail'], ['POST', '/api/admin/updatecheck'], ['GET', '/api/admin/overview']]) {
const body = method === 'GET' ? undefined : JSON.stringify({ title: 'EZB erhöht Leitzins' });
assert.equal((await json(url, { method, body })).status, 401, `${method} ${url} ohne Anmeldung`);
assert.equal((await json(url, { method, body, headers: h })).status, 403, `${method} ${url} ohne Adminrechte`);
}
});
test('Prototyp-Schlüssel werden abgewiesen (WebSocket und REST)', async () => {
const bad = '{"type":"order","symbol":"RHBK","side":"buy","qty":1,"__proto__":{"x":1},"reqId":5}';
const { ws, msgs } = await connect();
ws.send(bad);
ws.send('{"type":"clans","q":{"constructor":{"prototype":{}}},"reqId":6}');
const a = await waitFor(msgs, (m) => m.reqId === 5);
const b = await waitFor(msgs, (m) => m.reqId === 6);
assert.equal(a.ok, false); assert.match(a.error, /Ungültige Anfrage/);
assert.equal(b.ok, false);
ws.close();
const r = await json('/api/action/clans', { method: 'POST', body: '{"__proto__":{"admin":true}}' });
assert.equal(r.status, 400);
assert.equal(({}).admin, undefined);
});
test('Doppelt gesendete Anfrage (gleiche reqId) wird nur einmal ausgeführt; Ratenbegrenzung je Spieler über alle Verbindungen', async () => {
const r = await json('/api/login', { method: 'POST', body: JSON.stringify({ name: 'Trader', password: 'geheim123' }) });
const conns = [await connect(), await connect(), await connect()];
for (const [i, c] of conns.entries()) {
c.ws.send(JSON.stringify({ type: 'auth', token: r.body.token, reqId: `a${i}` }));
assert.equal((await waitFor(c.msgs, (m) => m.reqId === `a${i}`)).ok, true);
}
const { ws, msgs } = conns[0];
const before = (await json('/api/action/portfolio', { method: 'POST', body: '{}', headers: { authorization: `Bearer ${r.body.token}` } })).body.portfolio.cond.length;
const order = JSON.stringify({ type: 'order', symbol: 'RHBK', side: 'sell', orderType: 'trailing', trailPct: 5, qty: 1, reqId: 'dup-1' });
ws.send(order); ws.send(order);
await waitFor(msgs, (m) => m.reqId === 'dup-1');
await sleep(200);
const replies = msgs.filter((m) => m.reqId === 'dup-1');
assert.equal(replies.length, 2, 'beide erhalten eine Antwort');
assert.deepEqual(replies[0], replies[1], 'gleiche Antwort');
const after = (await json('/api/action/portfolio', { method: 'POST', body: '{}', headers: { authorization: `Bearer ${r.body.token}` } })).body.portfolio.cond.length;
assert.equal(replies[0].ok, true, replies[0].error);
assert.equal(after - before, 1, 'nur einmal ausgeführt');
// drei Verbindungen je 35 Nachrichten (unter dem Limit je Verbindung) → Limit je Spieler greift
for (const c of conns) for (let i = 0; i < 35; i++) c.ws.send(JSON.stringify({ type: 'quests', reqId: `q${i}` }));
const end = Date.now() + 3000;
while (Date.now() < end && !conns.some((c) => c.msgs.some((m) => m.type === 'error' && /langsamer/.test(m.error)))) await sleep(20);
assert.ok(conns.some((c) => c.msgs.some((m) => m.type === 'error' && /langsamer/.test(m.error))), 'Limit je Spieler greift');
for (const c of conns) c.ws.close();
});
test('Bot-Erkennung: Skript-Client ohne Browser wird markiert, um Bestätigung gebeten und im Admin-Menü gelistet', async () => {
const r = await json('/api/register', { method: 'POST', body: JSON.stringify({ name: 'Skriptie', password: 'geheim123' }) });
const { ws, msgs } = await connect();
ws.send(JSON.stringify({ type: 'auth', token: r.body.token, reqId: 1 }));
await waitFor(msgs, (m) => m.reqId === 1);
let check = null;
for (let i = 0; i < 12 && !check; i++) {
ws.send(JSON.stringify({ type: 'cancel', orderId: 'x', reqId: 100 + i }));
const rep = await waitFor(msgs, (m) => m.reqId === 100 + i);
if (rep.humanCheck) check = rep;
}
assert.ok(check, 'Menschen-Bestätigung verlangt');
assert.match(check.error, /bestätige/);
// per Skript „geklickt“ besteht nicht
ws.send(JSON.stringify({ type: 'humanCheck', nonce: check.humanCheck, ms: 3, trusted: false, reqId: 200 }));
const hc = await waitFor(msgs, (m) => m.reqId === 200);
assert.equal(hc.passed, false);
ws.close();
const login = await json('/api/login', { method: 'POST', body: JSON.stringify({ name: 'Gateway', password: 'geheim123' }) });
const list = await json('/api/admin/bots', { headers: { authorization: `Bearer ${login.body.token}` } });
assert.equal(list.status, 200);
const me = list.body.list.find((b) => b.name === 'Skriptie');
assert.ok(me && me.level === 'verdacht', 'im Admin-Menü als Verdacht gelistet');
const ok = await json(`/api/admin/bots/${encodeURIComponent(me.id)}`, { method: 'POST', body: JSON.stringify({ action: 'botOk' }), headers: { authorization: `Bearer ${login.body.token}` } });
assert.equal(ok.status, 200);
});