M1.5 관리자 사이트: 슈퍼어드민/어드민 권한, 게임·사이트 설정, 방·사용자 관리, 기록
- 권한: 디스코드 ID로 요청마다 계산. 슈퍼어드민 293719842274541579(SUPERADMIN_DISCORD_IDS), 어드민은 슈퍼어드민이 디스코드 ID로 추가(로그인 전 미리 등록 가능), 고정 슈퍼어드민은 삭제 불가 - 게임 설정: 사용 여부, 표시 이름·설명·안내문, 원작 범위 안 인원, 모든 규칙 옵션 기본값, 옵션별 방장 변경 금지(잠금), 초기화. 입력 화면은 옵션 스키마(zod→JSON Schema)로 자동 생성 - 오목 옵션 전체에 한국어 제목·선택지 메타, 엔진 고정값(자동 착수 허용 횟수, 무승부 재제안 간격, 한 수 제한 초)을 옵션으로 꺼냄 - 사이트 설정: 이름, 공지, 점검 모드, 금지어, 방 수 제한, 연결 유예, 채팅 기본값 - 방 관리(목록·닫기), 사용자 관리(검색·닉네임 변경·이용 제한·강제 로그아웃·삭제, 슈퍼어드민 전용), 관리자 작업 기록(전/후 값) - 이용 제한: 세션 삭제 + 접속 종료 + 디스코드 재로그인 거부 - 테스트: 관리자 API 7개(권한·설정 반영·잠금·점검·금지어·방 닫기·이용 제한·기록), 오목 옵션 2개, e2e/admin.e2e.ts(슈퍼어드민 로그인→규칙 변경·잠금→어드민 추가→게스트 새 방 반영) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
208
apps/server/src/admin.test.ts
Normal file
208
apps/server/src/admin.test.ts
Normal file
@@ -0,0 +1,208 @@
|
||||
/** Admin site tests (docs/14-admin.md §9). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Client, api, boot, guest, sleep } from './test-utils';
|
||||
|
||||
const SUPER = '293719842274541579';
|
||||
type Booted = ReturnType<typeof boot>;
|
||||
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');
|
||||
});
|
||||
|
||||
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, 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('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']);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user