mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-06 13:34:09 +01:00
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
257 lines
13 KiB
JavaScript
257 lines
13 KiB
JavaScript
// Bot-Erkennung: Erkennt Spielerkonten, die von Skripten oder Bots gesteuert werden (statt von Menschen im Browser).
|
||
// Bewertet nur Verhalten und technische Merkmale der Verbindung – keine Inhalte. Rivalen (computergesteuert) sind ausgenommen.
|
||
//
|
||
// Signale (jeweils mit Punkten, die über die Zeit abklingen):
|
||
// - Verbindung ohne Browser (kein Origin-Header) oder Skript-/Headless-Kennung im User-Agent
|
||
// - Browser meldet Fernsteuerung (navigator.webdriver) oder der Spiel-Client meldet sich nie
|
||
// - Handelsbefehle ohne jede Maus-/Tastatur-/Touch-Eingabe davor (Konsole oder eigenes Programm)
|
||
// - übermenschliches Tempo (viele Orders je Sekunde/Minute) und maschinell gleichmäßige Abstände
|
||
// - Dauerbetrieb rund um die Uhr, Nutzung der REST-Schnittstelle für Spielaktionen
|
||
// Ab einer Schwelle wird der Spieler gemeldet und – je nach Einstellung – um eine kurze Menschen-Bestätigung gebeten,
|
||
// gebremst oder für den Handel pausiert. Admins können ein Konto als unbedenklich markieren.
|
||
import { uid } from './util.js';
|
||
|
||
export const BOT_SIGNALS = {
|
||
noOrigin: { pts: 25, label: 'Verbindung ohne Browser (kein Origin-Header)' },
|
||
scriptUa: { pts: 20, label: 'Skript- oder Headless-Kennung im User-Agent' },
|
||
webdriver: { pts: 40, label: 'Browser wird ferngesteuert (WebDriver/Automatisierung)' },
|
||
noClient: { pts: 15, label: 'Offizieller Spiel-Client hat sich nie gemeldet' },
|
||
noInput: { pts: 25, label: 'Handelsbefehle ohne Maus-, Tastatur- oder Touch-Eingabe' },
|
||
burst: { pts: 20, label: 'Übermenschliches Tempo (mehrere Orders pro Sekunde)' },
|
||
rate: { pts: 20, label: 'Dauerhaft sehr viele Orders pro Minute' },
|
||
regular: { pts: 25, label: 'Maschinell gleichmäßige Abstände zwischen Befehlen' },
|
||
nonstop: { pts: 15, label: 'Aktiv in fast allen Stunden eines Tages' },
|
||
rest: { pts: 10, label: 'Spielaktionen über die REST-Schnittstelle' },
|
||
failedCheck: { pts: 20, label: 'Menschen-Bestätigung nicht bestanden' },
|
||
};
|
||
|
||
export const BOT_ACTIONS = { melden: 'Nur melden', pruefen: 'Menschen-Bestätigung verlangen', bremsen: 'Bremsen (wenige Befehle pro Minute)', pausieren: 'Handel pausieren bis zur Freigabe' };
|
||
|
||
const SCRIPT_UA = /python|curl|wget|httpie|postman|insomnia|axios|node-fetch|undici|got\/|go-http|okhttp|java\/|libwww|scrapy|aiohttp|requests|headless|phantom|selenium|puppeteer|playwright|webdriver|bot\b|spider|crawler/i;
|
||
/** Befehle, an denen Automatisierung gemessen wird (Handel und spielrelevante Klicks) */
|
||
export const WATCHED = new Set(['order', 'cancel', 'cancelAll', 'tender', 'squeezeOut', 'ipoSubscribe', 'agmVote', 'predictTip', 'vote', 'electionVote',
|
||
'challenge', 'respond', 'rematch', 'queue', 'alertAdd', 'analysisPost', 'analysisLike', 'comment', 'follow', 'lobby', 'derivOrder', 'dmSend']);
|
||
const HALF_LIFE_MS = 24 * 3_600_000;
|
||
const HOUR = 3_600_000;
|
||
|
||
export class BotGuard {
|
||
/**
|
||
* @param {{ cfg: () => any, dirty?: (p: any) => void, notifyAdmins?: (subject: string, text: string) => void, onFlag?: (p: any, info: any) => void, now?: () => number }} opt
|
||
*/
|
||
constructor({ cfg, notifyAdmins = () => {}, onFlag = () => {}, dirty = () => {}, now = () => Date.now() }) {
|
||
this.cfg = cfg;
|
||
this.dirty = dirty;
|
||
this.notifyAdmins = notifyAdmins;
|
||
this.onFlag = onFlag;
|
||
this.now = now;
|
||
this.live = new Map(); // pid → { times[], noInput[], hours: Map(hourKey→true), clientSeen, firstWatched, challenge }
|
||
this.log = []; // letzte Meldungen für das Admin-Menü
|
||
}
|
||
|
||
#exempt(p) { return !p || p.rival || p.botOk || !this.cfg().botDetect; }
|
||
#live(pid) {
|
||
let l = this.live.get(pid);
|
||
if (!l) this.live.set(pid, (l = { times: [], inputs: [], hours: new Map(), clientSeen: false, firstWatched: 0, challenge: null, lastSlow: [] }));
|
||
return l;
|
||
}
|
||
#state(p) { return (p.bot ??= { score: 0, signals: {}, level: 'ok', since: 0, notifiedAt: 0, checks: 0 }); }
|
||
|
||
/** Punkte abklingen lassen und Score neu berechnen */
|
||
#decay(p) {
|
||
const b = this.#state(p), now = this.now();
|
||
let score = 0;
|
||
for (const [k, s] of Object.entries(b.signals)) {
|
||
const f = Math.pow(0.5, (now - s.ts) / HALF_LIFE_MS);
|
||
s.pts *= f; s.ts = now;
|
||
if (s.pts < 0.5) { delete b.signals[k]; continue; }
|
||
score += s.pts;
|
||
}
|
||
b.score = Math.min(100, Math.round(score));
|
||
return b;
|
||
}
|
||
|
||
/** Signal vergeben (höchstens ein Mal je `everyMs` pro Signal, Punkte gedeckelt auf das Dreifache) */
|
||
signal(p, key, detail = '', everyMs = 10 * 60_000) {
|
||
if (this.#exempt(p) || !BOT_SIGNALS[key]) return;
|
||
const b = this.#decay(p), now = this.now();
|
||
const s = (b.signals[key] ??= { pts: 0, ts: now, n: 0, last: 0, detail: '' });
|
||
if (now - s.last < everyMs) return;
|
||
s.pts = Math.min(BOT_SIGNALS[key].pts * 3, s.pts + BOT_SIGNALS[key].pts);
|
||
s.n++; s.last = now; s.detail = String(detail).slice(0, 160);
|
||
this.#evaluate(p);
|
||
this.dirty(p);
|
||
}
|
||
|
||
#evaluate(p) {
|
||
const b = this.#decay(p), c = this.cfg(), now = this.now();
|
||
const prev = b.level;
|
||
b.level = b.score >= c.botThreshold ? 'verdacht' : b.score >= c.botThreshold / 2 ? 'auffaellig' : 'ok';
|
||
if (b.level === 'verdacht' && prev !== 'verdacht') {
|
||
b.since = now;
|
||
const top = Object.entries(b.signals).sort((x, y) => y[1].pts - x[1].pts).map(([k, s]) => `${BOT_SIGNALS[k].label}${s.detail ? ` (${s.detail})` : ''}`);
|
||
const entry = { id: uid(6), ts: now, pid: p.id, name: p.name, score: b.score, signals: top, action: c.botAction };
|
||
this.log.unshift(entry);
|
||
if (this.log.length > 200) this.log.length = 200;
|
||
if (now - b.notifiedAt > 12 * HOUR) {
|
||
b.notifiedAt = now;
|
||
this.notifyAdmins(`Bot-Verdacht: ${p.name} (${b.score} Punkte)`,
|
||
`Die Bot-Erkennung hat das Konto „${p.name}“ markiert (${b.score} von 100 Punkten).\n\nAuffälligkeiten:\n- ${top.join('\n- ')}\n\n`
|
||
+ `Eingestellte Maßnahme: ${BOT_ACTIONS[c.botAction] ?? c.botAction}.\nIm Admin-Menü unter „Spieler → Bot-Erkennung“ kannst du das Konto als unbedenklich markieren, zurücksetzen oder sperren.`);
|
||
}
|
||
if (c.botAction === 'pruefen') this.#challenge(p);
|
||
this.onFlag(p, entry);
|
||
}
|
||
}
|
||
|
||
#challenge(p) {
|
||
const l = this.#live(p.id);
|
||
if (!l.challenge || this.now() - l.challenge.at > 10 * 60_000) l.challenge = { nonce: uid(8), at: this.now() };
|
||
return l.challenge;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ Eingänge vom Server
|
||
/** Neue Verbindung angemeldet */
|
||
connect(p, { origin, ua }) {
|
||
if (this.#exempt(p)) return;
|
||
if (!origin) this.signal(p, 'noOrigin', ua ? String(ua).slice(0, 60) : 'ohne User-Agent', HOUR);
|
||
if (!ua || SCRIPT_UA.test(ua)) this.signal(p, 'scriptUa', ua ? String(ua).slice(0, 60) : 'leer', HOUR);
|
||
}
|
||
|
||
/** Meldung des offiziellen Clients nach der Anmeldung */
|
||
clientEnv(p, m = {}) {
|
||
if (this.#exempt(p)) return {};
|
||
const l = this.#live(p.id);
|
||
l.clientSeen = true;
|
||
if (m.wd === true) this.signal(p, 'webdriver', 'navigator.webdriver', HOUR);
|
||
return this.status(p);
|
||
}
|
||
|
||
/**
|
||
* Spielaktion über WebSocket oder REST (vor der Ausführung). Wirft, wenn die Maßnahme den Befehl blockiert.
|
||
* agent = Aufruf über die MCP-Schnittstelle mit persönlichem Schlüssel: Das ist erklärte, erlaubte Automatisierung –
|
||
* sie bekommt keine Bot-Punkte und keine Menschen-Bestätigung (dafür gibt es dort keinen Weg). Stattdessen gelten
|
||
* das Rate-Limit je Schlüssel und das Kennzeichen „Agent“ in der Rangliste. Gezählt wird getrennt (agentView).
|
||
* Nur „Handel pausieren“ bleibt wirksam: Das ist eine Maßnahme gegen das Konto, keine Prüfung des Eingabewegs.
|
||
*/
|
||
action(p, type, m = {}, { rest = false, agent = false } = {}) {
|
||
if (this.#exempt(p) || !WATCHED.has(type)) return;
|
||
const now = this.now(), l = this.#live(p.id), c = this.cfg();
|
||
if (agent) {
|
||
l.agent = { n: (l.agent?.n ?? 0) + 1, last: now };
|
||
if (c.botAction === 'pausieren' && this.#decay(p).level === 'verdacht') throw new Error('Dein Konto ist wegen automatisierter Steuerung vorübergehend für Aktionen pausiert. Die Spielleitung prüft das.');
|
||
return;
|
||
}
|
||
if (rest) this.signal(p, 'rest', type, 30 * 60_000);
|
||
// Maßnahmen bei Verdacht
|
||
const b = this.#decay(p);
|
||
if (b.level === 'verdacht') {
|
||
if (c.botAction === 'pausieren') throw new Error('Dein Konto ist wegen automatisierter Steuerung vorübergehend für Aktionen pausiert. Die Spielleitung prüft das – melde dich gern über den Käfer-Knopf.');
|
||
if (c.botAction === 'pruefen') {
|
||
const ch = this.#challenge(p);
|
||
const err = new Error('Bitte bestätige kurz, dass du selbst spielst.');
|
||
err.humanCheck = ch.nonce;
|
||
throw err;
|
||
}
|
||
if (c.botAction === 'bremsen') {
|
||
l.lastSlow = l.lastSlow.filter((t) => now - t < 60_000);
|
||
if (l.lastSlow.length >= c.botSlowPerMin) throw new Error(`Gebremst: höchstens ${c.botSlowPerMin} Aktionen pro Minute (Verdacht auf automatisierte Steuerung).`);
|
||
l.lastSlow.push(now);
|
||
}
|
||
}
|
||
// Zeitreihe
|
||
if (!l.firstWatched) l.firstWatched = now;
|
||
l.times.push(now);
|
||
if (l.times.length > 60) l.times.shift();
|
||
// Eingaben des Menschen: der offizielle Client schickt „hi“ = Anzahl echter Eingaben seit dem letzten Befehl
|
||
const hi = Number.isFinite(m.hi) ? m.hi : -1;
|
||
l.inputs.push(hi > 0);
|
||
if (l.inputs.length > 30) l.inputs.shift();
|
||
if (l.inputs.length >= 15) {
|
||
const none = l.inputs.filter((x) => !x).length / l.inputs.length;
|
||
if (none >= 0.8) this.signal(p, 'noInput', `${Math.round(none * 100)} % der letzten ${l.inputs.length} Befehle`, 30 * 60_000);
|
||
}
|
||
// Tempo
|
||
const in1s = l.times.filter((t) => now - t <= 1000).length;
|
||
if (in1s >= c.botBurst) this.signal(p, 'burst', `${in1s} Befehle in 1 s`, 5 * 60_000);
|
||
const in60 = l.times.filter((t) => now - t <= 60_000).length;
|
||
if (in60 >= c.botPerMin) this.signal(p, 'rate', `${in60} Befehle in 1 min`, 10 * 60_000);
|
||
// Gleichmäßigkeit: Variationskoeffizient der Abstände
|
||
if (l.times.length >= 25) {
|
||
const t = l.times.slice(-25), d = [];
|
||
for (let i = 1; i < t.length; i++) d.push(t[i] - t[i - 1]);
|
||
const mean = d.reduce((a, x) => a + x, 0) / d.length;
|
||
const sd = Math.sqrt(d.reduce((a, x) => a + (x - mean) ** 2, 0) / d.length);
|
||
if (mean > 50 && mean < 10 * 60_000 && sd / mean < 0.08) this.signal(p, 'regular', `Abstand ${(mean / 1000).toFixed(1)} s ± ${Math.round((sd / mean) * 100)} %`, 30 * 60_000);
|
||
}
|
||
// Dauerbetrieb: aktive Stunden der letzten 24 h
|
||
const hk = Math.floor(now / HOUR);
|
||
l.hours.set(hk, true);
|
||
for (const k of l.hours.keys()) if (k <= hk - 24) l.hours.delete(k);
|
||
if (l.hours.size >= 21) this.signal(p, 'nonstop', `${l.hours.size} von 24 Stunden aktiv`, 6 * HOUR);
|
||
// Client meldet sich nie, obwohl schon eine Weile gehandelt wird
|
||
if (!l.clientSeen && !rest && l.times.length >= 10 && now - l.firstWatched > 60_000) this.signal(p, 'noClient', '', HOUR);
|
||
}
|
||
|
||
/** Antwort auf die Menschen-Bestätigung */
|
||
humanCheck(p, { nonce, ms, trusted } = {}) {
|
||
if (!p) throw new Error('Bitte anmelden');
|
||
const l = this.#live(p.id), b = this.#state(p);
|
||
if (!l.challenge || l.challenge.nonce !== nonce) return this.status(p);
|
||
l.challenge = null;
|
||
b.checks = (b.checks ?? 0) + 1;
|
||
if (trusted === true && Number(ms) >= 400 && Number(ms) <= 10 * 60_000) {
|
||
// bestanden: Punkte deutlich unter die Schwelle senken (bleiben aber sichtbar)
|
||
const thr = this.cfg().botThreshold;
|
||
const f = Math.min(0.4, (0.6 * thr) / Math.max(1, b.score));
|
||
for (const s of Object.values(b.signals)) s.pts *= f;
|
||
l.inputs = []; l.times = [];
|
||
this.#decay(p);
|
||
b.level = b.score >= thr / 2 ? 'auffaellig' : 'ok';
|
||
this.dirty(p);
|
||
return { ...this.status(p), passed: true };
|
||
}
|
||
this.signal(p, 'failedCheck', `${Number(ms) || 0} ms`, 0);
|
||
return { ...this.status(p), passed: false };
|
||
}
|
||
|
||
/** Für den Spieler: steht eine Bestätigung aus? */
|
||
status(p) {
|
||
if (this.#exempt(p)) return { check: null };
|
||
const b = this.#decay(p);
|
||
const ch = b.level === 'verdacht' && this.cfg().botAction === 'pruefen' ? this.#challenge(p).nonce : null;
|
||
return { check: ch };
|
||
}
|
||
|
||
// ------------------------------------------------------------------ Admin
|
||
view(p) {
|
||
if (!p?.bot) return null;
|
||
const b = this.#decay(p);
|
||
return {
|
||
score: b.score, level: b.level, since: b.since, ok: !!p.botOk, checks: b.checks ?? 0,
|
||
signals: Object.entries(b.signals).map(([k, s]) => ({ key: k, label: BOT_SIGNALS[k]?.label ?? k, pts: Math.round(s.pts), n: s.n, last: s.last, detail: s.detail })).sort((a, z) => z.pts - a.pts),
|
||
};
|
||
}
|
||
|
||
admin(p, action) {
|
||
if (!p) throw new Error('Spieler nicht gefunden');
|
||
if (action === 'botOk') { p.botOk = true; p.bot = { score: 0, signals: {}, level: 'ok', since: 0, notifiedAt: 0, checks: 0 }; }
|
||
else if (action === 'botWatch') p.botOk = false;
|
||
else if (action === 'botReset') p.bot = { score: 0, signals: {}, level: 'ok', since: 0, notifiedAt: 0, checks: 0 };
|
||
else throw new Error('Unbekannte Aktion');
|
||
this.live.delete(p.id);
|
||
this.dirty(p);
|
||
}
|
||
|
||
/** Aktionen über MCP (getrennt von den Signalen gezählt, seit Serverstart) */
|
||
agentView(pid) { const a = this.live.get(pid)?.agent; return a ? { n: a.n, last: a.last } : null; }
|
||
|
||
forget(pid) { this.live.delete(pid); }
|
||
cleanup() {
|
||
const now = this.now();
|
||
for (const [k, l] of this.live) {
|
||
if (l.agent && now - l.agent.last < 2 * 24 * HOUR) continue;
|
||
if (!l.times.length || now - l.times.at(-1) > 2 * 24 * HOUR) { if (!l.challenge) this.live.delete(k); }
|
||
}
|
||
}
|
||
}
|