Files
game_voice_recorder/site/server/test/bot-broker.test.ts
EJClaw 1429f74074 봇 중계: 연결한 뒤 권한을 잃으면 음성 연결을 끊는다
- 음성 연결을 가진 앱과 그 채널을 기록하고, 다시 확인해서 그 유저가 더는 들어갈 수 없으면
  음성 접속 정보 전달을 멈추고, 봇을 빼고(op 4 null), 앱에 taken 을 보낸다 (revoke)
- 다시 확인하는 때: 탈퇴 · 추방 · 역할 · 채널 권한 변경 이벤트(BotSource 'access', discord.js GuildMemberRemove/Update ·
  ChannelUpdate/Delete · GuildRoleUpdate/Delete · GuildDelete), vserver/vstate 를 넘기기 직전(봇이 옮겨진 채널 기준), 30초 주기
- 서버 멤버가 아니게 되면 지켜보기도 watch_denied 로 끊는다
- 테스트 (site/server/test/bot-broker.test.ts): 허용 → 연결 → 회수(탈퇴 · 채널 권한 제거 · 이벤트 없이 바뀜 · 권한 없는 채널로 옮겨짐)
  → 전달 차단 · 봇 퇴장 · 알림. 고치기 전 코드에서는 4건 모두 실패

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 11:34:45 +09:00

186 lines
8.2 KiB
TypeScript

