관리자 사이트 설정에 "채팅 도배 방지" 켜기/끄기(기본 끄기): 끄면 채팅·입력 중 신호에 속도 제한이 전혀 없고, 켜면 접속마다 초당 50개(한 번에 200개)와 해석 전 원시 한도. 메시지마다 설정을 읽어 저장하면 열린 접속에도 바로 적용. 게임 조작 한도와 잘못된 메시지 차단은 그대로

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-14 09:08:54 +09:00
parent 0bff06fa3e
commit 77e9688876
9 changed files with 105 additions and 10 deletions

View File

@@ -17,6 +17,8 @@ export const SiteSettingsSchema = z.object({
graceSec: z.number().int().min(10).max(600).default(60),
chatEnabledDefault: z.boolean().default(true),
chatFilterDefault: z.boolean().default(true),
/** Chat flood guard (per-socket chat budget, docs/03 §8). Off: chat lines and 입력 중 signals are never limited. */
chatFloodGuard: z.boolean().default(false),
/** Animations and the computers' thinking time are divided by this (applies at once, also to running games). */
gameSpeed: z.number().min(GAME_SPEED_MIN).max(GAME_SPEED_MAX).default(GAME_SPEED_DEFAULT),
});

View File

@@ -234,6 +234,27 @@ describe('M1 integration scenarios', () => {
expect(a.messages.filter((m) => m.t === 'pong').length).toBe(30);
});
test('10c. admin 채팅 도배 방지 (default off) applies at once to open sockets', async () => {
const s = start();
expect(s.settings.getSite().chatFloodGuard).toBe(false);
const a = await client(s, '매크로');
const code = await createRoom(s, a);
await join(a, code);
const lines = () => a.messages.filter((m) => m.t === 'chat').length;
// On: 230 lines at once → only the chat budget (200) gets through.
s.settings.setSite({ ...s.settings.getSite(), chatFloodGuard: true }, 'test');
for (let i = 0; i < 230; i++) a.send({ t: 'chat', text: `켜짐 ${i}` });
await a.next('chat', (m) => m.text === '켜짐 199');
await sleep(200);
expect(lines()).toBe(200);
// Off again: no limit at all.
s.settings.setSite({ ...s.settings.getSite(), chatFloodGuard: false }, 'test');
for (let i = 0; i < 300; i++) a.send({ t: 'chat', text: `꺼짐 ${i}` });
await a.next('chat', (m) => m.text === '꺼짐 299');
expect(lines()).toBe(500);
expect(a.closed).toBeFalsy();
});
test('11. malformed / oversized / schema-invalid messages', async () => {
const s = start();
const a = await client(s, '이상한값');

View File

@@ -77,7 +77,14 @@ export function startServer(opts: StartOptions) {
});
const restored = rooms.restoreAll();
log('info', 'rooms restored', restored);
const gateway = new Gateway({ rooms, me: publicUser, log, onClose: (id) => users.touch(id), build: () => build });
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);

View File

@@ -22,8 +22,11 @@ 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 chatLine = JSON.stringify({ t: 'chat', text: '도배' });
const gateway = (guard: boolean) => new Gateway({ rooms: {} as RoomManager, me: () => null, now: () => 0, chatFloodGuard: () => guard });
test('도배 방지 켜짐: a flood is cut off before parsing: at most the raw budget of messages is ever parsed', () => {
const gw = gateway(true);
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;
@@ -33,4 +36,34 @@ describe('gateway flood guard (2026-10-14)', () => {
expect(spy.mock.calls.length).toBeLessThanOrEqual(250);
expect(closed()).toBeNull();
});
test('도배 방지 켜짐: chat past its budget (200 at once) is dropped and a flood closes the socket', () => {
const gw = gateway(true);
const { ws, closed } = socket(gw);
for (let i = 0; i < 1000 && closed() === null; i++) gw.handlers.message(ws, chatLine);
expect(closed()).toBe(4429);
});
test('도배 방지 꺼짐 (기본): chat is never limited; other messages keep their budget', () => {
const gw = gateway(false);
const { ws, closed } = socket(gw);
spy = spyOn(JSON, 'parse');
for (let i = 0; i < 1000; i++) {
gw.handlers.message(ws, chatLine);
gw.handlers.message(ws, JSON.stringify({ t: 'typing', on: i % 2 === 0, ch: 'room' }));
}
expect(spy.mock.calls.length).toBe(2000);
expect(ws.data.strikes).toBe(0);
expect(closed()).toBeNull();
// Junk is still cut off (general budget, then strikes).
for (let i = 0; i < 1000 && closed() === null; i++) gw.handlers.message(ws, '{not json');
expect(closed()).toBe(4429);
});
test('without the setting wired in, the guard is off', () => {
const gw = new Gateway({ rooms: {} as RoomManager, me: () => null });
const { ws, closed } = socket(gw);
for (let i = 0; i < 1000; i++) gw.handlers.message(ws, chatLine);
expect(closed()).toBeNull();
});
});

