From 0bff06fa3ec7b53cbbf2ef5a8789d23a6fc823f0 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Wed, 14 Oct 2026 09:04:07 +0900 Subject: [PATCH] =?UTF-8?q?=EC=9B=B9=EC=86=8C=EC=BC=93=20=EB=8F=84?= =?UTF-8?q?=EB=B0=B0=20=EB=B0=A9=EC=A7=80=EB=A5=BC=20JSON=20=ED=95=B4?= =?UTF-8?q?=EC=84=9D=20=EC=A0=84=EC=9C=BC=EB=A1=9C:=20=EC=B1=84=ED=8C=85?= =?UTF-8?q?=C2=B7=EA=B2=8C=EC=9E=84=20=ED=95=9C=EB=8F=84=EB=A5=BC=20?= =?UTF-8?q?=ED=95=A9=EC=B9=9C=20=EC=9B=90=EC=8B=9C=20=ED=95=9C=EB=8F=84(?= =?UTF-8?q?=EC=B4=88=EB=8B=B9=2070,=20=EC=B5=9C=EB=8C=80=20240)=EB=A5=BC?= =?UTF-8?q?=20=ED=8C=8C=EC=8B=B1=20=EC=A0=84=EC=97=90=20=EB=A8=BC=EC=A0=80?= =?UTF-8?q?=20=EC=A0=81=EC=9A=A9=ED=95=B4=20=EB=8F=84=EB=B0=B0=EA=B0=80=20?= =?UTF-8?q?=EB=A9=94=EC=8B=9C=EC=A7=80=EB=A7=88=EB=8B=A4=20=ED=8C=8C?= =?UTF-8?q?=EC=8B=B1=20=EB=B9=84=EC=9A=A9=EC=9D=84=20=EC=93=B0=EC=A7=80=20?= =?UTF-8?q?=EC=95=8A=EA=B2=8C(gateway.test.ts).=20=EB=AC=B8=EC=84=9C?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EC=A7=80=EC=9A=B4=20lastChatAt=20?= =?UTF-8?q?=EC=84=A4=EB=AA=85=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/server/src/ws/gateway.test.ts | 36 ++++++++++++++++++++++++++++++ apps/server/src/ws/gateway.ts | 25 ++++++++++++++++----- docs/03-realtime-protocol.md | 2 +- docs/games/liar.md | 2 +- docs/games/mafia.md | 1 - 5 files changed, 58 insertions(+), 8 deletions(-) create mode 100644 apps/server/src/ws/gateway.test.ts diff --git a/apps/server/src/ws/gateway.test.ts b/apps/server/src/ws/gateway.test.ts new file mode 100644 index 0000000..571c364 --- /dev/null +++ b/apps/server/src/ws/gateway.test.ts @@ -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; + 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; + return { ws, sent, closed: () => closed }; +} + +describe('gateway flood guard (2026-10-14)', () => { + let spy: ReturnType | 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(); + }); +}); diff --git a/apps/server/src/ws/gateway.ts b/apps/server/src/ws/gateway.ts index 1f976a8..6eb7e86 100644 --- a/apps/server/src/ws/gateway.ts +++ b/apps/server/src/ws/gateway.ts @@ -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, 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; diff --git a/docs/03-realtime-protocol.md b/docs/03-realtime-protocol.md index b279142..e51ba3d 100644 --- a/docs/03-realtime-protocol.md +++ b/docs/03-realtime-protocol.md @@ -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 넘게 밀리면(느린 클라이언트) 연결을 끊음 → 재연결 시 전체 상태로 회복 | diff --git a/docs/games/liar.md b/docs/games/liar.md index df3a3c4..33c2d7b 100644 --- a/docs/games/liar.md +++ b/docs/games/liar.md @@ -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; } ``` diff --git a/docs/games/mafia.md b/docs/games/mafia.md index 940ccf4..b8f6cf9 100644 --- a/docs/games/mafia.md +++ b/docs/games/mafia.md @@ -165,7 +165,6 @@ interface MafiaState { lastHealTarget: PlayerId | null; privateResults: { to: PlayerId; day: number; text: string }[]; // 경찰/영매 결과 chat: ChatMessage[]; // 서버 상태에 전부 저장, view에서 필터 - lastChatAt: Record; // 레이트 리밋 history: PublicEvent[]; // 공개 발표 기록 winner: null | 'town' | 'mafia'; }