웹소켓 도배 방지를 JSON 해석 전으로: 채팅·게임 한도를 합친 원시 한도(초당 70, 최대 240)를 파싱 전에 먼저 적용해 도배가 메시지마다 파싱 비용을 쓰지 않게(gateway.test.ts). 문서에서 지운 lastChatAt 설명 제거

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-14 09:04:07 +09:00
parent 4d1deb8346
commit 0bff06fa3e
5 changed files with 58 additions and 8 deletions

View File

@@ -0,0 +1,36 @@
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import type { Server, ServerWebSocket } from 'bun';
import type { RoomManager } from '../rooms/manager';
import { Gateway, type WsData } from './gateway';
function socket(gw: Gateway) {
let data: WsData | undefined;
const server = { upgrade: (_req: Request, o: { data: WsData }) => ((data = o.data), true) } as unknown as Server<WsData>;
gw.upgrade(new Request('http://x/ws'), server, 'u1');
const sent: string[] = [];
let closed: number | null = null;
const ws = {
data: data!,
send: (m: string) => void sent.push(m),
close: (code: number) => void (closed = code),
getBufferedAmount: () => 0,
} as unknown as ServerWebSocket<WsData>;
return { ws, sent, closed: () => closed };
}
describe('gateway flood guard (2026-10-14)', () => {
let spy: ReturnType<typeof spyOn> | null = null;
afterEach(() => spy?.mockRestore());
test('a flood is cut off before parsing: at most the raw budget of messages is ever parsed', () => {
const gw = new Gateway({ rooms: {} as RoomManager, me: () => null, now: () => 0 });
const { ws, closed } = socket(gw);
// Keep the socket open for the whole flood (strikes would close it): only the parse count is under test.
ws.data.strikes = -1e9;
spy = spyOn(JSON, 'parse');
for (let i = 0; i < 1000; i++) gw.handlers.message(ws, '{not json');
// Raw budget = game burst 40 + chat burst 200 (the loop takes a few ms, so barely anything refills).
expect(spy.mock.calls.length).toBeLessThanOrEqual(250);
expect(closed()).toBeNull();
});
});

View File

@@ -8,6 +8,8 @@ import { TokenBucket } from './rate-limit';
export interface WsData {
userId: string;
connId: number;
/** Every message, checked before parsing (room for both budgets below), so a flood never costs a JSON parse each. */
rawBucket: TokenBucket;
bucket: TokenBucket;
/** Chat lines and "입력 중" signals have their own budget, so typing fast never eats into (or waits on) game moves. */
chatBucket: TokenBucket;
@@ -35,6 +37,9 @@ export const MAX_CONNS_PER_USER = 5;
*/
const CHAT_RATE_PER_SEC = 50;
const CHAT_BURST = 200;
/** Game/other budget per socket. */
const RATE_PER_SEC = 20;
const BURST = 40;
/** Room chat, game chat (마피아·라이어 게임·그림 맞히기 `act` with `type: 'chat'`) and the "입력 중" signal. */
function isChatMessage(m: unknown): boolean {
@@ -64,7 +69,16 @@ export class Gateway {
upgrade(req: Request, server: Server<WsData>, userId: string): Response | undefined {
if (this.closing) return new Response('restarting', { status: 503 });
if ((this.byUser.get(userId)?.size ?? 0) >= MAX_CONNS_PER_USER) return new Response('too many connections', { status: 429 });
const data: WsData = { userId, connId: this.nextId++, bucket: new TokenBucket(20, 40), chatBucket: new TokenBucket(CHAT_RATE_PER_SEC, CHAT_BURST), strikes: 0, room: null, conn: null };
const data: WsData = {
userId,
connId: this.nextId++,
rawBucket: new TokenBucket(RATE_PER_SEC + CHAT_RATE_PER_SEC, BURST + CHAT_BURST),
bucket: new TokenBucket(RATE_PER_SEC, BURST),
chatBucket: new TokenBucket(CHAT_RATE_PER_SEC, CHAT_BURST),
strikes: 0,
room: null,
conn: null,
};
if (server.upgrade(req, { data })) return undefined;
return new Response('upgrade failed', { status: 400 });
}
@@ -113,6 +127,10 @@ export class Gateway {
ws.close(1009, 'message too big');
return;
}
const strike = () => {
if (++ws.data.strikes > 50) ws.close(4429, 'rate limited');
};
if (!ws.data.rawBucket.take()) return strike();
let json: unknown;
let badJson = false;
try {
@@ -121,10 +139,7 @@ export class Gateway {
badJson = true;
}
const bucket = !badJson && isChatMessage(json) ? ws.data.chatBucket : ws.data.bucket;
if (!bucket.take()) {
if (++ws.data.strikes > 50) ws.close(4429, 'rate limited');
return;
}
if (!bucket.take()) return strike();
if (badJson) {
this.send(ws, { t: 'error', code: 'bad-json', message: '잘못된 요청이에요.' });
return;

View File

@@ -91,7 +91,7 @@
| 서버 idle timeout | 40초 (Bun `idleTimeout`), 서버가 25초마다 ping 프레임 |
| 클라이언트 ping | 10초마다, 5초 안에 pong이 없으면 연결을 끊고 재연결 |
| 메시지 최대 크기 | 16KB (그림 맞히기 붓질 메시지만 32KB) |
| 속도 제한 | 연결당 토큰 버킷 초당 20개, 최대 40개. 채팅(방 채팅·게임 채팅 `act` type `chat`·`typing`)은 따로 초당 50개, 최대 200개(사람은 닿지 않는 매크로 방지용, 채팅 줄 자체의 속도 제한은 없음). 넘으면 버리고 계속 넘으면 연결 종료 |
| 속도 제한 | 연결당 토큰 버킷 초당 20개, 최대 40개. 채팅(방 채팅·게임 채팅 `act` type `chat`·`typing`)은 따로 초당 50개, 최대 200개(사람은 닿지 않는 매크로 방지용, 채팅 줄 자체의 속도 제한은 없음). 둘을 합친 원시 한도(초당 70, 최대 240)를 JSON 해석 전에 먼저 적용. 넘으면 버리고 계속 넘으면 연결 종료 |
| 압축 | permessage-deflate 사용(1KB 이상 메시지만 효과) |
| 서버 송신 버퍼 | 연결당 1MB 넘게 밀리면(느린 클라이언트) 연결을 끊음 → 재연결 시 전체 상태로 회복 |

View File

@@ -86,7 +86,7 @@
interface LiarState {
options; players: { id; left }[]; topic; word; liar; liarWord /* 바보 모드 */; order /* 1바퀴 순서 */;
phase: reveal{ready} | describe{round, turn} | discussion{ready} | vote{round 1|2, candidates, votes} | guess | ended;
descriptions: { n, round, from, text | null }[]; chat: { n, from, text, at }[]; lastChatAt;
descriptions: { n, round, from, text | null }[]; chat: { n, from, text, at }[];
events: PublicEvent[]; accused; guess; seq; final: LiarFinal | null;
}
```

View File

@@ -165,7 +165,6 @@ interface MafiaState {
lastHealTarget: PlayerId | null;
privateResults: { to: PlayerId; day: number; text: string }[]; // 경찰/영매 결과
chat: ChatMessage[]; // 서버 상태에 전부 저장, view에서 필터
lastChatAt: Record<PlayerId, number>; // 레이트 리밋
history: PublicEvent[]; // 공개 발표 기록
winner: null | 'town' | 'mafia';
}