View File

@@ -8,7 +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. */
/** Every message, checked before parsing (room for both budgets below), so a flood never costs a JSON parse each.
* Only while the chat flood guard is on: with it off chat is unlimited, so the raw count cannot be capped. */
rawBucket: TokenBucket;
bucket: TokenBucket;
/** Chat lines and "입력 중" signals have their own budget, so typing fast never eats into (or waits on) game moves. */
@@ -27,6 +28,8 @@ export interface GatewayDeps {
onClose?: (userId: string) => void;
/** Web build being served (pages opened with an older one offer to refresh, docs/07 §11.1). */
build?: () => string | null;
/** Admin setting 채팅 도배 방지 (read per message, so a change applies at once). Off when not given. */
chatFloodGuard?: () => boolean;
}
export const MAX_CONNS_PER_USER = 5;
@@ -130,7 +133,8 @@ export class Gateway {
const strike = () => {
if (++ws.data.strikes > 50) ws.close(4429, 'rate limited');
};
if (!ws.data.rawBucket.take()) return strike();
const guard = this.deps.chatFloodGuard?.() ?? false;
if (guard && !ws.data.rawBucket.take()) return strike();
let json: unknown;
let badJson = false;
try {
@@ -138,8 +142,10 @@ export class Gateway {
} catch {
badJson = true;
}
const bucket = !badJson && isChatMessage(json) ? ws.data.chatBucket : ws.data.bucket;
if (!bucket.take()) return strike();
// Guard off: chat is never limited. Everything else keeps the general budget, and junk is still cut off by strikes.
const chat = !badJson && isChatMessage(json);
const bucket = chat ? (guard ? ws.data.chatBucket : null) : ws.data.bucket;
if (bucket && !bucket.take()) return strike();
if (badJson) {
this.send(ws, { t: 'error', code: 'bad-json', message: '잘못된 요청이에요.' });
return;

View File

@@ -372,10 +372,15 @@ function Site() {
<input className="input" type="number" min={min} max={max} value={s[k]} onChange={(e) => setS({ ...s, [k]: Number(e.target.value) })} />
</label>
);
const bool = (k: string, label: string, on = '켜기', off = '끄기') => (
const bool = (k: string, label: string, on = '켜기', off = '끄기', hint?: string) => (
<div className="stack" style={{ gap: 6 }}>
<strong>{label}</strong>
<div className="segmented">
{hint && (
<p className="muted small" style={{ margin: 0 }}>
{hint}
</p>
)}
<div className="segmented" role="group" aria-label={label}>
<button type="button" aria-pressed={s[k]} onClick={() => setS({ ...s, [k]: true })}>
{on}
</button>
@@ -446,6 +451,13 @@ function Site() {
{num('graceSec', '연결 끊김 유예(초, 새 방 기본값)', 10, 600)}
{bool('chatEnabledDefault', '새 방 채팅 기본값', '켜기', '끄기')}
{bool('chatFilterDefault', '새 방 욕설 필터 기본값', '켜기', '끄기')}
{bool(
'chatFloodGuard',
'채팅 도배 방지',
'켜기',
'끄기',
'켜면 한 사람이 매크로처럼 아주 빠르게(초당 50개 넘게) 보내는 채팅을 막아요. 끄면 채팅 속도 제한이 전혀 없어요. 사람이 치는 속도로는 어느 쪽이든 바로 올라가요. 저장하면 바로 적용돼요.',
)}
</section>
<section className="card stack">
<label className="field">

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개(사람은 닿지 않는 매크로 방지용, 채팅 줄 자체의 속도 제한은 없음). 둘을 합친 원시 한도(초당 70, 최대 240)를 JSON 해석 전에 먼저 적용. 넘으면 버리고 계속 넘으면 연결 종료 |
| 속도 제한 | 연결당 토큰 버킷 초당 20개, 최대 40개. 채팅(방 채팅·게임 채팅 `act` type `chat`·`typing`)은 이 한도를 쓰지 않음. 관리자 설정 "채팅 도배 방지"(기본 꺼짐)를 켜면 채팅은 따로 초당 50개, 최대 200개(사람은 닿지 않는 매크로 방지용)이고, 둘을 합친 원시 한도(초당 70, 최대 240)를 JSON 해석 전에 먼저 적용. 끄면 채팅 속도 제한 없음. 넘으면 버리고 계속 넘으면 연결 종료 |
| 압축 | permessage-deflate 사용(1KB 이상 메시지만 효과) |
| 서버 송신 버퍼 | 연결당 1MB 넘게 밀리면(느린 클라이언트) 연결을 끊음 → 재연결 시 전체 상태로 회복 |

View File

@@ -57,6 +57,7 @@
| 서버 전체 방 수 | 2000 | 방 만들기 제한 |
| 연결 끊김 유예(초) | 60 | 새 방의 기본값 |
| 채팅 기본값 | 켜짐 / 필터 켜짐 | 새 방의 기본값 |
| 채팅 도배 방지 | 꺼짐 | 켜면 접속마다 채팅·입력 중 신호를 초당 50개(한 번에 200개)까지만 받음(`03-realtime-protocol.md` §8). 끄면 채팅 속도 제한 없음. 저장하면 바로 적용 |
| 게임 속도 배율 | 1배 | 1/16~16배. 게임 화면의 애니메이션·연출(배너가 떠 있는 시간, 차례로 이어지는 연출, 다시 보기 한 칸)과 컴퓨터가 생각하는 시간을 이 배율로 나눈다(2배 = 두 배 빠르게). 저장하면 열린 방에도 바로 적용(방 정보 `RoomView.gameSpeed`로 다시 보냄). 턴 제한 시간·결과 화면 대기 같은 규칙 시간, 원카드 외치기 같은 반응 경쟁, 실시간 게임의 판정 시간은 그대로 |
## 6. 사용자 관리 (슈퍼어드민)

View File

@@ -118,6 +118,19 @@ try {
if (cfg !== 2) throw new Error(`gameSpeed not saved: ${cfg}`);
});
await step('사이트 탭: 채팅 도배 방지는 기본 끄기, 켜기 저장 → 서버에 바로 반영', async () => {
const guard = a.getByRole('group', { name: '채팅 도배 방지' });
if ((await guard.getByRole('button', { name: '끄기' }).getAttribute('aria-pressed')) !== 'true') throw new Error('chat flood guard should default to off');
if (app.settings.getSite().chatFloodGuard !== false) throw new Error('server default should be off');
await guard.getByRole('button', { name: '켜기' }).click();
await guard.evaluate((el) => el.scrollIntoView({ block: 'center' }));
await a.screenshot({ path: join(SHOTS, 'admin-5-chat-flood-guard.png') });
await a.getByRole('button', { name: '저장', exact: true }).click();
await a.getByText('저장했어요.').last().waitFor();
for (let i = 0; i < 20 && app.settings.getSite().chatFloodGuard !== true; i++) await a.waitForTimeout(100);
if (app.settings.getSite().chatFloodGuard !== true) throw new Error('chat flood guard not saved');
});
await step('기록 탭에 변경 내역', async () => {
await a.locator('.admin-side').getByRole('link', { name: '기록', exact: true }).click();
await a.getByText('어드민 추가').waitFor();