봇 중계: 연결한 뒤 권한을 잃으면 음성 연결을 끊는다

- 음성 연결을 가진 앱과 그 채널을 기록하고, 다시 확인해서 그 유저가 더는 들어갈 수 없으면
  음성 접속 정보 전달을 멈추고, 봇을 빼고(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>
This commit is contained in:
EJClaw
2026-10-15 11:34:45 +09:00
parent 6721db23ac
commit 1429f74074
5 changed files with 261 additions and 17 deletions

View File

@@ -16,7 +16,7 @@ const SID = 'gvr_sid';
const RECHECK_MS = 10 * 60000;
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
export async function buildServer(cfg: Config, opts: { botSource?: BotSource } = {}) {
export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number } = {}) {
const app = Fastify({
logger: {
level: process.env.LOG_LEVEL || 'info',
@@ -34,7 +34,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource } =
const secure = cfg.publicUrl.startsWith('https://');
let broker: BotBroker | null = null;
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log);
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log, opts.botRecheckMs);
// 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시)
// CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게)

View File

@@ -32,7 +32,8 @@ export interface BotSnapshot {
/**
* 디스코드 게이트웨이 쪽 (실서버: discord-source.ts 의 discord.js, 테스트: 가짜).
* 이벤트: 'ready', 'guilds', 'voiceState' (BotVoiceEvent), 'command' (BotCommand, respond(content))
* 이벤트: 'ready', 'guilds', 'voiceState' (BotVoiceEvent), 'command' (BotCommand, respond(content)),
* 'access' (guildId: 그 서버의 멤버 탈퇴 · 추방 · 역할 · 채널 권한이 바뀜 → 권한을 다시 확인한다)
* 권한은 앱 유저(디스코드 아이디) 기준: 그 유저가 가입한 서버, 그 유저가 볼 수 있는 채널만
*/
export interface BotSource extends EventEmitter {
@@ -69,8 +70,8 @@ const SNOWFLAKE = /^\d{17,20}$/;
export class BotBroker {
readonly wss = new WebSocketServer({ noServer: true, maxPayload: 256 * 1024 });
private conns = new Set<Conn>();
/** 서버별로 지금 봇 음성 연결을 가진 앱 */
private owners = new Map<string, Conn>();
/** 서버별로 지금 봇 음성 연결을 가진 앱과 그 앱이 봇을 부른 음성채널 */
private owners = new Map<string, { conn: Conn; channelId: string }>();
private adapters = new Map<string, { send: (payload: any) => boolean }>();
private commandsDone = new Set<string>();
private cmds = new Map<string, (content: string | null) => void>();
@@ -81,7 +82,11 @@ export class BotBroker {
/** 앱 토큰 확인 (등록 해제 · 로그아웃이면 null) */
private verify: (token: string) => { userId: string; role: AppRole } | null,
private log: { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void },
/** 권한 · 등록 다시 확인 주기 (이벤트를 놓쳐도 이 안에 막힌다) */
recheckMs = 30000,
) {
// 디스코드 서버 탈퇴 · 추방 · 역할 · 채널 권한 변경 → 그 서버의 음성 연결 · 지켜보기 권한을 바로 다시 확인
source.on('access', (guildId: string) => this.recheck(guildId));
source.on('ready', () => {
for (const c of this.conns) void this.sendReady(c);
});
@@ -102,10 +107,12 @@ export class BotBroker {
source.wants = (guildId) => [...this.conns].some((c) => c.guildId === guildId);
source.on('command', (cmd: BotCommand, respond: (content: string) => void) => void this.onCommand(cmd).then(respond));
// 등록 해제 · 로그아웃된 연결은 30초 안에 끊는다 (해제 · 로그아웃 API 는 kick 으로 바로 끊는다)
// 서버 · 채널 권한도 다시 확인한다 (권한 변경 이벤트를 놓친 경우)
this.timer = setInterval(() => {
for (const c of this.conns) if (!this.verify(c.token)) c.ws.close(4401, 'unauthorized');
for (const c of this.conns) if (c.ws.readyState === WebSocket.OPEN) c.ws.ping();
}, 30000);
for (const g of new Set([...this.owners.keys(), ...[...this.conns].map((c) => c.guildId).filter((x): x is string => !!x)])) this.recheck(g);
}, recheckMs);
}
close(): void {
@@ -152,13 +159,53 @@ export class BotBroker {
if (!this.conns.delete(c)) return;
this.log.info({ user: c.userId, conn: c.id }, '겜녹이 봇 중계 끊김');
// 앱이 꺼지거나 끊기면 봇을 음성채널에서 뺀다 (서버 연결은 계속 살아 있어서 그냥 두면 계속 남는다)
for (const [g, o] of this.owners) {
if (o !== c) continue;
this.owners.delete(g);
this.adapters.get(g)?.send({ op: 4, d: { guild_id: g, channel_id: null, self_mute: false, self_deaf: false } });
for (const [g, o] of this.owners) if (o.conn === c) this.release(g);
}
/** 봇을 그 서버의 음성채널에서 뺀다 */
private release(guildId: string): void {
this.owners.delete(guildId);
this.adapters.get(guildId)?.send({ op: 4, d: { guild_id: guildId, channel_id: null, self_mute: false, self_deaf: false } });
}
/** 권한을 잃은 앱의 음성 연결을 끊는다: 음성 접속 정보 전달을 멈추고, 봇을 빼고, 앱에는 taken 으로 알려 녹음을 멈추게 한다 */
private revoke(guildId: string, why: string): void {
const o = this.owners.get(guildId);
if (!o) return;
this.log.info({ user: o.conn.userId, guild: guildId, why }, '권한이 없어져 겜녹이 봇 음성 연결을 끊음');
this.release(guildId);
this.send(o.conn, { t: 'taken', guildId });
}
/** 그 서버의 권한을 다시 확인한다 (음성 연결: 들어갈 수 있는 채널인지, 지켜보기: 아직 멤버인지) */
private recheck(guildId: string): void {
const o = this.owners.get(guildId);
if (o && !this.source.canConnect(guildId, o.conn.userId, o.channelId)) this.revoke(guildId, 'access-changed');
for (const c of this.conns) {
if (c.guildId !== guildId) continue;
void this.source.snapshot(guildId, c.userId).then(
(snap) => {
if (snap || c.guildId !== guildId) return;
c.guildId = null;
this.send(c, { t: 'watch_denied', guildId });
},
() => undefined,
);
}
}
/** 음성 접속 정보를 넘겨도 되는지 (봇이 있는 채널에 그 앱의 유저가 지금도 들어갈 수 있는지) */
private owned(guildId: string, channelId?: string | null): Conn | null {
const o = this.owners.get(guildId);
if (!o) return null;
if (channelId) o.channelId = String(channelId); // 봇이 다른 채널로 옮겨진 경우 그 채널 기준으로
if (!this.source.canConnect(guildId, o.conn.userId, o.channelId)) {
this.revoke(guildId, 'forward-check');
return null;
}
return o.conn;
}
private async sendReady(c: Conn): Promise<void> {
const me = this.source.me();
if (!me) return;
@@ -174,12 +221,13 @@ export class BotBroker {
let a = this.adapters.get(guildId);
if (!a) {
a = this.source.voiceAdapter(guildId, {
// 넘기기 전에 매번 권한을 확인한다
server: (d) => {
const o = this.owners.get(guildId);
const o = this.owned(guildId);
if (o) this.send(o, { t: 'vserver', guildId, data: d });
},
state: (d) => {
const o = this.owners.get(guildId);
const o = this.owned(guildId, d?.channel_id);
if (o) this.send(o, { t: 'vstate', guildId, data: d });
},
});
@@ -202,14 +250,14 @@ export class BotBroker {
const ch = d.channel_id === null ? null : String(d.channel_id);
// 이 유저가 직접 들어갈 수 있는 음성채널에만 봇을 부른다 (비공개 채널 · 권한 없는 채널 거절)
if (ch !== null && !this.source.canConnect(g, c.userId, ch)) return;
const owner = this.owners.get(g);
const owner = this.owners.get(g)?.conn;
if (ch === null) {
// 이미 다른 PC 가 가져간 봇을 이전 PC 가 빼지 못하게
if (owner !== c) return;
this.owners.delete(g);
} else if (owner !== c) {
if (owner) this.send(owner, { t: 'taken', guildId: g });
this.owners.set(g, c);
} else {
if (owner && owner !== c) this.send(owner, { t: 'taken', guildId: g });
this.owners.set(g, { conn: c, channelId: ch });
}
this.adapter(g).send({ op: 4, d: { guild_id: g, channel_id: ch, self_mute: !!d.self_mute, self_deaf: !!d.self_deaf } });
return;
@@ -254,7 +302,7 @@ export class BotBroker {
private async onCommand(cmd: BotCommand): Promise<string> {
const here = [...this.conns].filter((c) => c.guildId === cmd.guildId).sort((a, b) => b.at - a.at);
if (!here.length) return '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다.';
const owner = this.owners.get(cmd.guildId);
const owner = this.owners.get(cmd.guildId)?.conn;
const mine = here.find((c) => c.userId === cmd.user.id);
let targets: Conn[];
if (cmd.name === '녹음제외' || cmd.name === '녹음참여') targets = here; // 각 PC 기록에 모두 남긴다

View File

@@ -29,6 +29,15 @@ export class DiscordSource extends EventEmitter implements BotSource {
this.emit('ready');
});
c.on(Events.GuildCreate, () => this.emit('guilds'));
// 권한이 바뀔 수 있는 일: 탈퇴 · 추방, 역할 변경, 채널 권한 변경 · 삭제, 역할 권한 변경 · 삭제 → 중계가 다시 확인한다
const access = (guildId: string | null | undefined) => guildId && this.emit('access', guildId);
c.on(Events.GuildMemberRemove, (m) => access(m.guild.id));
c.on(Events.GuildMemberUpdate, (_o, n) => access(n.guild.id));
c.on(Events.ChannelUpdate, (_o, n) => access('guildId' in n ? n.guildId : null));
c.on(Events.ChannelDelete, (ch) => access('guildId' in ch ? ch.guildId : null));
c.on(Events.GuildRoleUpdate, (_o, n) => access(n.guild.id));
c.on(Events.GuildRoleDelete, (r) => access(r.guild.id));
c.on(Events.GuildDelete, (g) => access(g.id));
c.on(Events.GuildDelete, () => this.emit('guilds'));
c.on(Events.Error, (e) => log.error(e, '디스코드 오류'));
c.on(Events.VoiceStateUpdate, (o, n) => {