- 제시어 1,519개를 주제별 '비슷한 단어 묶음' 391개로 정리(bank/*.ts groups). 바보 모드 라이어는 제시어와 같은 묶음의 다른 단어를 받음 - 관리자 → 라이어 제시어(/admin/liar): 주제 추가·이름 변경·삭제(내장 주제는 다시 살리기/처음 값으로), 제시어·묶음·다른 표기·컴퓨터 설명 편집, 저장 시 topicProblems 검사 - 저장: liar_topics(바뀐 주제), liar_bank_versions(판본). 새 판 옵션에 bank 판본을 붙여(prepareOptions) 다시 보기·복구가 같은 은행 사용 - 판 상태에 주제 이름·단어 목록·다른 표기를 복사해 진행 중 판은 관리자 수정의 영향을 받지 않음 - 대기실 주제 목록은 GET /api/liar/topics, 관리자 API /api/admin/liar/topics, 기록 liar.topic.* - 테스트: 엔진(묶음·바보 모드·판본·검사), 서버(관리자 API·새 판·재시작), E2E(관리자 편집 → 대기실 새 주제) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
234 lines
9.0 KiB
TypeScript
234 lines
9.0 KiB
TypeScript
/** Wires DB, auth, rooms, HTTP and WebSocket into one Bun server (docs/02 §2). */
|
|
import { existsSync, readFileSync } from 'node:fs';
|
|
import { join, normalize } from 'node:path';
|
|
import type { Server } from 'bun';
|
|
import { GAMES } from '@bg/games';
|
|
import { botProfile } from '@bg/shared';
|
|
import { Llm } from './ai/llm';
|
|
import type { Config } from './config';
|
|
import { openDb } from './db';
|
|
import { SESSION_COOKIE, Sessions } from './auth/sessions';
|
|
import { Users, toPublicUser } from './auth/users';
|
|
import { createHttpApp, type HttpDeps } from './http/app';
|
|
import { RoomManager } from './rooms/manager';
|
|
import { createLuckSeeder } from './rooms/luck';
|
|
import type { BotDelayInput } from './rooms/bots';
|
|
import { RoomStore } from './rooms/store';
|
|
import { Replays } from './rooms/replay';
|
|
import { Gateway, type WsData } from './ws/gateway';
|
|
import { Audit, Roles } from './admin/roles';
|
|
import { SettingsStore } from './admin/settings';
|
|
import { LiarBankStore } from './admin/liar-bank';
|
|
|
|
/** A guest who closed the site and stayed away this long is deleted. */
|
|
export const GUEST_IDLE_MS = 24 * 3600_000;
|
|
|
|
export type LogFn = (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
|
|
|
|
export const jsonLog: LogFn = (level, msg, extra) => {
|
|
const line = JSON.stringify({ t: new Date().toISOString(), level, msg, ...extra });
|
|
if (level === 'error') console.error(line);
|
|
else console.log(line);
|
|
};
|
|
|
|
export interface StartOptions {
|
|
config: Config;
|
|
log?: LogFn;
|
|
staticDir?: string | null;
|
|
discordExchange?: HttpDeps['discordExchange'];
|
|
/** Computer players' thinking time (tests shorten it). */
|
|
botDelay?: (input: BotDelayInput) => number;
|
|
/** Upper bound for waiting on Bun's server.stop() (tests shorten it). */
|
|
stopWaitMs?: number;
|
|
/** Computers' luck on a worker thread (docs/04 §5.1); default on. */
|
|
luck?: boolean;
|
|
}
|
|
|
|
export function startServer(opts: StartOptions) {
|
|
const { config } = opts;
|
|
const log = opts.log ?? jsonLog;
|
|
const db = openDb(config.dbPath);
|
|
const users = new Users(db);
|
|
const sessions = new Sessions(db);
|
|
const store = new RoomStore(db);
|
|
const publicUser = (id: string) => {
|
|
const bot = botProfile(id);
|
|
if (bot) return bot;
|
|
const u = users.get(id);
|
|
return u ? toPublicUser(u) : null;
|
|
};
|
|
const settings = new SettingsStore(db, GAMES);
|
|
// 라이어 게임 words the admins changed: loaded before rooms are restored (their games may use an edited bank).
|
|
const liarBank = new LiarBankStore(db);
|
|
const roles = new Roles(db, config.superadminDiscordIds);
|
|
const audit = new Audit(db);
|
|
const startedAt = Date.now();
|
|
// Computers talk and play like people with a local model on the GPU when AI_URL is set (docs/06 §12.1, docs/11 §8).
|
|
const ai = config.ai ? new Llm({ url: config.ai.url, model: config.ai.model, log }) : null;
|
|
if (ai) void ai.warm().then((ok) => log('info', 'ai model', { model: config.ai!.model, ready: ok }));
|
|
const luck = opts.luck === false ? null : createLuckSeeder({ log });
|
|
const rooms = new RoomManager({
|
|
store,
|
|
games: GAMES,
|
|
users: { publicUser },
|
|
log,
|
|
settings,
|
|
botDelay: opts.botDelay,
|
|
ai,
|
|
luckSeed: luck ? (job) => luck.seed(job) : undefined,
|
|
offlineSince: (id): number | null => gateway.offlineSince(id),
|
|
});
|
|
const restored = rooms.restoreAll();
|
|
log('info', 'rooms restored', restored);
|
|
const gateway = new Gateway({
|
|
rooms,
|
|
me: publicUser,
|
|
log,
|
|
onClose: (id) => users.touch(id),
|
|
build: () => build,
|
|
chatFloodGuard: () => settings.getSite().chatFloodGuard,
|
|
});
|
|
const removeGuest = (id: string) => {
|
|
rooms.leaveAll(id);
|
|
gateway.closeUser(id);
|
|
if (users.deleteGuest(id)) log('info', 'guest removed', { user: id });
|
|
};
|
|
/** Still on the site (socket open) or still holding a seat: not idle. */
|
|
const guestKept = (id: string) => gateway.isOnline(id) || !!rooms.activeRoomFor(id);
|
|
/** Guests who closed the site and stayed away a day are deleted (docs/05 §4). */
|
|
const purgeIdleGuests = (now = Date.now()) => {
|
|
for (const id of users.idleGuests(now - GUEST_IDLE_MS)) {
|
|
if (guestKept(id)) continue;
|
|
removeGuest(id);
|
|
}
|
|
};
|
|
let ready = true;
|
|
|
|
const ipOf = (req: Request) =>
|
|
(config.trustProxy ? req.headers.get('x-forwarded-for')?.split(',').pop()?.trim() : undefined) ||
|
|
server?.requestIP(req)?.address ||
|
|
'unknown';
|
|
|
|
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
|
|
const serveStatic = staticDir && existsSync(staticDir);
|
|
// The web build being served (docs/07 §11.1): pages that were opened with an older one offer to refresh.
|
|
const build = serveStatic ? webBuildId(staticDir!) : null;
|
|
const app = createHttpApp({
|
|
config,
|
|
build,
|
|
users,
|
|
sessions,
|
|
rooms,
|
|
replays: new Replays(db, GAMES, { publicUser }),
|
|
ipOf,
|
|
discordExchange: opts.discordExchange,
|
|
health: () => ({
|
|
ok: ready,
|
|
rooms: rooms.all().length,
|
|
connections: gateway.connectionCount,
|
|
...(ai ? { ai: { model: ai.stats.model, available: ai.available(), ok: ai.stats.ok, failed: ai.stats.failed, avgMs: ai.stats.avgMs } } : {}),
|
|
}),
|
|
roles,
|
|
settings,
|
|
removeGuest,
|
|
admin: {
|
|
audit,
|
|
games: GAMES,
|
|
liarBank,
|
|
disconnectUser: (id) => gateway.disconnectUser(id),
|
|
guestDeleteAt: (u) => (u.kind !== 'guest' || guestKept(u.id) ? null : u.last_seen_at + GUEST_IDLE_MS),
|
|
stats: () => {
|
|
const all = rooms.all();
|
|
const day = Date.now() - 24 * 3600_000;
|
|
return {
|
|
connections: gateway.connectionCount,
|
|
rooms: { total: all.length, lobby: all.filter((r) => r.status === 'lobby').length, playing: all.filter((r) => r.status === 'playing').length },
|
|
games: db.query<{ total: number; today: number }, [number]>('SELECT COUNT(*) AS total, SUM(started_at > ?) AS today FROM games').get(day),
|
|
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
|
|
memoryMb: Math.round(process.memoryUsage().rss / 1048576),
|
|
};
|
|
},
|
|
},
|
|
});
|
|
|
|
|
|
const server: Server<WsData> = Bun.serve<WsData>({
|
|
port: config.port,
|
|
async fetch(req, srv) {
|
|
const url = new URL(req.url);
|
|
if (url.pathname === '/ws') {
|
|
const origin = req.headers.get('origin');
|
|
if (!origin || !config.allowedOrigins.includes(origin)) return new Response('forbidden origin', { status: 403 });
|
|
const cookie = req.headers.get('cookie') ?? '';
|
|
const token = cookie
|
|
.split(';')
|
|
.map((s) => s.trim())
|
|
.find((s) => s.startsWith(`${SESSION_COOKIE}=`))
|
|
?.slice(SESSION_COOKIE.length + 1);
|
|
const userId = token ? sessions.resolve(decodeURIComponent(token)) : null;
|
|
if (!userId) return new Response('unauthorized', { status: 401 });
|
|
return gateway.upgrade(req, srv, userId);
|
|
}
|
|
if (url.pathname.startsWith('/api/') || url.pathname === '/healthz') return app.fetch(req);
|
|
if (url.pathname.startsWith('/internal/')) return new Response('not found', { status: 404 });
|
|
if (serveStatic) return serveFile(staticDir!, url.pathname);
|
|
return new Response('not found', { status: 404 });
|
|
},
|
|
websocket: {
|
|
...gateway.handlers,
|
|
idleTimeout: 40,
|
|
sendPings: true,
|
|
perMessageDeflate: true,
|
|
maxPayloadLength: 64 * 1024,
|
|
},
|
|
});
|
|
|
|
const sweeper = setInterval(() => {
|
|
try {
|
|
rooms.sweep();
|
|
sessions.purgeExpired();
|
|
purgeIdleGuests();
|
|
store.purgeOldLogs();
|
|
} catch (err) {
|
|
log('error', 'sweep failed', { err: String(err) });
|
|
}
|
|
}, 60_000);
|
|
|
|
const stop = async () => {
|
|
ready = false;
|
|
clearInterval(sweeper);
|
|
gateway.shutdown();
|
|
rooms.shutdown();
|
|
luck?.stop();
|
|
// Bun's stop() promise can stay pending after server-initiated WS closes even though the
|
|
// listener is already closed, so bound the wait.
|
|
await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]);
|
|
db.close();
|
|
};
|
|
|
|
return { server, stop, rooms, users, sessions, db, gateway, settings, roles, purgeIdleGuests };
|
|
}
|
|
|
|
/** The build id the web build wrote into its index.html (`<meta name="bg-build">`, vite.config.ts), or null. */
|
|
export function webBuildId(root: string): string | null {
|
|
try {
|
|
return /<meta name="bg-build" content="([0-9a-f]+)"/.exec(readFileSync(join(root, 'index.html'), 'utf8'))?.[1] ?? null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function serveFile(root: string, pathname: string): Promise<Response> {
|
|
const safe = normalize(decodeURIComponent(pathname)).replace(/^(\.\.[/\\])+/, '');
|
|
const candidate = join(root, safe);
|
|
if (candidate.startsWith(root) && !candidate.endsWith('/')) {
|
|
const f = Bun.file(candidate);
|
|
if (await f.exists()) {
|
|
const immutable = safe.startsWith('/assets/');
|
|
return new Response(f, { headers: { 'Cache-Control': immutable ? 'public, max-age=31536000, immutable' : 'no-cache' } });
|
|
}
|
|
}
|
|
// SPA fallback.
|
|
return new Response(Bun.file(join(root, 'index.html')), { headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'text/html; charset=utf-8' } });
|
|
}
|