Files
game_voice_recorder/app/test/bot-gateway.test.ts
EJClaw db2f1866e4 v1.3.4: 슬래시 명령 무응답 고침 · 녹음 중 봇 상태 메시지
- 원인: 그 서버를 지켜보는 앱이 없으면 discord-source 가 명령을 그냥 무시 → 디스코드 "애플리케이션이 응답하지 않았어요"
  → 1.5초 기다린 뒤(옛 v1.1.0 PC 가 먼저 받았으면 '이미 응답함'으로 빠짐) 이유를 답한다:
    앱 없음 / 내 앱이 다른 서버를 녹음 대상으로 정함 / 내 앱이 아직 연결 중. 서버 로그에 남김
- 앱: 지켜보던 중 권한 재확인으로 watch_denied 를 받으면 1분 뒤 다시 지켜보기 요청 (명령 · 음성 상태가 영영 끊기지 않게)
- 상태 메시지: 봇이 어느 서버에서든 음성채널에 있으면 dnd + "🔴 녹음 중", 아니면 online + "🎙️ 대기 중 · /녹음시작"
  (겜녹이 봇은 사이트 서버, 다른 봇 모드는 LocalGateway). 테스트 봇으로 실제 디스코드가 형식을 받는 것 확인
- 테스트: 앱 41 · 서버 16 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 02:58:26 +09:00

414 lines
21 KiB
TypeScript

