/** Admin site tests (docs/14-admin.md §9). */ 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'; const [SUPER, SUPER2] = TEST_SUPERADMINS; type Booted = ReturnType; const running: Booted[] = []; const clients: Client[] = []; afterEach(async () => { for (const c of clients.splice(0)) c.close(); for (const s of running.splice(0)) await s.stop(); }); function start(): Booted { const s = boot(undefined, { discordExchange: async (code) => ({ id: code, username: `user${code.slice(-4)}`, global_name: `디코${code.slice(-4)}`, avatar: null }), }); s.config.discord = { clientId: 'cid', clientSecret: 'sec' }; running.push(s); return s; } /** Logs in through the (mocked) Discord flow; returns the session cookie and user id. */ async function discordLogin(s: Booted, discordId: string): Promise<{ cookie: string; id: string }> { const st = await api(s.base, '/api/auth/discord/start?next=/'); const state = new URL(st.res.headers.get('location')!).searchParams.get('state')!; const oauth = st.setCookie!.split(';')[0]!; const cb = await api(s.base, `/api/auth/discord/callback?code=${discordId}&state=${state}`, { cookie: oauth }); const loc = cb.res.headers.get('location'); if (loc !== '/') throw new Error(`login redirect ${loc}`); const sid = cb.setCookie!.split(/,(?=\s*\w+=)/).find((c) => c.trim().startsWith('sid='))!.split(';')[0]!.trim(); const me = await api(s.base, '/api/me', { cookie: sid }); return { cookie: sid, id: me.body.me.id }; } describe('roles', () => { test('guest and plain discord users get 401/403; superadmin by fixed Discord ID', async () => { const s = start(); const g = await guest(s.base, '손님'); expect((await api(s.base, '/api/admin/me', { cookie: g.cookie })).res.status).toBe(403); expect((await api(s.base, '/api/admin/me')).res.status).toBe(401); const plain = await discordLogin(s, '111111111111111111'); expect((await api(s.base, '/api/admin/overview', { cookie: plain.cookie })).res.status).toBe(403); expect((await api(s.base, '/api/me', { cookie: plain.cookie })).body.role).toBe('user'); const sup = await discordLogin(s, SUPER); const me = await api(s.base, '/api/admin/me', { cookie: sup.cookie }); expect(me.body.role).toBe('superadmin'); expect((await api(s.base, '/api/me', { cookie: sup.cookie })).body.role).toBe('superadmin'); const sup2 = await discordLogin(s, SUPER2); expect((await api(s.base, '/api/admin/me', { cookie: sup2.cookie })).body.role).toBe('superadmin'); }); test('superadmin adds/removes an admin by Discord ID; takes effect immediately; admin cannot manage users', async () => { const s = start(); const sup = await discordLogin(s, SUPER); const adminDiscord = '222222222222222222'; const bad = await api(s.base, '/api/admin/admins', { method: 'POST', cookie: sup.cookie, body: JSON.stringify({ discordId: '12ab' }) }); expect(bad.res.status).toBe(400); // Pre-register before the person ever logged in. const add = await api(s.base, '/api/admin/admins', { method: 'POST', cookie: sup.cookie, body: JSON.stringify({ discordId: adminDiscord, note: '친구1' }) }); expect(add.res.status).toBe(200); expect(add.body.admins.map((a: any) => a.discordId)).toEqual([SUPER, SUPER2, adminDiscord]); const adm = await discordLogin(s, adminDiscord); expect((await api(s.base, '/api/admin/me', { cookie: adm.cookie })).body.role).toBe('admin'); expect((await api(s.base, '/api/admin/users', { cookie: adm.cookie })).res.status).toBe(403); expect((await api(s.base, '/api/admin/admins', { cookie: adm.cookie })).res.status).toBe(403); expect((await api(s.base, '/api/admin/games', { cookie: adm.cookie })).res.status).toBe(200); // Fixed superadmin cannot be removed. expect((await api(s.base, `/api/admin/admins/${SUPER}`, { method: 'DELETE', cookie: sup.cookie })).res.status).toBe(400); expect((await api(s.base, `/api/admin/admins/${adminDiscord}`, { method: 'DELETE', cookie: sup.cookie })).res.status).toBe(200); expect((await api(s.base, '/api/admin/me', { cookie: adm.cookie })).res.status).toBe(403); const audit = await api(s.base, '/api/admin/audit', { cookie: sup.cookie }); expect(audit.body.entries.map((e: any) => e.action)).toEqual(['admin.remove', 'admin.add']); }); test('admin API rejects foreign-origin writes', async () => { const s = start(); const sup = await discordLogin(s, SUPER); const res = await fetch(s.base + '/api/admin/site', { method: 'PUT', headers: { origin: 'https://evil.example', cookie: sup.cookie, 'content-type': 'application/json' }, body: JSON.stringify({ maintenance: true }), }); expect(res.status).toBe(403); }); }); describe('game settings', () => { test('schema exposed with Korean titles; defaults apply to new rooms; locked options win; invalid values rejected', async () => { const s = start(); const sup = await discordLogin(s, SUPER); const games = await api(s.base, '/api/admin/games', { cookie: sup.cookie }); const omok = games.body.games.find((g: any) => g.id === 'omok'); expect(omok.schema.properties.ruleSet.title).toBe('규칙'); expect(omok.schema.properties.autoMoveLimit.title).toContain('자동 착수'); const bad = await api(s.base, '/api/admin/games/omok', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ defaultOptions: { ruleSet: 'nope' } }), }); expect(bad.res.status).toBe(400); const tooMany = await api(s.base, '/api/admin/games/omok', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ maxPlayers: 3 }) }); expect(tooMany.res.status).toBe(400); const put = await api(s.base, '/api/admin/games/omok', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ nameKo: '오목(친구룰)', notice: '렌주룰로만 해요', defaultOptions: { ruleSet: 'renju', timeControl: { kind: 'perMove', perMoveSec: 45 } }, lockedOptions: ['ruleSet'], }), }); expect(put.res.status).toBe(200); expect(put.body.effective.defaultOptions.timeControl.perMoveSec).toBe(45); const cfg = await api(s.base, '/api/config'); expect(cfg.body.catalog.find((g: any) => g.id === 'omok')).toMatchObject({ nameKo: '오목(친구룰)', notice: '렌주룰로만 해요' }); // A host creates a room → admin defaults; trying to change the locked rule is overridden. const host = await guest(s.base, '방장'); const room = await api(s.base, '/api/rooms', { method: 'POST', cookie: host.cookie, body: JSON.stringify({ gameId: 'omok' }) }); const c = await new Client(s.base, host.cookie, host.id).connect(); clients.push(c); c.send({ t: 'join', code: room.body.code, as: 'player' }); const first = await c.next('room'); expect((first.room.options as any).ruleSet).toBe('renju'); expect(first.room.lockedOptions).toEqual(['ruleSet']); c.send({ t: 'config', options: { ...(first.room.options as any), ruleSet: 'free', boardSize: 19 } }); const after = await c.next('room', (m) => (m.room.options as any).boardSize === 19); expect((after.room.options as any).ruleSet).toBe('renju'); // Disable the game → creation refused and hidden from catalog. await api(s.base, '/api/admin/games/omok', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ enabled: false }) }); const refused = await api(s.base, '/api/rooms', { method: 'POST', cookie: host.cookie, body: JSON.stringify({ gameId: 'omok' }) }); expect(refused.res.status).toBe(400); expect((await api(s.base, '/api/config')).body.catalog.find((g: any) => g.id === 'omok').available).toBe(false); // Reset restores code defaults. await api(s.base, '/api/admin/games/omok/reset', { method: 'POST', cookie: sup.cookie }); expect((await api(s.base, '/api/config')).body.catalog.find((g: any) => g.id === 'omok')).toMatchObject({ nameKo: '오목', available: true }); }); }); 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(); const host = await guest(s.base, '방장'); const room = await api(s.base, '/api/rooms', { method: 'POST', cookie: host.cookie, body: JSON.stringify({ gameId: 'omok' }) }); const c = await new Client(s.base, host.cookie, host.id).connect(); clients.push(c); c.send({ t: 'join', code: room.body.code, as: 'player' }); const first = await c.next('room'); expect((first.room.options as any).threatHints).toBe(false); expect(first.room.lockedOptions).toEqual([]); c.send({ t: 'config', options: { ...(first.room.options as any), threatHints: true, boardSize: 19 } }); const after = await c.next('room', (m) => (m.room.options as any).boardSize === 19); expect((after.room.options as any).threatHints).toBe(false); const sup = await discordLogin(s, SUPER); const put = await api(s.base, '/api/admin/games/omok', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ defaultOptions: { threatHints: true } }) }); expect(put.res.status).toBe(200); const room2 = await api(s.base, '/api/rooms', { method: 'POST', cookie: host.cookie, body: JSON.stringify({ gameId: 'omok' }) }); const c2 = await new Client(s.base, host.cookie, host.id).connect(); clients.push(c2); c2.send({ t: 'join', code: room2.body.code, as: 'player' }); const r2 = await c2.next('room'); expect((r2.room.options as any).threatHints).toBe(true); expect(r2.room.lockedOptions).toEqual([]); c2.send({ t: 'config', options: { ...(r2.room.options as any), threatHints: false, boardSize: 19 } }); const after2 = await c2.next('room', (m) => (m.room.options as any).boardSize === 19); expect((after2.room.options as any).threatHints).toBe(true); }); }); describe('site settings, rooms, users', () => { test('maintenance blocks room creation; banned words masked in chat and rejected in nicknames', async () => { const s = start(); const sup = await discordLogin(s, SUPER); const site = (await api(s.base, '/api/admin/site', { cookie: sup.cookie })).body.site; await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, maintenance: true, announcement: '점검 중이에요' }) }); const g = await guest(s.base, '방장님'); const r = await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ gameId: 'omok' }) }); expect(r.res.status).toBe(429); expect(r.body.error).toBe('점검 중이에요'); expect((await api(s.base, '/api/config')).body).toMatchObject({ maintenance: true, announcement: '점검 중이에요' }); await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, bannedWords: ['바보'] }) }); expect((await api(s.base, '/api/auth/guest', { method: 'POST', body: JSON.stringify({ nickname: '왕바보' }) })).res.status).toBe(400); const room = await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ gameId: 'omok' }) }); const c = await new Client(s.base, g.cookie, g.id).connect(); clients.push(c); c.send({ t: 'join', code: room.body.code, as: 'player' }); await c.next('room'); const chat = c.next('chat'); c.send({ t: 'chat', text: '너 바보야' }); expect((await chat).text).toBe('너 **야'); }); test('admin closes a room: everyone is told and disconnected from it', async () => { const s = start(); const sup = await discordLogin(s, SUPER); const g = await guest(s.base, '방주인'); const room = await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ gameId: 'omok' }) }); const c = await new Client(s.base, g.cookie, g.id).connect(); clients.push(c); c.send({ t: 'join', code: room.body.code, as: 'player' }); await c.next('room'); const list = await api(s.base, '/api/admin/rooms', { cookie: sup.cookie }); expect(list.body.rooms.map((r: any) => r.code)).toContain(room.body.code); const bye = c.next('bye'); expect((await api(s.base, `/api/admin/rooms/${room.body.code}/close`, { method: 'POST', cookie: sup.cookie })).res.status).toBe(200); expect((await bye).reason).toBe('closed'); expect((await api(s.base, `/api/rooms/${room.body.code}`)).res.status).toBe(404); }); test('superadmin: search, rename, ban (sessions revoked, socket closed, discord re-login refused), unban', async () => { const s = start(); const sup = await discordLogin(s, SUPER); const victim = await discordLogin(s, '333333333333333333'); const c = await new Client(s.base, victim.cookie, victim.id).connect(); clients.push(c); const found = await api(s.base, '/api/admin/users?q=333333333333333333', { cookie: sup.cookie }); expect(found.body.users.map((u: any) => u.id)).toEqual([victim.id]); const ren = await api(s.base, `/api/admin/users/${victim.id}`, { method: 'PATCH', cookie: sup.cookie, body: JSON.stringify({ nickname: '바뀐 이름' }) }); expect(ren.res.status).toBe(200); expect((await api(s.base, '/api/me', { cookie: victim.cookie })).body.me.nickname).toBe('바뀐 이름'); const ban = await api(s.base, `/api/admin/users/${victim.id}`, { method: 'PATCH', cookie: sup.cookie, body: JSON.stringify({ ban: { reason: '도배' } }) }); expect(ban.res.status).toBe(200); for (let i = 0; i < 20 && !c.closed; i++) await sleep(25); expect(c.closed?.code).toBe(4403); expect((await api(s.base, '/api/me', { cookie: victim.cookie })).body.me).toBeNull(); await expect(discordLogin(s, '333333333333333333')).rejects.toThrow('/?login=banned'); // Superadmin cannot ban themselves. const self = await api(s.base, `/api/admin/users/${sup.id}`, { method: 'PATCH', cookie: sup.cookie, body: JSON.stringify({ ban: { reason: 'x' } }) }); expect(self.res.status).toBe(400); await api(s.base, `/api/admin/users/${victim.id}`, { method: 'PATCH', cookie: sup.cookie, body: JSON.stringify({ ban: null }) }); const again = await discordLogin(s, '333333333333333333'); expect(again.id).toBe(victim.id); const actions = (await api(s.base, '/api/admin/audit', { cookie: sup.cookie })).body.entries.map((e: any) => e.action); expect(actions).toEqual(['user.unban', 'user.ban', 'user.rename']); }); test('superadmin sees when an idle guest will be deleted; none for members or guests still online', async () => { const s = start(); const sup = await discordLogin(s, SUPER); const away = await guest(s.base, '떠난손님'); const here = await guest(s.base, '있는손님'); const c = await new Client(s.base, here.cookie, here.id).connect(); clients.push(c); const seen = (s.db.query('SELECT last_seen_at AS t FROM users WHERE id = ?').get(away.id) as { t: number }).t; const list = (await api(s.base, '/api/admin/users', { cookie: sup.cookie })).body.users; const byId = (id: string) => list.find((u: any) => u.id === id); expect(byId(away.id).deleteAt).toBe(seen + GUEST_IDLE_MS); expect(byId(here.id).deleteAt).toBeNull(); expect(byId(sup.id).deleteAt).toBeNull(); expect((await api(s.base, `/api/admin/users/${away.id}`, { cookie: sup.cookie })).body.user.deleteAt).toBe(seen + GUEST_IDLE_MS); }); test('records: totals in the user list, per-game stats and recent games for superadmin; player card for logged-in users', async () => { const s = start(); const sup = await discordLogin(s, SUPER); const a = await guest(s.base, '호랑이'); const b = await guest(s.base, '고양이'); // Two finished omok games (a won one, b won one) and one draw-less yacht game for a. const games: [string, string, number, [string, number][]][] = [ ['01J00000000000000000000001', 'omok', 1, [[a.id, 1], [b.id, 2]]], ['01J00000000000000000000002', 'omok', 2, [[a.id, 2], [b.id, 1]]], ['01J00000000000000000000003', 'yacht', 3, [[a.id, 1]]], ]; for (const [id, gameId, no, players] of games) { s.db .query("INSERT INTO games (id, room_id, game_no, game_id, options_json, seed_hash, seed, started_at, ended_at, end_reason, result_json) VALUES (?, 'r', ?, ?, '{}', 'h', 's', ?, ?, 'normal', ?)") .run(id, no, gameId, 1000 * no, 1000 * no + 500, JSON.stringify({ summary: '끝' })); players.forEach(([u, rank], seat) => s.db.query('INSERT INTO game_players (game_pk, user_id, seat, rank, score) VALUES (?, ?, ?, ?, NULL)').run(id, u, seat, rank)); } s.db.query("INSERT INTO user_stats (user_id, game_id, played, wins, draws) VALUES (?, 'omok', 2, 1, 0), (?, 'yacht', 1, 1, 0), (?, 'omok', 2, 1, 0)").run(a.id, a.id, b.id); const list = (await api(s.base, '/api/admin/users', { cookie: sup.cookie })).body.users; expect(list.find((u: any) => u.id === a.id)).toMatchObject({ played: 3, wins: 2, draws: 0 }); expect(list.find((u: any) => u.id === sup.id)).toMatchObject({ played: 0, wins: 0, draws: 0 }); const detail = (await api(s.base, `/api/admin/users/${a.id}`, { cookie: sup.cookie })).body; expect(detail.stats).toEqual([ { gameId: 'omok', played: 2, wins: 1, draws: 0 }, { gameId: 'yacht', played: 1, wins: 1, draws: 0 }, ]); const recent = (await api(s.base, `/api/admin/users/${a.id}/games`, { cookie: sup.cookie })).body; expect(recent.next).toBeNull(); expect(recent.games.map((g: any) => [g.gameId, g.myRank])).toEqual([ ['yacht', 1], ['omok', 2], ['omok', 1], ]); expect(recent.games[1].players.map((p: any) => p.nickname)).toEqual(['고양이', '호랑이']); expect((await api(s.base, `/api/admin/users/${a.id}/games?before=bad`, { cookie: sup.cookie })).res.status).toBe(400); expect((await api(s.base, '/api/admin/users/nobody/games', { cookie: sup.cookie })).res.status).toBe(404); // Recent games are superadmin-only like the rest of the user pages. expect((await api(s.base, `/api/admin/users/${a.id}/games`, { cookie: b.cookie })).res.status).toBe(403); // Player card in a room: any logged-in user can read another player's record. const card = await api(s.base, `/api/users/${a.id}/stats`, { cookie: b.cookie }); expect(card.res.status).toBe(200); expect(card.body.user).toMatchObject({ id: a.id, nickname: '호랑이', kind: 'guest' }); expect(card.body.stats).toEqual(detail.stats); expect((await api(s.base, `/api/users/${a.id}/stats`)).res.status).toBe(401); expect((await api(s.base, '/api/users/nobody/stats', { cookie: b.cookie })).res.status).toBe(404); }); });