Files
wibosim/server/src/auth.js
T
db9979andClaude Opus 5.5 894926a5ad Gateway: Limit je Spieler, Schutz vor doppelten Anfragen und Prototyp-Schlüsseln
- 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
2026-12-03 20:15:36 +00:00

97 lines
3.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Anmeldung: Passwort-Hashing (scrypt, asynchron – blockiert den Spieltakt nicht),
// Sitzungen mit gehashten Tokens und Ablauf, Sperre nach Fehlversuchen.
import { scrypt, randomBytes, timingSafeEqual, createHash } from 'node:crypto';
const scryptAsync = (pw, salt) => new Promise((res, rej) => scrypt(pw, salt, 32, (e, k) => (e ? rej(e) : res(k))));
const SESSION_DAYS = 30;
const DAY = 86_400_000;
export async function hashPw(pw) {
const salt = randomBytes(16).toString('hex');
return `${salt}:${(await scryptAsync(String(pw), salt)).toString('hex')}`;
}
export async function checkPw(pw, stored) {
const [salt, h] = String(stored ?? '').split(':');
if (!salt || !h) return false;
const a = Buffer.from(h, 'hex');
const b = await scryptAsync(String(pw ?? ''), salt);
return a.length === b.length && timingSafeEqual(a, b);
}
export const tokenHash = (t) => createHash('sha256').update(String(t)).digest('hex');
export class Sessions {
constructor(rows = []) {
this.map = new Map(rows.map((r) => [r.hash, { player: r.player, created: r.created, expires: r.expires }]));
this.pendingSet = [];
this.pendingDel = [];
this.pendingDelPlayers = [];
this.failures = new Map(); // name -> { n, until }
}
create(playerId) {
const token = randomBytes(32).toString('hex');
const hash = tokenHash(token);
const s = { player: playerId, created: Date.now(), expires: Date.now() + SESSION_DAYS * DAY };
this.map.set(hash, s);
this.pendingSet.push({ hash, ...s });
return token;
}
/** @returns {string|null} Spieler-ID; verlängert die Sitzung gleitend */
resolve(token) {
if (!token || typeof token !== 'string' || token.length > 200) return null;
const hash = tokenHash(token);
const s = this.map.get(hash);
if (!s) return null;
if (s.expires < Date.now()) { this.map.delete(hash); this.pendingDel.push(hash); return null; }
if (s.expires - Date.now() < (SESSION_DAYS - 1) * DAY) {
s.expires = Date.now() + SESSION_DAYS * DAY;
this.pendingSet.push({ hash, ...s });
}
return s.player;
}
revoke(token) {
const hash = tokenHash(token);
if (this.map.delete(hash)) this.pendingDel.push(hash);
}
revokeAll(playerId) {
for (const [h, s] of this.map) if (s.player === playerId) this.map.delete(h);
this.pendingDelPlayers.push(playerId);
}
/** Übernahme alter Klartext-Tokens (Migration aus state.json) */
adopt(playerId, token) {
const hash = tokenHash(token);
const s = { player: playerId, created: Date.now(), expires: Date.now() + SESSION_DAYS * DAY };
this.map.set(hash, s);
this.pendingSet.push({ hash, ...s });
}
locked(name) {
const f = this.failures.get(String(name).toLowerCase());
return !!f && f.until > Date.now();
}
failed(name) {
const k = String(name).toLowerCase();
const f = this.failures.get(k) ?? { n: 0, until: 0 };
f.n++;
if (f.n >= 10) { f.until = Date.now() + 15 * 60_000; f.n = 0; }
this.failures.set(k, f);
}
succeeded(name) { this.failures.delete(String(name).toLowerCase()); }
drain() {
const out = { sessions: this.pendingSet, deletedSessions: this.pendingDel, deletedSessionsOf: this.pendingDelPlayers };
this.pendingSet = []; this.pendingDel = []; this.pendingDelPlayers = [];
// aufräumen, ohne laufende Sperren aufzuheben (sonst ließe sich eine Sperre durch viele Fehlversuche mit anderen Namen löschen)
if (this.failures.size > 1000) for (const [k, f] of this.failures) if (!(f.until > Date.now())) this.failures.delete(k);
return out;
}
}