// 겜녹이 봇 중계: 앱 RemoteGateway ↔ 실제 사이트 서버 코드(BotBroker). 디스코드 게이트웨이만 가짜(FakeSource).
// 핵심: 봇 토큰은 서버 밖으로 나가지 않고, 앱은 지켜보는 서버의 음성 참여 · 나가기만 요청할 수 있다
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import type { BotGwChannel, BotGwGuild, BotGwMember } from '@gvr/shared';
import { buildServer } from '../../site/server/src/app.ts';
import type { BotCommand, BotSource } from '../../site/server/src/bot-broker.ts';
import { AppAuth } from '../src/core/auth.ts';
import { RemoteGateway } from '../src/core/discord/gateway.ts';
import { SettingsStore } from '../src/core/settings.ts';
const SUPER = '1352267557213573160';
const FRIEND = '111111111111111111';
const BOT = 'MTExMTExMTExMTExMTExMTEx.FAKE00.server-only-bot-token-xxxxxxxxx';
const G = '900000000000000001';
const OTHER_G = '900000000000000002';
const VC1 = '910000000000000001';
const VC2 = '910000000000000002';
const TEXT = '910000000000000009';
/** 최고 관리자만 볼 수 있는 비공개 음성채널 */
const PRIV = '910000000000000003';
/** 모두 볼 수 있지만 최고 관리자만 들어갈 수 있는 음성채널 */
const LOCKED = '910000000000000004';
const OTHER_VC = '920000000000000001';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-botgw-'));
delete process.env.GVR_BOT_TOKEN;
const m = (id: string, name: string, bot = false): BotGwMember => ({ id, name, avatar: null, bot });
const ME = m('800000000000000001', '겜녹이', true);
class FakeSource extends EventEmitter implements BotSource {
sent: { guildId: string; payload: any }[] = [];
handlers = new Map<string, { server: (d: any) => void; state: (d: any) => void }>();
commands: string[] = [];
wants?: (guildId: string) => boolean;
me() {
return ME;
}
private all: BotGwGuild[] = [
{ id: G, name: 'M&L', icon: null },
{ id: OTHER_G, name: '다른 서버', icon: null },
];
/** 서버별 멤버: 친구는 M&L 에만 가입 */
private memberOf: Record<string, string[]> = { [G]: [SUPER, FRIEND], [OTHER_G]: [SUPER] };
private channels: Record<string, { id: string; name: string; voice: boolean; view: string[]; connect: string[] }[]> = {
[G]: [
{ id: VC1, name: '일반', voice: true, view: [SUPER, FRIEND], connect: [SUPER, FRIEND] },
{ id: VC2, name: '게임', voice: true, view: [SUPER, FRIEND], connect: [SUPER, FRIEND] },
{ id: PRIV, name: '운영진', voice: true, view: [SUPER], connect: [SUPER] },
{ id: LOCKED, name: '방송', voice: true, view: [SUPER, FRIEND], connect: [SUPER] },
{ id: TEXT, name: '채팅', voice: false, view: [SUPER, FRIEND], connect: [] },
],
[OTHER_G]: [{ id: OTHER_VC, name: '다른 음성', voice: true, view: [SUPER], connect: [SUPER] }],
};
/** 지금 음성채널에 있는 사람 */
voice: { member: BotGwMember; channelId: string; guildId: string }[] = [
{ member: m(SUPER, '관리자'), channelId: VC1, guildId: G },
{ member: m('300000000000000001', '운영진'), channelId: PRIV, guildId: G },
];
private ch(g: string, c: string) {
return this.channels[g]?.find((x) => x.id === c);
}
async guildsFor(userId: string) {
return this.all.filter((g) => this.memberOf[g.id]?.includes(userId));
}
async snapshot(guildId: string, userId: string) {
const g = this.all.find((x) => x.id === guildId);
if (!g || !this.memberOf[guildId]?.includes(userId)) return null;
const channels: BotGwChannel[] = this.channels[guildId]!.filter((c) => c.voice && c.view.includes(userId)).map((c) => ({ id: c.id, name: c.name }));
return { guild: g, channels, voice: this.voice.filter((v) => v.guildId === guildId && channels.some((c) => c.id === v.channelId)).map(({ member, channelId }) => ({ member, channelId })) };
}
canView(guildId: string, userId: string, channelId: string) {
return !!this.ch(guildId, channelId)?.view.includes(userId);
}
canConnect(guildId: string, userId: string, channelId: string) {
const c = this.ch(guildId, channelId);
return !!c?.voice && c.view.includes(userId) && c.connect.includes(userId);
}
async members(guildId: string, userId: string) {
if (!this.memberOf[guildId]?.includes(userId)) throw new Error('forbidden');
return [m(SUPER, '관리자'), m(FRIEND, '친구'), m('700000000000000001', '음악봇', true)];
}
async registerCommands(guildId: string) {
this.commands.push(guildId);
}
voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }) {
this.handlers.set(guildId, handlers);
return {
send: (payload: any) => {
this.sent.push({ guildId, payload });
return true;
},
};
}
}
async function fakeDiscord() {
const names: Record<string, string> = { [SUPER]: '관리자', [FRIEND]: '친구' };
const srv = http.createServer((req, res) => {
const u = new URL(req.url!, 'http://x');
res.setHeader('content-type', 'application/json');
if (u.pathname === '/oauth2/token') {
let b = '';
req.on('data', (c) => (b += c));
req.on('end', () => res.end(JSON.stringify({ access_token: new URLSearchParams(b).get('code') })));
return;
}
if (u.pathname === '/users/@me') {
const id = String(req.headers.authorization).replace('Bearer ', '');
return res.end(JSON.stringify({ id, username: names[id], global_name: names[id], avatar: null }));
}
const mm = /^\/users\/(\d+)$/.exec(u.pathname);
if (mm && names[mm[1]!]) return res.end(JSON.stringify({ id: mm[1], username: names[mm[1]!], global_name: names[mm[1]!], avatar: null }));
res.statusCode = 404;
res.end('{}');
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
}
async function stack() {
const dc = await fakeDiscord();
const source = new FakeSource();
const { app } = await buildServer(
{
port: 0, host: '127.0.0.1', publicUrl: 'http://placeholder', clientId: 'cid', clientSecret: 's', botToken: BOT,
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
version: 'test', discordApi: dc.url, assetUpstream: {},
},
{ botSource: source },
);
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
const browser = (who: string) => async (url: string) => {
const start = await fetch(url.replace('http://placeholder', base), { redirect: 'manual' });
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
const cookie = start.headers.getSetCookie()[0]!.split(';')[0]!;
await fetch(`${base}/auth/discord/callback?code=${who}&state=${encodeURIComponent(state)}`, { headers: { cookie }, redirect: 'manual' });
};
/** 로그인한 앱 하나 (설정 · 로그인 · 봇 중계) */
const pc = async (who: string) => {
const st = new SettingsStore(tmp());
st.update({ site: { serverUrl: base } });
const auth = new AppAuth(st, { version: 't', openUrl: browser(who), pollMs: 20 });
assert.equal((await auth.login()).status, 'ok');
const gw = new RemoteGateway({ serverUrl: () => base, appToken: () => st.getSecret('appToken') ?? null, version: 't' });
// 서버가 앱에 보낸 모든 메시지 (봇 토큰이 섞여 있지 않은지 본다)
const seen: string[] = [];
const orig = (gw as any).onMessage.bind(gw);
(gw as any).onMessage = (msg: any) => (seen.push(JSON.stringify(msg)), orig(msg));
return { st, auth, gw, seen };
};
return { base, source, pc, close: async () => (await app.close(), dc.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 = (guildId: string, channelId: string | null) => ({ op: 4, d: { guild_id: guildId, channel_id: channelId, self_mute: false, self_deaf: false } });
test('봇 중계: 로그인 안 한 연결은 막히고, 로그인한 앱은 봇 토큰 없이 서버 정보 · 음성 상태를 받는다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
try {
// 앱 토큰이 틀리면 401 → unauthorized
const bad = new RemoteGateway({ serverUrl: () => s.base, appToken: () => 'wrong-token', version: 't' });
await assert.rejects(bad.start(), /로그인/);
await bad.stop();
await a.gw.start();
assert.deepEqual(a.gw.me(), ME);
assert.deepEqual(a.gw.guilds().map((g) => g.id), [G, OTHER_G]);
// 지켜보기 전에도 (설정 창이 봇 연결 직후 바로 요청) 가입한 서버 멤버 목록을 받는다
assert.equal((await a.gw.members(G)).length, 3);
const g = await a.gw.watch(G, { commands: true });
assert.equal(g?.name, 'M&L');
await until(() => s.source.commands.includes(G));
assert.deepEqual(a.gw.voiceChannelOf(G, SUPER), { id: VC1, name: '일반' });
assert.deepEqual(a.gw.channelMembers(G, VC1).map((x) => x.id), [SUPER]);
// 음성 상태 변화가 넘어온다
const evs: any[] = [];
a.gw.on('voiceState', (e) => evs.push(e));
s.source.emit('voiceState', { guildId: G, member: m(FRIEND, '친구'), oldChannelId: null, newChannelId: VC2, channel: { id: VC2, name: '게임' } });
s.source.emit('voiceState', { guildId: OTHER_G, member: m(FRIEND, '친구'), oldChannelId: null, newChannelId: '1', channel: null }); // 지켜보지 않는 서버
await until(() => evs.length === 1);
assert.deepEqual(a.gw.voiceChannelOf(G, FRIEND), { id: VC2, name: '게임' });
// 멤버 목록 (봇 판별)
const ms = await a.gw.members(G);
assert.equal(ms.length, 3);
assert.equal(a.gw.isBot('700000000000000001'), true);
assert.equal(a.gw.isBot(FRIEND), false);
assert.ok(a.seen.length > 3);
assert.ok(!a.seen.some((x) => x.includes(BOT)), '봇 토큰이 앱으로 가면 안 된다');
} finally {
await a.gw.stop();
await s.close();
}
});
test('봇 중계: 음성 참여는 서버가 대신 보내고 일회용 음성 접속 정보만 그 앱에 넘긴다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
try {
await a.gw.start();
await a.gw.watch(G, { commands: false });
const got: any[] = [];
const adapter = a.gw.adapterCreator(G)({
onVoiceServerUpdate: (d) => got.push(['server', d]),
onVoiceStateUpdate: (d) => got.push(['state', d]),
destroy: () => got.push(['destroy']),
});
// 지켜보지 않는 서버 · 음성채널이 아닌 곳 · op 4 가 아닌 것은 서버가 버린다
a.gw.adapterCreator(OTHER_G)({ onVoiceServerUpdate: () => undefined, onVoiceStateUpdate: () => undefined, destroy: () => undefined }).sendPayload(op4(OTHER_G, '1'));
adapter.sendPayload(op4(G, TEXT));
adapter.sendPayload({ op: 2, d: { token: 'x' } });
adapter.sendPayload({ op: 4, d: { guild_id: OTHER_G, channel_id: VC1 } });
// 정상 참여
assert.equal(adapter.sendPayload({ op: 4, d: { guild_id: G, channel_id: VC1, self_mute: false, self_deaf: false, extra: 'x' } }), true);
await until(() => s.source.sent.length === 1);
assert.deepEqual(s.source.sent[0], { guildId: G, payload: op4(G, VC1) }, '검사한 필드만 다시 만들어 보낸다');
// 디스코드가 준 음성 접속 정보 → 앱의 @discordjs/voice 로
s.source.handlers.get(G)!.state({ guild_id: G, user_id: ME.id, session_id: 'sess-1', channel_id: VC1 });
s.source.handlers.get(G)!.server({ guild_id: G, token: 'one-time-voice-token', endpoint: 'voice.example:443' });
await until(() => got.length === 2);
assert.equal(got[0][0], 'state');
assert.equal(got[0][1].session_id, 'sess-1');
assert.equal(got[1][1].token, 'one-time-voice-token');
// 나가기
adapter.sendPayload(op4(G, null));
await until(() => s.source.sent.length === 2);
assert.equal(s.source.sent[1]!.payload.d.channel_id, null);
assert.ok(!a.seen.some((x) => x.includes(BOT)));
} finally {
await a.gw.stop();
await s.close();
}
});
test('봇 중계: 다른 PC 가 봇을 데려가면 이전 PC 는 taken 을 받고, 이전 PC 가 봇을 빼거나 음성 정보를 받지 못한다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
const admin = new AppAuth(a.st, { version: 't', openUrl: () => undefined });
await admin.adminAddUser(FRIEND, 'user');
const b = await s.pc(FRIEND);
try {
await a.gw.start();
await b.gw.start();
await a.gw.watch(G, { commands: false });
await b.gw.watch(G, { commands: false });
const aGot: any[] = [];
const bGot: any[] = [];
const aAd = a.gw.adapterCreator(G)({ onVoiceServerUpdate: (d) => aGot.push(d), onVoiceStateUpdate: (d) => aGot.push(d), destroy: () => undefined });
const bAd = b.gw.adapterCreator(G)({ onVoiceServerUpdate: (d) => bGot.push(d), onVoiceStateUpdate: (d) => bGot.push(d), destroy: () => undefined });
const taken: string[] = [];
a.gw.on('taken', (g) => taken.push(g));
aAd.sendPayload(op4(G, VC1));
await until(() => s.source.sent.length === 1);
bAd.sendPayload(op4(G, VC2));
await until(() => taken.length === 1 && s.source.sent.length === 2);
assert.equal(taken[0], G);
// 이제 음성 접속 정보는 B 에게만
s.source.handlers.get(G)!.server({ guild_id: G, token: 'for-b' });
await until(() => bGot.length === 1);
assert.equal(aGot.length, 0);
// A 가 늦게 나가기를 보내도 B 의 봇을 빼지 않는다
aAd.sendPayload(op4(G, null));
await new Promise((r) => setTimeout(r, 100));
assert.equal(s.source.sent.length, 2);
// B 앱이 꺼지면 서버가 봇을 음성채널에서 뺀다
await b.gw.stop();
await until(() => s.source.sent.length === 3);
assert.equal(s.source.sent[2]!.payload.d.channel_id, null);
} finally {
await a.gw.stop();
await b.gw.stop();
await s.close();
}
});
test('봇 중계: 슬래시 명령은 그 서버를 지켜보는 앱으로 가고 앱의 답이 돌아간다. 등록 해제하면 바로 끊긴다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
const admin = new AppAuth(a.st, { version: 't', openUrl: () => undefined });
await admin.adminAddUser(FRIEND, 'user');
const b = await s.pc(FRIEND);
const cmd = (name: string, user: string) =>
new Promise<string>((resolve) => s.source.emit('command', { name, guildId: G, user: m(user, user), voiceChannel: { id: VC1, name: '일반' } } satisfies BotCommand, resolve));
try {
assert.match(await cmd('녹음시작', SUPER), /^지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다/);
// 지켜보는 앱이 없는 서버의 명령은 서버가 잠깐 기다렸다가 받는다 (봇 토큰을 직접 쓰는 v1.1.0 PC 가 먼저 응답하게)
assert.equal(s.source.wants?.(G), false);
await a.gw.start();
await b.gw.start();
// 내 앱이 켜져 있어도 다른 서버를 녹음 대상으로 정해 두면 그렇다고 알려 준다 ("응답하지 않았어요" 대신)
assert.match(await cmd('녹음시작', SUPER), /^내 겜녹이 앱이 이 서버에 아직 연결되지 않았습니다/);
await a.gw.watch(OTHER_G, { commands: false });
assert.match(await cmd('녹음시작', SUPER), /^내 겜녹이 앱이 다른 디스코드 서버를 녹음 대상으로 정해 두었습니다/);
await a.gw.watch(G, { commands: false });
assert.equal(s.source.wants?.(G), true);
assert.equal(s.source.wants?.(OTHER_G), false);
await b.gw.watch(G, { commands: false });
const seenBy: string[] = [];
a.gw.on('command', (c, respond) => (seenBy.push(`a:${c.name}`), respond(`A 가 ${c.name}`)));
b.gw.on('command', (c, respond) => (seenBy.push(`b:${c.name}`), respond(`B 가 ${c.name}`)));
// 명령한 사람의 PC 로
assert.equal(await cmd('녹음시작', FRIEND), 'B 가 녹음시작');
assert.equal(await cmd('녹음시작', SUPER), 'A 가 녹음시작');
// 녹음 중인 PC 가 없으면 종료할 것이 없다
assert.equal(await cmd('녹음종료', SUPER), '지금은 녹음 중이 아닙니다.');
// 녹음제외는 모든 PC 기록에 남긴다
await cmd('녹음제외', FRIEND);
await until(() => seenBy.includes('a:녹음제외') && seenBy.includes('b:녹음제외'));
// 등록 해제 → B 의 중계 연결이 바로 끊기고 unauthorized
let unauth = false;
b.gw.on('unauthorized', () => (unauth = true));
await admin.adminRemoveUser(FRIEND);
await until(() => unauth);
assert.equal(b.gw.me(), null);
// 로그아웃 → A 도 끊긴다
let aUnauth = false;
a.gw.on('unauthorized', () => (aUnauth = true));
await a.auth.logout();
await until(() => aUnauth);
} finally {
await a.gw.stop();
await b.gw.stop();
await s.close();
}
});
test('봇 중계 권한: 일반 유저는 가입한 서버 · 볼 수 있는 채널만 보이고, 들어갈 수 있는 음성채널에만 봇을 부른다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
const admin = new AppAuth(a.st, { version: 't', openUrl: () => undefined });
await admin.adminAddUser(FRIEND, 'user');
const b = await s.pc(FRIEND);
try {
await b.gw.start();
// 서버 목록: 가입한 M&L 만
assert.deepEqual(b.gw.guilds().map((g) => g.id), [G]);
// 가입하지 않은 서버는 지켜볼 수 없다 (바로 거절)
const t0 = Date.now();
assert.equal(await b.gw.watch(OTHER_G, { commands: true }), null);
assert.ok(Date.now() - t0 < 3000, '거절은 바로 온다');
assert.ok(!s.source.commands.includes(OTHER_G), '가입하지 않은 서버에 명령을 등록하지 않는다');
await assert.rejects(b.gw.members(OTHER_G), /forbidden/);
// M&L: 비공개 채널과 그 안의 사람은 안 보인다
assert.ok(await b.gw.watch(G, { commands: false }));
assert.deepEqual((b.gw as any).channels && [...(b.gw as any).channels.keys()].sort(), [VC1, VC2, LOCKED].sort());
assert.equal(b.gw.voiceChannelOf(G, '300000000000000001'), null);
assert.equal(b.gw.channel(G, PRIV), null);
// 비공개 채널 안의 움직임은 안 오고, 비공개 채널로 옮기면 "나감"으로만 보인다
const evs: any[] = [];
b.gw.on('voiceState', (e) => evs.push(e));
s.source.emit('voiceState', { guildId: G, member: m('300000000000000002', '운영진2'), oldChannelId: null, newChannelId: PRIV, channel: { id: PRIV, name: '운영진' } });
s.source.emit('voiceState', { guildId: G, member: m(SUPER, '관리자'), oldChannelId: VC1, newChannelId: PRIV, channel: { id: PRIV, name: '운영진' } });
await until(() => evs.length === 1);
await new Promise((r) => setTimeout(r, 100));
assert.equal(evs.length, 1);
assert.deepEqual([evs[0].member.id, evs[0].oldChannelId, evs[0].newChannelId, evs[0].channel], [SUPER, VC1, null, null]);
// 음성 참여: 비공개 · 연결 권한 없는 채널 · 다른 서버는 거절, 들어갈 수 있는 채널만
const ad = b.gw.adapterCreator(G)({ onVoiceServerUpdate: () => undefined, onVoiceStateUpdate: () => undefined, destroy: () => undefined });
ad.sendPayload(op4(G, PRIV));
ad.sendPayload(op4(G, LOCKED));
ad.sendPayload(op4(G, OTHER_VC));
ad.sendPayload(op4(G, VC2));
await until(() => s.source.sent.length === 1);
await new Promise((r) => setTimeout(r, 100));
assert.deepEqual(s.source.sent.map((x) => x.payload.d.channel_id), [VC2]);
// 슬래시 명령: 최고 관리자가 비공개 채널에서 /녹음시작 → 그 채널에 못 들어가는 친구 PC 로는 보내지 않는다
const cmds: any[] = [];
b.gw.on('command', (c, respond) => (cmds.push(c), respond('ok')));
const cmd = (name: string) =>
new Promise<string>((resolve) => s.source.emit('command', { name, guildId: G, user: m(SUPER, '관리자'), voiceChannel: { id: PRIV, name: '운영진' } } satisfies BotCommand, resolve));
assert.equal(await cmd('녹음시작'), '이 음성채널에 들어갈 수 있는 겜녹이 앱이 없습니다.');
// /녹음제외 는 친구 PC 기록에도 남기되 비공개 채널 이름은 보내지 않는다
assert.equal(await cmd('녹음제외'), 'ok');
assert.equal(cmds.length, 1);
assert.equal(cmds[0].voiceChannel, null);
// 친구 PC 가 받은 메시지 어디에도 비공개 채널 · 그 안의 사람 정보가 없다
const all = b.seen.join('\n');
// (OTHER_G 는 친구가 직접 보낸 watch 의 거절 응답에만 나온다)
for (const secret of [PRIV, '운영진', '300000000000000001', '300000000000000002', '다른 서버', OTHER_VC]) assert.ok(!all.includes(secret), secret);
} finally {
await a.gw.stop();
await b.gw.stop();
await s.close();
}
});