1단계 뼈대: joke-app에서 로그인(디스코드·게스트)·세션·권한·관리자·DB를 가져와 음악퀴즈용으로 정리, 새 디자인·아이콘, WS 연결·시계 맞추기, 테스트·e2e

- apps/server: Hono API(auth/me/config/admin), Bun WebSocket(welcome·ping/pong, 압축 끔), SQLite 마이그레이션
- 사이트 설정: 채팅 도배 방지 기본 꺼짐(관리자가 켬, 초당·순간 횟수)
- apps/web: 첫 화면·로그인·관리자(대시보드·사이트·사용자·관리자·기록), 라이트/다크, 휴대폰, noindex
- packages/shared: 닉네임 규칙, 프로토콜(zod), 시계 차이 계산
- 테스트 20개 + 브라우저 e2e 6단계 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 19:44:47 +09:00
parent 7ae34c49c1
commit 391bbe69e5
61 changed files with 3569 additions and 3 deletions

View File

@@ -0,0 +1,86 @@
/**
* WebSocket gateway (docs/01 실시간 메시지). Stage 1: authenticated connection, welcome, clock-sync ping.
* Messages are handled synchronously on arrival: no queue and no batching (docs/12 채팅 "무조건 실시간").
*/
import type { Server, ServerWebSocket } from 'bun';
import { ClientMessage, MAX_CLIENT_MESSAGE_BYTES, PROTOCOL, type ServerMessage } from '@mq/shared';
import type { LogFn } from '../server';
export interface WsData {
userId: string;
connId: number;
}
export interface GatewayDeps {
log: LogFn;
onClose?: (userId: string) => void;
}
export class Gateway {
private conns = new Map<string, Set<ServerWebSocket<WsData>>>();
private nextId = 1;
constructor(private d: GatewayDeps) {}
get connectionCount(): number {
let n = 0;
for (const s of this.conns.values()) n += s.size;
return n;
}
isOnline(userId: string): boolean {
return (this.conns.get(userId)?.size ?? 0) > 0;
}
upgrade(req: Request, srv: Server<WsData>, userId: string): Response | undefined {
if (srv.upgrade(req, { data: { userId, connId: this.nextId++ } })) return undefined;
return new Response('upgrade failed', { status: 400 });
}
/** Banned / force-logged-out users: drop every socket. */
disconnectUser(userId: string): void {
for (const ws of this.conns.get(userId) ?? []) ws.close(4001, 'logged out');
}
shutdown(): void {
for (const set of this.conns.values()) for (const ws of set) ws.close(1001, 'server restart');
}
private send(ws: ServerWebSocket<WsData>, m: ServerMessage): void {
ws.send(JSON.stringify(m));
}
readonly handlers = {
open: (ws: ServerWebSocket<WsData>) => {
const set = this.conns.get(ws.data.userId) ?? new Set();
set.add(ws);
this.conns.set(ws.data.userId, set);
this.send(ws, { t: 'welcome', protocol: PROTOCOL, userId: ws.data.userId, serverNow: Date.now() });
},
message: (ws: ServerWebSocket<WsData>, raw: string | Buffer) => {
const text = typeof raw === 'string' ? raw : raw.toString();
if (text.length > MAX_CLIENT_MESSAGE_BYTES) return this.send(ws, { t: 'error', message: '메시지가 너무 길어요.' });
let json: unknown;
try {
json = JSON.parse(text);
} catch {
return this.send(ws, { t: 'error', message: '잘못된 메시지예요.' });
}
const parsed = ClientMessage.safeParse(json);
if (!parsed.success) return this.send(ws, { t: 'error', message: '잘못된 메시지예요.' });
const m = parsed.data;
switch (m.t) {
case 'ping':
return this.send(ws, { t: 'pong', c: m.c, s: Date.now() });
}
},
close: (ws: ServerWebSocket<WsData>) => {
const set = this.conns.get(ws.data.userId);
set?.delete(ws);
if (set && set.size === 0) {
this.conns.delete(ws.data.userId);
this.d.onClose?.(ws.data.userId);
}
},
};
}

View File

@@ -0,0 +1,45 @@
/** Token bucket: chat flood guard when the admin turns it on (docs/12 채팅). */
export class TokenBucket {
private tokens: number;
private last: number;
constructor(
private ratePerSec: number,
private burst: number,
now = Date.now(),
) {
this.tokens = burst;
this.last = now;
}
take(now = Date.now()): boolean {
this.tokens = Math.min(this.burst, this.tokens + ((now - this.last) / 1000) * this.ratePerSec);
this.last = now;
if (this.tokens < 1) return false;
this.tokens -= 1;
return true;
}
}
/** Fixed-window counter per key (HTTP endpoints). */
export class WindowLimiter {
private hits = new Map<string, { start: number; n: number }>();
constructor(
private limit: number,
private windowMs: number,
) {}
allow(key: string, now = Date.now()): boolean {
const h = this.hits.get(key);
if (!h || now - h.start >= this.windowMs) {
this.hits.set(key, { start: now, n: 1 });
if (this.hits.size > 50_000) this.prune(now);
return true;
}
h.n++;
return h.n <= this.limit;
}
private prune(now: number): void {
for (const [k, v] of this.hits) if (now - v.start >= this.windowMs) this.hits.delete(k);
}
}