// 겜녹이 봇 중계: 연결한 뒤 권한을 잃으면 (탈퇴 · 채널 권한 제거) 음성 접속 정보 전달을 멈추고 봇을 빼고 앱에 알린다
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import WebSocket from 'ws';
import type { BotGwMember } from '@gvr/shared';
import { buildServer } from '../src/app.ts';
import type { BotSource } from '../src/bot-broker.ts';
import type { Config } from '../src/config.ts';
const SUPER = '293719842274541579';
const USER = '111111111111111111';
const G = '900000000000000001';
const VC1 = '910000000000000001';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-broker-'));
const mem = (id: string): BotGwMember => ({ id, name: id, avatar: null, bot: false });
/** 권한을 바꿀 수 있는 가짜 디스코드 (members: 서버 멤버, connect: VC1 에 들어갈 수 있는 사람) */
class FakeSource extends EventEmitter implements BotSource {
members_ = new Set([SUPER, USER]);
connect = new Set([SUPER, USER]);
sent: any[] = [];
handlers: { server: (d: any) => void; state: (d: any) => void } | null = null;
me() {
return { id: '800000000000000001', name: '겜녹이', avatar: null, bot: true };
}
async guildsFor(u: string) {
return this.members_.has(u) ? [{ id: G, name: 'M&L', icon: null }] : [];
}
async snapshot(g: string, u: string) {
return g === G && this.members_.has(u) ? { guild: { id: G, name: 'M&L', icon: null }, channels: [{ id: VC1, name: '일반' }], voice: [] } : null;
}
canView(g: string, u: string, ch: string) {
return g === G && ch === VC1 && this.members_.has(u);
}
canConnect(g: string, u: string, ch: string) {
return this.canView(g, u, ch) && this.connect.has(u);
}
async members() {
return [mem(SUPER), mem(USER)];
}
async registerCommands() {}
voiceAdapter(_g: string, h: { server: (d: any) => void; state: (d: any) => void }) {
this.handlers = h;
return { send: (p: any) => (this.sent.push(p), true) };
}
}
async function setup(recheckMs?: number) {
const source = new FakeSource();
const cfg: Config = {
port: 0, host: '127.0.0.1', publicUrl: 'http://127.0.0.1', clientId: 'c', clientSecret: 's', botToken: 'bot-token',
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
version: 'test', discordApi: 'http://127.0.0.1:1', assetUpstream: {},
};
const { app, store } = await buildServer(cfg, { botSource: source, botRecheckMs: recheckMs });
await app.listen({ host: '127.0.0.1', port: 0 });
const url = `ws://127.0.0.1:${(app.server.address() as any).port}/app/bot/ws`;
store.upsertAppUser({ id: USER, name: 'u', avatar: null, role: 'user', addedBy: SUPER });
/** 일반 유저 앱 하나: 받은 메시지를 모은다 */
const pc = async () => {
const ws = new WebSocket(url, { headers: { authorization: `Bearer ${store.createAppSession(USER)}` } });
const got: any[] = [];
ws.on('message', (d) => got.push(JSON.parse(String(d))));
await new Promise((r) => ws.once('open', r));
const send = (m: unknown) => ws.send(JSON.stringify(m));
return { ws, got, send };
};
return { source, pc, close: () => app.close() };
}
const until = async (cond: () => boolean, ms = 3000) => {
const end = Date.now() + ms;
while (!cond()) {
if (Date.now() > end) throw new Error('시간 초과');
await new Promise((r) => setTimeout(r, 10));
}
};
const op4 = (ch: string | null) => ({ op: 4, d: { guild_id: G, channel_id: ch, self_mute: false, self_deaf: false } });
/** 허용 → 연결: 봇을 VC1 에 부르고 음성 접속 정보를 받는 데까지 */
async function connected(s: Awaited<ReturnType<typeof setup>>) {
const p = await s.pc();
p.send({ t: 'watch', guildId: G, commands: false });
await until(() => p.got.some((m) => m.t === 'guild'));
p.send({ t: 'voice', guildId: G, payload: op4(VC1) });
await until(() => s.source.sent.length === 1);
assert.equal(s.source.sent[0].d.channel_id, VC1);
s.source.handlers!.state({ guild_id: G, channel_id: VC1, session_id: 'sess-1', user_id: '800000000000000001' });
s.source.handlers!.server({ guild_id: G, token: 'voice-token-1', endpoint: 'x' });
await until(() => p.got.filter((m) => m.t === 'vstate' || m.t === 'vserver').length === 2);
return p;
}
/** 권한 회수 뒤: 봇을 빼고(op 4 null), 앱에 taken, 음성 접속 정보는 더 가지 않는다 */
async function assertRevoked(s: Awaited<ReturnType<typeof setup>>, p: Awaited<ReturnType<typeof connected>>) {
await until(() => s.source.sent.length === 2);
assert.equal(s.source.sent[1].d.channel_id, null, '봇을 음성채널에서 뺀다');
await until(() => p.got.some((m) => m.t === 'taken' && m.guildId === G));
const before = p.got.filter((m) => m.t === 'vstate' || m.t === 'vserver').length;
s.source.handlers!.server({ guild_id: G, token: 'voice-token-2', endpoint: 'x' });
s.source.handlers!.state({ guild_id: G, channel_id: VC1, session_id: 'sess-2', user_id: '800000000000000001' });
await new Promise((r) => setTimeout(r, 150));
assert.equal(p.got.filter((m) => m.t === 'vstate' || m.t === 'vserver').length, before, '권한을 잃은 앱에 음성 접속 정보가 가면 안 된다');
assert.ok(!JSON.stringify(p.got).includes('voice-token-2'));
}
test('권한 회수 (디스코드 서버 탈퇴 · 추방): 이벤트가 오면 바로 봇을 빼고 알리고 음성 정보 전달을 멈춘다', async () => {
const s = await setup();
try {
const p = await connected(s);
s.source.members_.delete(USER);
s.source.connect.delete(USER);
s.source.emit('access', G);
await assertRevoked(s, p);
// 지켜보기도 끊긴다 (탈퇴했으니)
await until(() => p.got.some((m) => m.t === 'watch_denied' && m.guildId === G));
p.ws.close();
} finally {
await s.close();
}
});
test('권한 회수 (채널 권한 제거): 이벤트가 오면 바로 봇을 빼고 알리고 음성 정보 전달을 멈춘다', async () => {
const s = await setup();
try {
const p = await connected(s);
s.source.connect.delete(USER); // 서버 멤버는 그대로, VC1 연결 권한만 빼앗김
s.source.emit('access', G);
await assertRevoked(s, p);
assert.ok(!p.got.some((m) => m.t === 'watch_denied'), '서버 멤버이므로 지켜보기는 유지');
p.ws.close();
} finally {
await s.close();
}
});
test('권한 회수 (이벤트를 놓친 경우): 음성 정보를 넘기기 직전 검사와 주기 검사로 막는다', async () => {
// 넘기기 직전 검사
const s = await setup();
try {
const p = await connected(s);
s.source.connect.delete(USER); // 이벤트 없이 권한만 바뀜
const before = p.got.filter((m) => m.t === 'vserver').length;
s.source.handlers!.server({ guild_id: G, token: 'voice-token-x', endpoint: 'x' });
await until(() => s.source.sent.length === 2);
assert.equal(s.source.sent[1].d.channel_id, null);
await until(() => p.got.some((m) => m.t === 'taken'));
assert.equal(p.got.filter((m) => m.t === 'vserver').length, before);
p.ws.close();
} finally {
await s.close();
}
// 주기 검사 (음성 정보도 이벤트도 없을 때)
const s2 = await setup(200);
try {
const p = await connected(s2);
s2.source.members_.delete(USER);
s2.source.connect.delete(USER);
await assertRevoked(s2, p);
await until(() => p.got.some((m) => m.t === 'watch_denied'));
p.ws.close();
} finally {
await s2.close();
}
});
test('봇이 권한 없는 채널로 옮겨지면 (다른 사람이 끌어감) 그 채널 기준으로 막는다', async () => {
const s = await setup();
try {
const p = await connected(s);
const before = p.got.filter((m) => m.t === 'vstate').length;
s.source.handlers!.state({ guild_id: G, channel_id: '910000000000000099', session_id: 'sess-1', user_id: '800000000000000001' });
await until(() => s.source.sent.length === 2);
assert.equal(s.source.sent[1].d.channel_id, null);
await until(() => p.got.some((m) => m.t === 'taken'));
assert.equal(p.got.filter((m) => m.t === 'vstate').length, before);
p.ws.close();
} finally {
await s.close();
}
});