Files
tidefront/packages/engine/src/auth.ts
T
db9979 e6423e344a KI-Spieler: Händler, Festung, Freibeuter spielen über die normalen Befehle mit
- Neues Engine-Modul bots-*.ts: Bauordnung, Doktrin, Forschung, Börse, Spielerhandel, Felder,
  Gründung, Nester-/Spielerangriffe mit Aufklärung und Probekampf, Minen; Aktivitätszeiten mit Nachtschild
- Angriffe auf Menschen je Bot schaltbar (Vorgabe aus), Schutzregeln der Befehle plus 12 h Sperrfrist je Mensch
- Worker-Takt: höchstens 2 Züge je Minute reihum, Zeitbudget, abschaltbar (bots_enabled, BOTS_DISABLED)
- Verwaltung: Bots anlegen (Startbesetzung, Bot hinzufügen mit Spielweise, Obergrenze bots_max), aktiv/
  Angriffserlaubnis, letzte Aktionen, Entfernen über Rückruf/Aufgeben
- Bots ohne Anmeldung, Rücksetzcode, Push und E-Mail; KI-Kennzeichen in Rangliste und Spielerübersicht
- Schema: player.bot_profile, bot_settings, bot_state (Migration erzeugt der Integrator)
- Balance-Block bots, Handbuch-Kapitel und docs/REGELN-KI.md, ENTSCHEIDUNGEN Abschnitt L
- Tests: Anlegen, Zug je Spielweise, Angriffssperre, Sperrfrist, Schutzregeln, Takt, Saisonwechsel,
  Testlauf über mehrere Spieltage
2026-11-27 09:29:19 +01:00

113 lines
5.2 KiB
TypeScript

// Konten: Anmeldung nur mit Einladungscode, Passwort mit scrypt, Sitzung als Zufallstoken.
import { randomBytes, scrypt as scryptCb, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";
import { and, eq, gt, isNull, lt, sql } from "drizzle-orm";
import { market as marketCore } from "@tidefront/game-core";
import { tables, type Db } from "@tidefront/db";
import { marketBalance, GameError, SESSION_DAYS } from "./context.ts";
import { grantAdminOnRegister } from "./account.ts";
import { claimPersonalInvite, markInviteAccepted } from "./invite.ts";
const scrypt = promisify(scryptCb) as (pw: string, salt: Buffer, len: number) => Promise<Buffer>;
export async function hashPassword(pw: string): Promise<string> {
const salt = randomBytes(16);
const key = await scrypt(pw, salt, 32);
return `scrypt$${salt.toString("hex")}$${key.toString("hex")}`;
}
export async function verifyPassword(pw: string, stored: string): Promise<boolean> {
const [kind, saltHex, keyHex] = stored.split("$");
if (kind !== "scrypt" || !saltHex || !keyHex) return false;
const key = await scrypt(pw, Buffer.from(saltHex, "hex"), 32);
const expected = Buffer.from(keyHex, "hex");
return key.length === expected.length && timingSafeEqual(key, expected);
}
export async function createSession(db: Db, playerId: number): Promise<string> {
const token = randomBytes(32).toString("hex");
await db.insert(tables.session).values({
token,
playerId,
expiresAt: new Date(Date.now() + SESSION_DAYS * 86400000),
});
return token;
}
/** Einladungscodes vergleicht der Server ohne Rücksicht auf Groß-/Kleinschreibung (neue Codes in Großbuchstaben). */
export function normalizeInviteCode(code: string): string {
return code.trim().toUpperCase();
}
/** Registrierung: Einladungscode wird im selben Commit verbraucht. Codes: invite_invalid, name_taken.
* Den Einladenden einer persönlichen Einladung benachrichtigt danach notifyInviter (invite.ts). */
export async function register(db: Db, input: { inviteCode: string; name: string; password: string }) {
const nowMs = Date.now();
const playerId = await db.transaction(async (tx) => {
// Groß-/Kleinschreibung egal: gespeicherter Code mit gleicher Schreibweise ohne Rücksicht auf Groß/klein.
const [match] = await tx
.select({ code: tables.inviteCode.code })
.from(tables.inviteCode)
.where(and(
sql`upper(${tables.inviteCode.code}) = ${normalizeInviteCode(input.inviteCode)}`,
lt(tables.inviteCode.uses, tables.inviteCode.maxUses),
isNull(tables.inviteCode.disabledAt),
))
.orderBy(tables.inviteCode.code)
.limit(1);
if (!match) throw new GameError("invite_invalid");
const used = await tx
.update(tables.inviteCode)
.set({ uses: sql`${tables.inviteCode.uses} + 1` })
.where(and(
eq(tables.inviteCode.code, match.code),
lt(tables.inviteCode.uses, tables.inviteCode.maxUses),
isNull(tables.inviteCode.disabledAt),
))
.returning({ code: tables.inviteCode.code });
if (used.length === 0) throw new GameError("invite_invalid");
// Persönliche Einladung (Freunde einladen): muss noch gelten; wird nach dem Anlegen als angenommen markiert.
const personalInvite = await claimPersonalInvite(tx, used[0].code, nowMs);
const [taken] = await tx
.select({ id: tables.player.id })
.from(tables.player)
.where(sql`lower(${tables.player.name}) = lower(${input.name})`);
if (taken) throw new GameError("name_taken");
const trader = marketCore.createTraderState(marketBalance, 0, {}, nowMs);
const { stock: _stock, ...rest } = trader;
const [p] = await tx
.insert(tables.player)
.values({ name: input.name, passHash: await hashPassword(input.password), trader: rest })
.returning({ id: tables.player.id });
await grantAdminOnRegister(tx, p.id, input.name);
if (personalInvite !== null) await markInviteAccepted(tx, personalInvite, p.id, nowMs);
return p.id;
});
return { playerId, token: await createSession(db, playerId) };
}
/** Code: bad_login. */
export async function login(db: Db, input: { name: string; password: string }) {
const [p] = await db
.select()
.from(tables.player)
.where(sql`lower(${tables.player.name}) = lower(${input.name})`);
// KI-Spieler: kein nutzbares Passwort, Anmeldung immer abgelehnt.
if (!p || p.botProfile !== null || !(await verifyPassword(input.password, p.passHash))) throw new GameError("bad_login");
return { playerId: p.id, token: await createSession(db, p.id) };
}
export async function logout(db: Db, token: string): Promise<void> {
await db.delete(tables.session).where(eq(tables.session.token, token));
}
export async function playerForToken(db: Db, token: string | undefined): Promise<{ id: number; name: string; isAdmin: boolean } | null> {
if (!token || !/^[0-9a-f]{64}$/.test(token)) return null;
const [r] = await db
.select({ id: tables.player.id, name: tables.player.name, isAdmin: tables.player.isAdmin })
.from(tables.session)
.innerJoin(tables.player, eq(tables.player.id, tables.session.playerId))
.where(and(eq(tables.session.token, token), gt(tables.session.expiresAt, new Date())));
return r ?? null;
}