From 1bd69200fd2fe1450efd70c08d9fb3dc16c0f47d Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sun, 18 Oct 2026 04:16:17 +0900 Subject: [PATCH] =?UTF-8?q?=EB=9D=BC=EC=9D=B4=EC=96=B4=20=EA=B2=8C?= =?UTF-8?q?=EC=9E=84:=20=EA=B4=80=EB=A6=AC=EC=9E=90=20=ED=99=94=EB=A9=B4?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EC=A3=BC=EC=A0=9C=C2=B7=EC=A0=9C=EC=8B=9C?= =?UTF-8?q?=EC=96=B4=20=EC=B6=94=EA=B0=80/=EC=88=98=EC=A0=95/=EC=82=AD?= =?UTF-8?q?=EC=A0=9C,=20=EB=B0=94=EB=B3=B4=20=EB=AA=A8=EB=93=9C=20?= =?UTF-8?q?=EB=9D=BC=EC=9D=B4=EC=96=B4=EB=8A=94=20=EB=B9=84=EC=8A=B7?= =?UTF-8?q?=ED=95=9C=20=EB=8B=A8=EC=96=B4(=EA=B0=99=EC=9D=80=20=EB=AC=B6?= =?UTF-8?q?=EC=9D=8C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 제시어 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 --- README.md | 2 +- apps/server/src/admin.test.ts | 108 ++++++ apps/server/src/admin/liar-bank.ts | 153 ++++++++ .../src/db/migrations/004_liar_bank.sql | 5 + apps/server/src/http/admin.ts | 53 +++ apps/server/src/http/app.ts | 4 + apps/server/src/rooms/room.ts | 3 +- apps/server/src/server.ts | 4 + apps/web/src/games/liar/index.tsx | 40 ++- apps/web/src/pages/admin/AdminApp.tsx | 8 + apps/web/src/pages/admin/LiarWords.tsx | 338 ++++++++++++++++++ docs/14-admin.md | 10 + docs/games/liar.md | 21 +- e2e/admin.e2e.ts | 68 ++++ packages/engine/src/types.ts | 5 + packages/games/src/liar/bank/animal.ts | 24 ++ packages/games/src/liar/bank/body.ts | 15 + packages/games/src/liar/bank/brand.ts | 18 + packages/games/src/liar/bank/character.ts | 18 + packages/games/src/liar/bank/clothes.ts | 19 + packages/games/src/liar/bank/country.ts | 21 ++ packages/games/src/liar/bank/fairy.ts | 17 + packages/games/src/liar/bank/food.ts | 23 ++ packages/games/src/liar/bank/fruit.ts | 15 + packages/games/src/liar/bank/game.ts | 18 + packages/games/src/liar/bank/instrument.ts | 15 + packages/games/src/liar/bank/job.ts | 26 ++ packages/games/src/liar/bank/landmark.ts | 17 + packages/games/src/liar/bank/movie.ts | 17 + packages/games/src/liar/bank/nature.ts | 18 + packages/games/src/liar/bank/person.ts | 16 + packages/games/src/liar/bank/place.ts | 24 ++ packages/games/src/liar/bank/sea.ts | 17 + packages/games/src/liar/bank/snack.ts | 16 + packages/games/src/liar/bank/sport.ts | 18 + packages/games/src/liar/bank/thing.ts | 29 ++ packages/games/src/liar/bank/vegetable.ts | 18 + packages/games/src/liar/bank/vehicle.ts | 18 + packages/games/src/liar/bank/w.ts | 10 +- packages/games/src/liar/bot.test.ts | 4 +- packages/games/src/liar/bot.ts | 15 +- packages/games/src/liar/index.ts | 123 +++++-- packages/games/src/liar/liar.test.ts | 125 ++++++- packages/games/src/liar/types.ts | 26 +- packages/games/src/liar/words.ts | 122 ++++++- scripts/liar-groups-check.ts | 30 ++ 46 files changed, 1639 insertions(+), 75 deletions(-) create mode 100644 apps/server/src/admin/liar-bank.ts create mode 100644 apps/server/src/db/migrations/004_liar_bank.sql create mode 100644 apps/web/src/pages/admin/LiarWords.tsx create mode 100644 scripts/liar-groups-check.ts diff --git a/README.md b/README.md index e99b9cc..343fe20 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ - 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 36개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만. - 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드. - 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드. -- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록. +- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 라이어 게임 주제·제시어 추가/수정/삭제, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록. ## 개발 ```bash diff --git a/apps/server/src/admin.test.ts b/apps/server/src/admin.test.ts index 28838f7..5047f04 100644 --- a/apps/server/src/admin.test.ts +++ b/apps/server/src/admin.test.ts @@ -2,6 +2,8 @@ import { afterEach, describe, expect, test } from 'bun:test'; import { Client, TEST_SUPERADMINS, api, boot, guest, sleep } from './test-utils'; import { GUEST_IDLE_MS } from './server'; +import { TOPICS, bankTopics, liarBankRef, setLiarBank, setLiarBankResolver, type LiarState } from '@bg/games/liar'; +import type { Conn, Room } from './rooms/room'; const [SUPER, SUPER2] = TEST_SUPERADMINS; type Booted = ReturnType; @@ -11,6 +13,9 @@ const clients: Client[] = []; afterEach(async () => { for (const c of clients.splice(0)) c.close(); for (const s of running.splice(0)) await s.stop(); + // The 라이어 word bank is process-wide (the game module holds it): back to the code's for the next test. + setLiarBank(TOPICS, null); + setLiarBankResolver(null); }); function start(): Booted { @@ -142,6 +147,109 @@ describe('game settings', () => { }); }); +describe('라이어 게임 제시어 (§4.1)', () => { + const topic = { + ko: '우리 반', + generic: ['교실에 있어요', '매일 봐요'], + words: [ + { word: '칠판', hints: ['앞에 걸려 있어요', '분필로 써요'], aliases: ['흑판'], group: '앞' }, + { word: '교탁', hints: ['선생님 자리예요'], group: '앞' }, + { word: '사물함', hints: ['뒤에 있어요', '자물쇠를 달아요'], group: '뒤' }, + { word: '청소함', hints: ['빗자루가 들어 있어요'], group: '뒤' }, + ], + }; + const send = (s: Booted, cookie: string, method: string, path: string, body?: unknown) => + api(s.base, `/api/admin/liar${path}`, { method, cookie, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + + test('추가·수정·삭제·되돌리기, 잘못된 단어는 이유와 함께 거절, 일반 사용자는 403, 모두 기록', async () => { + const s = start(); + const sup = await discordLogin(s, SUPER); + const plain = await discordLogin(s, '111111111111111111'); + expect((await send(s, plain.cookie, 'GET', '/topics')).res.status).toBe(403); + expect((await send(s, plain.cookie, 'POST', '/topics', topic)).res.status).toBe(403); + + const list = await send(s, sup.cookie, 'GET', '/topics'); + expect(list.body.topics.map((t: any) => t.id)).toEqual(TOPICS.map((t) => t.id)); + expect(list.body.topics[0]).toMatchObject({ id: 'fruit', builtin: true, modified: false, deleted: false }); + expect(list.body.topics[0].words[0].group).toBeTruthy(); + + // Problems come back in Korean: the word inside its own hint, and one word inside another. + const bad = await send(s, sup.cookie, 'POST', '/topics', { ...topic, words: [...topic.words, { word: '큰칠판', hints: ['큰 칠판이에요'] }] }); + expect(bad.res.status).toBe(400); + expect(bad.body.error).toContain("'큰칠판'의 설명"); + expect(bad.body.error).toContain("'칠판'가 '큰칠판' 안에"); + + const made = await send(s, sup.cookie, 'POST', '/topics', topic); + expect(made.res.status).toBe(200); + const id = made.body.topic.id as string; + expect(id).toMatch(/^c_[a-z0-9]+$/); + expect(made.body.topic).toMatchObject({ ko: '우리 반', builtin: false, deleted: false }); + expect((await api(s.base, '/api/liar/topics')).body.topics.at(-1)).toEqual({ id, ko: '우리 반', words: 4 }); + + // Edit a built-in topic (drop 수박), then reset it. + const fruit = list.body.topics[0]; + const edited = await send(s, sup.cookie, 'PUT', '/topics/fruit', { ko: fruit.ko, generic: fruit.generic, words: fruit.words.filter((w: any) => w.word !== '수박') }); + expect(edited.res.status).toBe(200); + expect(edited.body.topic).toMatchObject({ builtin: true, modified: true }); + expect(bankTopics(liarBankRef()).find((t) => t.id === 'fruit')!.words.some((w) => w.word === '수박')).toBe(false); + expect((await send(s, sup.cookie, 'POST', '/topics/fruit/reset')).body.topic.modified).toBe(false); + expect(bankTopics(liarBankRef()).find((t) => t.id === 'fruit')!.words.some((w) => w.word === '수박')).toBe(true); + + // Delete: a built-in topic is hidden (and can come back), an admin's own is gone. + expect((await send(s, sup.cookie, 'DELETE', '/topics/person')).res.status).toBe(200); + expect((await api(s.base, '/api/liar/topics')).body.topics.some((t: any) => t.id === 'person')).toBe(false); + expect((await send(s, sup.cookie, 'GET', '/topics')).body.topics.find((t: any) => t.id === 'person')).toMatchObject({ deleted: true }); + await send(s, sup.cookie, 'POST', '/topics/person/reset'); + expect((await api(s.base, '/api/liar/topics')).body.topics.some((t: any) => t.id === 'person')).toBe(true); + expect((await send(s, sup.cookie, 'DELETE', `/topics/${id}`)).res.status).toBe(200); + expect((await send(s, sup.cookie, 'PUT', `/topics/${id}`, topic)).res.status).toBe(404); + expect(liarBankRef()).toBeNull(); + + const audit = await api(s.base, '/api/admin/audit', { cookie: sup.cookie }); + expect(audit.body.entries.map((e: any) => e.action)).toEqual(['liar.topic.delete', 'liar.topic.reset', 'liar.topic.delete', 'liar.topic.reset', 'liar.topic.update', 'liar.topic.create']); + }); + + test('새 판은 고친 은행을 쓰고 그 판본을 옵션에 남겨요. 은행을 또 고쳐도 지난 판본은 남고, 서버를 다시 켜도 그대로', async () => { + const s = start(); + const sup = await discordLogin(s, SUPER); + const id = (await send(s, sup.cookie, 'POST', '/topics', topic)).body.topic.id as string; + const ref = liarBankRef()!; + expect(ref).toBeTruthy(); + const host = await guest(s.base, '방장'); + const room = s.rooms.createPractice(host.id, 'liar') as Room; + const conn: Conn = { userId: host.id, send: () => {}, close: () => {} }; + room.join(conn, 'player'); + expect(room.configure(host.id, { options: { ...(room.config.options as object), topic: id, foolMode: true } })).toBeNull(); + expect(room.start(host.id)).toBeNull(); + for (let i = 0; i < 200 && !room.game; i++) await sleep(10); + const st = room.game!.state as LiarState; + expect(st.topic).toBe(id); + expect(st.options.bank).toBe(ref); + expect(st.words).toEqual(['칠판', '교탁', '사물함', '청소함']); + // 바보 모드: the liar's word is from the same group. + const group = (w: string) => topic.words.find((x) => x.word === w)!.group; + expect(group(st.liarWord!)).toBe(group(st.word)); + const stored = s.db.query<{ options_json: string }, []>("SELECT options_json FROM games WHERE game_id = 'liar'").get()!; + expect(JSON.parse(stored.options_json).bank).toBe(ref); + + // Another change: a new version; the old one is still found (replays). + await send(s, sup.cookie, 'PUT', `/topics/${id}`, { ...topic, words: topic.words.slice(0, 2) }); + expect(liarBankRef()).not.toBe(ref); + expect(bankTopics(ref).find((t) => t.id === id)!.words).toHaveLength(4); + expect(bankTopics(liarBankRef()).find((t) => t.id === id)!.words).toHaveLength(2); + + // Restart on the same database: same bank, same version name. + const now = liarBankRef(); + await s.stop(); + running.splice(running.indexOf(s), 1); + setLiarBank(TOPICS, null); + const again = boot(s.dbPath); + running.push(again); + expect(liarBankRef()).toBe(now); + expect(bankTopics(ref).find((t) => t.id === id)!.words).toHaveLength(4); + }); +}); + describe('admin-only options (threat guides)', () => { test('off by default; the host cannot turn them on; the admin default always wins and is not shown as a lock', async () => { const s = start(); diff --git a/apps/server/src/admin/liar-bank.ts b/apps/server/src/admin/liar-bank.ts new file mode 100644 index 0000000..6cddda0 --- /dev/null +++ b/apps/server/src/admin/liar-bank.ts @@ -0,0 +1,153 @@ +/** + * 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1): admins replace, delete or add whole topics. + * The changes live in `liar_topics`; the merged bank is handed to the game module (`setLiarBank`) with a version name + * (hash of the changes) that new games carry in their options. Every version is kept in `liar_bank_versions` so a replay + * (or a game restored after a restart) sets up from the bank it started with. + */ +import type { Database } from 'bun:sqlite'; +import { z } from 'zod'; +import { TOPICS, mergeBank, setLiarBank, setLiarBankResolver, topicProblems, type LiarTopic, type TopicOverride } from '@bg/games/liar'; +import { sha256Hex } from '../auth/sessions'; + +const line = (max: number) => z.string().trim().min(1).max(max); +export const LiarTopicInputSchema = z.object({ + ko: line(20), + generic: z.array(line(80)).max(20), + words: z + .array( + z.object({ + word: line(20), + aliases: z.array(line(20)).max(10).optional(), + hints: z.array(line(80)).max(10), + group: z.string().trim().max(20).optional(), + }), + ) + .max(300), +}); +export type LiarTopicInput = z.infer; + +/** Most topics an admin may add. */ +export const CUSTOM_TOPICS_MAX = 100; + +export interface AdminLiarTopic extends Omit { + builtin: boolean; + /** Built-in topic changed by an admin (can be reset). */ + modified: boolean; + /** Built-in topic an admin deleted (can be restored). */ + deleted: boolean; +} + +/** Drops empty optional fields so the stored JSON stays small and stable. */ +function clean(t: LiarTopicInput): NonNullable { + return { + ko: t.ko, + generic: t.generic, + words: t.words.map((x) => ({ + word: x.word, + hints: x.hints, + ...(x.aliases?.length ? { aliases: x.aliases } : {}), + ...(x.group ? { group: x.group } : {}), + })), + }; +} + +export class LiarBankStore { + private rows: TopicOverride[] = []; + private versions = new Map(); + + constructor(private db: Database) { + this.load(); + setLiarBankResolver((ref) => this.version(ref)); + } + + private load(): void { + this.rows = this.db + .query<{ id: string; json: string }, []>('SELECT id, json FROM liar_topics ORDER BY created_at, id') + .all() + .map((r) => ({ id: r.id, ...(JSON.parse(r.json) as Omit) })); + const ref = this.rows.length ? sha256Hex(JSON.stringify(this.rows)).slice(0, 16) : null; + const topics = mergeBank(this.rows); + if (ref) { + this.db.query('INSERT OR IGNORE INTO liar_bank_versions (ref, json, created_at) VALUES (?, ?, ?)').run(ref, JSON.stringify(this.rows), Date.now()); + this.versions.set(ref, topics); + } + setLiarBank(topics, ref); + } + + /** A stored bank version (null if unknown: the game falls back to the bank in the code). */ + private version(ref: string): readonly LiarTopic[] | null { + const hit = this.versions.get(ref); + if (hit) return hit; + const row = this.db.query<{ json: string }, [string]>('SELECT json FROM liar_bank_versions WHERE ref = ?').get(ref); + if (!row) return null; + const topics = mergeBank(JSON.parse(row.json) as TopicOverride[]); + if (this.versions.size > 50) this.versions.clear(); + this.versions.set(ref, topics); + return topics; + } + + /** Every topic for the admin screen: the bank in use (code order, then the admins' own), then deleted built-in ones. */ + list(): AdminLiarTopic[] { + const by = new Map(this.rows.map((r) => [r.id, r])); + const out: AdminLiarTopic[] = mergeBank(this.rows).map((t) => { + const builtin = TOPICS.some((b) => b.id === t.id); + return { id: t.id, ko: t.ko, generic: t.generic, words: t.words, builtin, modified: builtin && !!by.get(t.id)?.topic, deleted: false }; + }); + for (const b of TOPICS) if (by.get(b.id)?.deleted) out.push({ id: b.id, ko: b.ko, generic: b.generic, words: b.words, builtin: true, modified: false, deleted: true }); + return out; + } + + get(id: string): AdminLiarTopic | null { + return this.list().find((t) => t.id === id) ?? null; + } + + /** Problems (Korean) with a topic as typed, or none. */ + problems(t: LiarTopicInput): string[] { + return topicProblems(clean(t)); + } + + private write(id: string, value: Omit, by: string, now: number): void { + this.db + .query( + 'INSERT INTO liar_topics (id, json, created_at, updated_by, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET json = excluded.json, updated_by = excluded.updated_by, updated_at = excluded.updated_at', + ) + .run(id, JSON.stringify(value), now, by, now); + this.load(); + } + + private remove(id: string): void { + this.db.query('DELETE FROM liar_topics WHERE id = ?').run(id); + this.load(); + } + + /** Replaces a topic (built-in or the admins' own, also a deleted built-in one: that restores it). Validate first. */ + save(id: string, t: LiarTopicInput, by: string, now = Date.now()): void { + this.write(id, { topic: clean(t) }, by, now); + } + + /** Adds a topic of the admins' own; returns its id, or null when there are too many. */ + create(t: LiarTopicInput, by: string, now = Date.now()): string | null { + if (this.rows.filter((r) => !TOPICS.some((b) => b.id === r.id)).length >= CUSTOM_TOPICS_MAX) return null; + let id: string; + do id = `c_${now.toString(36)}${Math.floor(Math.random() * 36 ** 3).toString(36)}`; + while (this.rows.some((r) => r.id === id)); + this.write(id, { topic: clean(t) }, by, now); + return id; + } + + /** Deletes a topic: a built-in one is hidden (can be restored), an admin's own is gone. */ + delete(id: string, by: string, now = Date.now()): void { + if (TOPICS.some((b) => b.id === id)) this.write(id, { deleted: true }, by, now); + else this.remove(id); + } + + /** A built-in topic back to the code's words (undoes a change or a delete). */ + reset(id: string): void { + this.remove(id); + } + + /** Topics new rooms can pick, for the lobby. */ + static choices(topics: readonly LiarTopic[]): { id: string; ko: string; words: number }[] { + return topics.map((t) => ({ id: t.id, ko: t.ko, words: t.words.length })); + } +} diff --git a/apps/server/src/db/migrations/004_liar_bank.sql b/apps/server/src/db/migrations/004_liar_bank.sql new file mode 100644 index 0000000..59f39aa --- /dev/null +++ b/apps/server/src/db/migrations/004_liar_bank.sql @@ -0,0 +1,5 @@ +-- 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1). +-- One row per changed topic: a built-in topic replaced ({"topic":…}) or deleted ({"deleted":true}), or an admin's own topic (id c_…). +CREATE TABLE liar_topics (id TEXT PRIMARY KEY, json TEXT NOT NULL, created_at INTEGER NOT NULL, updated_by TEXT, updated_at INTEGER NOT NULL); +-- Every set of changes games were started with (options.bank = ref), so replays set up from the same bank. +CREATE TABLE liar_bank_versions (ref TEXT PRIMARY KEY, json TEXT NOT NULL, created_at INTEGER NOT NULL); diff --git a/apps/server/src/http/admin.ts b/apps/server/src/http/admin.ts index da43c3f..1fa6785 100644 --- a/apps/server/src/http/admin.ts +++ b/apps/server/src/http/admin.ts @@ -5,6 +5,7 @@ import type { AnyGameDefinition } from '@bg/engine'; import { botProfile, nicknameError, normalizeNickname } from '@bg/shared'; import type { Audit, Role, Roles } from '../admin/roles'; import { GameSettingsSchema, SiteSettingsSchema, type SettingsStore } from '../admin/settings'; +import { LiarTopicInputSchema, type LiarBankStore } from '../admin/liar-bank'; import type { Sessions } from '../auth/sessions'; import { toPublicUser, type Users } from '../auth/users'; import type { RoomManager } from '../rooms/manager'; @@ -19,6 +20,7 @@ export interface AdminDeps { audit: Audit; settings: SettingsStore; games: Record; + liarBank: LiarBankStore; disconnectUser: (userId: string) => void; /** When an idle guest will be deleted; null for members and for guests still online or seated. */ guestDeleteAt: (u: { id: string; kind: 'guest' | 'member'; last_seen_at: number }) => number | null; @@ -85,6 +87,57 @@ export function createAdminApp(d: AdminDeps) { return c.json({ effective: d.settings.game(id), raw: {} }); }); + // ------------------------------------------------------------ 라이어 게임 topics and words (docs/14-admin.md §4.1) + app.get('/liar/topics', (c) => c.json({ topics: d.liarBank.list() })); + + /** Parses and checks a topic as typed; the error response, or the topic. */ + const liarInput = async (c: Context) => { + const parsed = LiarTopicInputSchema.safeParse(await body(c)); + if (!parsed.success) return { error: c.json({ error: `입력 값이 올바르지 않아요: ${parsed.error.issues.map((i) => i.path.join('.') + ' ' + i.message).join(', ')}` }, 400) }; + const problems = d.liarBank.problems(parsed.data); + if (problems.length) return { error: c.json({ error: problems.slice(0, 30).join('\n'), problems }, 400) }; + return { topic: parsed.data }; + }; + + app.post('/liar/topics', async (c) => { + const r = await liarInput(c); + if (r.error) return r.error; + const id = d.liarBank.create(r.topic, actor(c)); + if (!id) return c.json({ error: '주제는 100개까지 더할 수 있어요.' }, 400); + d.audit.log(actor(c), 'liar.topic.create', id, null, r.topic); + return c.json({ topic: d.liarBank.get(id) }); + }); + + app.put('/liar/topics/:id', async (c) => { + const id = c.req.param('id'); + const before = d.liarBank.get(id); + if (!before) return c.json({ error: '없는 주제예요.' }, 404); + const r = await liarInput(c); + if (r.error) return r.error; + d.liarBank.save(id, r.topic, actor(c)); + d.audit.log(actor(c), 'liar.topic.update', id, before, r.topic); + return c.json({ topic: d.liarBank.get(id) }); + }); + + app.delete('/liar/topics/:id', (c) => { + const id = c.req.param('id'); + const before = d.liarBank.get(id); + if (!before || before.deleted) return c.json({ error: '없는 주제예요.' }, 404); + if (d.liarBank.list().filter((t) => !t.deleted).length <= 1) return c.json({ error: '주제가 하나는 있어야 해요.' }, 400); + d.liarBank.delete(id, actor(c)); + d.audit.log(actor(c), 'liar.topic.delete', id, before, null); + return c.json({ ok: true }); + }); + + app.post('/liar/topics/:id/reset', (c) => { + const id = c.req.param('id'); + const before = d.liarBank.get(id); + if (!before?.builtin) return c.json({ error: '처음부터 있던 주제만 되돌릴 수 있어요.' }, 400); + d.liarBank.reset(id); + d.audit.log(actor(c), 'liar.topic.reset', id, before, null); + return c.json({ topic: d.liarBank.get(id) }); + }); + // ------------------------------------------------------------ site app.get('/site', (c) => c.json({ site: d.settings.getSite() })); app.put('/site', async (c) => { diff --git a/apps/server/src/http/app.ts b/apps/server/src/http/app.ts index cbaa638..a5f569d 100644 --- a/apps/server/src/http/app.ts +++ b/apps/server/src/http/app.ts @@ -2,6 +2,7 @@ import { Hono, type Context } from 'hono'; import { deleteCookie, getCookie, setCookie } from 'hono/cookie'; import { z } from 'zod'; +import { bankTopics, liarBankRef } from '@bg/games/liar'; import { nicknameError, normalizeNickname, normalizeRoomCode, formatRoomCode } from '@bg/shared'; import type { Config } from '../config'; import { authorizeUrl, avatarUrl, exchangeCode, safeNext, type DiscordUser } from '../auth/discord'; @@ -102,6 +103,9 @@ export function createHttpApp(d: HttpDeps) { }); }); + // 라이어 게임 topics new games can use (admins may add or delete some): the lobby's 주제 choices. + app.get('/api/liar/topics', (c) => c.json({ topics: bankTopics(liarBankRef()).map((t) => ({ id: t.id, ko: t.ko, words: t.words.length })) })); + app.post('/api/auth/guest', async (c) => { if (!guestLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429); const body = z.object({ nickname: z.string().max(100) }).safeParse(await c.req.json().catch(() => null)); diff --git a/apps/server/src/rooms/room.ts b/apps/server/src/rooms/room.ts index 10a2e67..0bd5a5b 100644 --- a/apps/server/src/rooms/room.ts +++ b/apps/server/src/rooms/room.ts @@ -904,7 +904,8 @@ export class Room { if (countErr) return countErr; const eff = this.deps.settings?.game(def.id); if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.'; - return { options: parsed.data }; + // Data the server decides (e.g. the admin-edited 라이어 word-bank version) goes with the options, so replays match. + return { options: def.prepareOptions ? def.prepareOptions(parsed.data) : parsed.data }; } /** diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index b797079..9186609 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -18,6 +18,7 @@ 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; @@ -57,6 +58,8 @@ export function startServer(opts: StartOptions) { 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(); @@ -131,6 +134,7 @@ export function startServer(opts: StartOptions) { 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: () => { diff --git a/apps/web/src/games/liar/index.tsx b/apps/web/src/games/liar/index.tsx index 2266ea7..8d041cd 100644 --- a/apps/web/src/games/liar/index.tsx +++ b/apps/web/src/games/liar/index.tsx @@ -25,6 +25,32 @@ import { fxMs } from '../../lib/motion'; type Kind = LiarView['phase']['kind']; +// ---------------------------------------------------------------- topics (admins may add or delete some) + +type TopicChoice = { id: string; ko: string }; +/** The topics new games can use; the code's list until the server answers. */ +let topicChoices: TopicChoice[] = TOPIC_IDS.map((id) => ({ id, ko: TOPIC_KO[id] })); +let topicsLoad: Promise | null = null; +function loadTopics(): Promise { + topicsLoad ??= fetch('/api/liar/topics', { credentials: 'same-origin' }) + .then((r) => (r.ok ? (r.json() as Promise<{ topics: TopicChoice[] }>) : Promise.reject(new Error(String(r.status))))) + .then((d) => (topicChoices = d.topics)) + .catch(() => ((topicsLoad = null), topicChoices)); + return topicsLoad; +} +const topicName = (id: string) => topicChoices.find((t) => t.id === id)?.ko ?? (TOPIC_KO as Record)[id] ?? '관리자가 고른 주제'; +function useTopicChoices(): TopicChoice[] { + const [list, setList] = useState(topicChoices); + useEffect(() => { + let on = true; + void loadTopics().then((x) => on && setList(x)); + return () => { + on = false; + }; + }, []); + return list; +} + const PHASE_KO: Record = { reveal: '제시어 확인', describe: '한 사람씩 설명', @@ -662,7 +688,7 @@ function FinalReveal({ v, players }: { v: LiarView; players: Record🏆 {f.winner === 'liar' ? '라이어 승리' : '시민 승리'} {REASON_KO[f.reason]}. - 제시어 {f.word} · 주제 {TOPIC_KO[f.topic]} + 제시어 {f.word} · 주제 {f.topicKo ?? topicName(f.topic)} {f.liarWord ? ` · 라이어가 받은 단어: ${f.liarWord}` : ''} {f.guess !== null ? ` · 라이어의 답: "${f.guess}"` : ''} @@ -954,13 +980,16 @@ const secs = (...v: T[]): [T | null, string][] => [...v.map((x function Options({ value: o, onChange }: OptionsProps) { const [more, setMore] = useState(false); + const topics = useTopicChoices(); + // A topic an admin deleted plays as 무작위 (shown as such so the host isn't left with a hidden choice). + const topic = o.topic === 'random' || topics.some((t) => t.id === o.topic) ? o.topic : 'random'; const set = (patch: Partial) => onChange({ ...o, ...patch }); return (
- label="주제" value={o.topic} options={[['random', '무작위'], ...TOPIC_IDS.map((t): [LiarOptions['topic'], string] => [t, TOPIC_KO[t]])]} onChange={(topic) => set({ topic })} /> + label="주제" value={topic} options={[['random', '무작위'], ...topics.map((t): [string, string] => [t.id, t.ko])]} onChange={(next) => set({ topic: next })} /> - + set({ foolMode })} /> @@ -1015,7 +1044,8 @@ function Options({ value: o, onChange }: OptionsProps) { } function optionsSummary(o: LiarOptions): string { - const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${TOPIC_KO[o.topic]}`]; + void loadTopics(); + const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${topicName(o.topic)}`]; if (o.foolMode) parts.push('바보 모드'); parts.push(o.rounds === 2 ? '두 바퀴' : '한 바퀴', o.describeSeconds === null ? '설명 무제한' : `설명 ${o.describeSeconds}초`, o.discussionSeconds === null ? '토론 무제한' : `토론 ${o.discussionSeconds}초`, o.guessMode === 'choice' ? '정답은 목록에서' : '정답은 직접 적기'); return parts.join(' · '); @@ -1038,7 +1068,7 @@ function Rules() {
  • 투표는 나를 뺀 한 명을 골라요. 동점이면 동점인 사람끼리 한 번 더 투표하고, 또 동점이면 라이어가 이겨요.
  • 라이어가 아닌 사람이 지목되면 라이어 승리. 라이어가 지목되면 제시어를 한 번 맞힐 수 있어요(띄어쓰기·대소문자 무시). 맞히면 라이어, 틀리면 시민 승리예요.
  • 점수: 시민이 이기면 시민마다 1점, 라이어가 이기면 라이어 2점.
  • -
  • 바보 모드: 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.
  • +
  • 바보 모드: 라이어도 제시어와 비슷한 다른 단어(같은 주제, 같은 묶음)를 받고, 자기가 라이어인지 몰라요.
  • 시간 무제한: 설명·토론·투표·정답 맞히기 시간을 무제한으로 할 수 있어요. 그 단계는 할 일을 다 마칠 때까지 기다려요.
  • 내 제시어는 "내 제시어" 카드를 꾹 누르고 있을 때만 보여요. 게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요.

    diff --git a/apps/web/src/pages/admin/AdminApp.tsx b/apps/web/src/pages/admin/AdminApp.tsx index 3c661a1..4c02db2 100644 --- a/apps/web/src/pages/admin/AdminApp.tsx +++ b/apps/web/src/pages/admin/AdminApp.tsx @@ -7,6 +7,7 @@ import { apiCall, discordLoginUrl, type Role } from '../../net/api'; import { useSession } from '../../store/session'; import { toast } from '../../store/toast'; import { SchemaForm, type JsonSchema } from './SchemaForm'; +import { LiarTopicEditor, LiarTopics } from './LiarWords'; import { gameName } from '../../components/GameNotice'; import { RecordCell, record, recordText, resultLabel, sumStats } from '../../components/PlayerCard'; import type { GameStat } from '../../net/api'; @@ -53,6 +54,7 @@ export default function AdminApp() { const tabs: [string, string, boolean][] = [ ['', '대시보드', true], ['games', '게임', true], + ['liar', '라이어 제시어', true], ['rooms', '방', true], ['site', '사이트', true], ['users', '사용자', sup], @@ -81,6 +83,8 @@ export default function AdminApp() { } /> } /> } /> + } /> + } /> } /> } /> {sup && } />} @@ -851,6 +855,10 @@ const ACTION_KO: Record = { 'user.delete': '계정 삭제', 'admin.add': '어드민 추가', 'admin.remove': '어드민 삭제', + 'liar.topic.create': '라이어 주제 추가', + 'liar.topic.update': '라이어 주제·제시어 수정', + 'liar.topic.delete': '라이어 주제 삭제', + 'liar.topic.reset': '라이어 주제 되돌리기', }; function Audit() { diff --git a/apps/web/src/pages/admin/LiarWords.tsx b/apps/web/src/pages/admin/LiarWords.tsx new file mode 100644 index 0000000..8da06d6 --- /dev/null +++ b/apps/web/src/pages/admin/LiarWords.tsx @@ -0,0 +1,338 @@ +/** 관리자: 라이어 게임 주제와 제시어 (docs/14-admin.md §4.1). Changes apply to games started afterwards. */ +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useNavigate, useParams } from 'react-router'; +import { ConfirmSheet } from '../../components/ui'; +import { apiCall } from '../../net/api'; +import { toast } from '../../store/toast'; + +interface Word { + word: string; + aliases?: string[]; + hints: string[]; + group?: string; +} +interface Topic { + id: string; + ko: string; + generic: string[]; + words: Word[]; + builtin: boolean; + modified: boolean; + deleted: boolean; +} + +const api = (m: 'GET' | 'POST' | 'PUT' | 'DELETE', p: string, b?: unknown) => apiCall<{ topics?: Topic[]; topic?: Topic }>(m, `/api/admin/liar${p}`, b); +const lines = (s: string) => + s + .split('\n') + .map((x) => x.trim()) + .filter(Boolean); +const commas = (s: string) => + s + .split(',') + .map((x) => x.trim()) + .filter(Boolean); + +/** `key`: reload when it changes (the editor moves from 'new' to the created topic's id). */ +function useTopics(key = ''): [Topic[] | null, () => void] { + const [d, setD] = useState(null); + const load = useCallback(() => { + api('GET', '/topics').then( + (r) => setD(r.topics ?? []), + (e) => toast((e as Error).message, 'error'), + ); + }, [key]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(load, [load]); + return [d, load]; +} + +function badge(t: Topic): string { + if (t.deleted) return '삭제됨'; + if (!t.builtin) return '관리자가 더함'; + return t.modified ? '고침' : '기본'; +} + +export function LiarTopics() { + const nav = useNavigate(); + const [topics, reload] = useTopics(); + const [ask, setAsk] = useState<{ t: Topic; kind: 'delete' | 'reset' } | null>(null); + if (!topics) return

    불러오는 중…

    ; + const live = topics.filter((t) => !t.deleted); + return ( +
    +

    라이어 게임 제시어

    +

    + 주제 {live.length}개 · 제시어 {live.reduce((n, t) => n + t.words.length, 0)}개. 바꾼 내용은 새로 시작하는 판부터 쓰여요. 바보 모드의 라이어는 제시어와 같은 "묶음"의 다른 단어를 받아요(묶음이 없거나 혼자면 같은 주제의 아무 + 단어). +

    + +
    + {topics.map((t) => ( +
    +
    + {t.ko} + + {badge(t)} · 제시어 {t.words.length}개 · 묶음 {new Set(t.words.map((w) => w.group).filter(Boolean)).size}개 · ID {t.id} + +
    +
    + {!t.deleted && ( + + )} + {t.builtin && (t.modified || t.deleted) && ( + + )} + {!t.deleted && ( + + )} +
    +
    + ))} +
    + {ask && ( + { + try { + if (ask.kind === 'delete') await api('DELETE', `/topics/${ask.t.id}`); + else await api('POST', `/topics/${ask.t.id}/reset`); + toast(ask.kind === 'delete' ? '삭제했어요.' : '되돌렸어요.'); + } catch (e) { + toast((e as Error).message, 'error', 6000); + } + reload(); + }} + onClose={() => setAsk(null)} + /> + )} +
    + ); +} + +/** One word as typed in the editor. */ +interface WordForm { + word: string; + group: string; + aliases: string; + hints: string; +} +const toForm = (w: Word): WordForm => ({ word: w.word, group: w.group ?? '', aliases: (w.aliases ?? []).join(', '), hints: w.hints.join('\n') }); +const fromForm = (f: WordForm): Word => ({ word: f.word.trim(), group: f.group.trim() || undefined, aliases: commas(f.aliases), hints: lines(f.hints) }); +const EMPTY: WordForm = { word: '', group: '', aliases: '', hints: '' }; + +function WordEditor({ value, groups, onSave, onCancel }: { value: WordForm; groups: string[]; onSave: (f: WordForm) => void; onCancel: () => void }) { + const [f, setF] = useState(value); + return ( +
    +
    + + +
    + +