앱 v1.2.1: 겜녹이 봇 토큰을 앱에 보내지 않고 사이트 서버가 봇을 대신 연결

- 사이트 서버: discord.js 로 디스코드 게이트웨이에 한 번 붙고(discord-source.ts), 로그인한 앱에 WS /app/bot/ws 로 중계(bot-broker.ts)
  · 앱이 보낸 op 4 는 지켜보는 서버의 음성채널 참여 · 나가기만 허용하고 필드를 다시 만들어 보낸다
  · 디스코드가 준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)는 음성을 가진 앱에만 넘긴다. 음성은 앱 ↔ 디스코드로 바로
  · 한 서버의 봇 음성은 마지막으로 요청한 앱이 가져가고 이전 앱은 taken. 이전 앱의 늦은 나가기 무시, 음성 가진 앱이 끊기면 봇을 뺀다
  · 슬래시 명령은 서버가 받아 defer 후 그 서버를 지켜보는 앱으로 보낸다
  · 등록 해제 · 로그아웃하면 그 유저의 중계 연결을 바로 끊는다 (4401), 30초마다 다시 확인
- /app/me 에서 botToken 제거. 앱은 v1.2.0 이 저장해 둔 봇 토큰을 시작할 때 지운다
- 앱: BotGateway 로 디스코드 연결을 분리 (RemoteGateway = 겜녹이 봇 서버 중계, LocalGateway = 다른 봇 토큰 직접 연결)
  Bot 은 discord.js 객체 대신 이 인터페이스만 쓴다. 중계가 로그인 만료를 알리면 바로 다시 확인해서 잠근다
- 로그인 확인: 잠그라는 응답(401 · 403)은 겹친 확인 때문에 늦게 와도 같은 토큰이면 따른다
  (겹친 두 번째 확인이 401 을 받아 "등록되지 않은 아이디" 대신 "로그인 만료"로 잠기던 문제). 미등록 화면은 다시 확인해도 유지
- 테스트: 봇 중계 4건(토큰 미노출 · 음성 정보 전달 · 다른 PC 인계 · 명령 라우팅 · 해제 시 끊김), 겹친 확인 1건
  실제 디스코드: voice-e2e GVR_E2E_RELAY=1 (서버 중계로 따라 들어가 녹음 · STT · 녹음 제외), login-e2e 19/19

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 10:30:14 +09:00
parent a2487e6241
commit 6a03c67b54
27 changed files with 1786 additions and 201 deletions

View File

@@ -6,6 +6,7 @@ import fs from 'node:fs';
import path from 'node:path';
import type { Config } from './config.js';
import { registerAppAuth } from './app-auth.js';
import { BotBroker, type BotSource } from './bot-broker.js';
import { avatarUrl, DiscordApi } from './discord.js';
import { RelayHub } from './relay.js';
import { ServerStore, type Session } from './store.js';
@@ -13,14 +14,17 @@ import { ServerStore, type Session } from './store.js';
const SID = 'gvr_sid';
const RECHECK_MS = 10 * 60000;
export async function buildServer(cfg: Config) {
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
export async function buildServer(cfg: Config, opts: { botSource?: BotSource } = {}) {
const app = Fastify({ logger: { level: process.env.LOG_LEVEL || 'info' }, trustProxy: true, bodyLimit: 1024 * 1024, forceCloseConnections: true });
const store = new ServerStore(cfg.dataDir);
const hub = new RelayHub(store);
const discord = new DiscordApi(cfg);
await app.register(cookie, { secret: cfg.sessionSecret });
const secure = cfg.publicUrl.startsWith('https://');
const appAuth = registerAppAuth(app, { cfg, store, discord, secure });
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);
const allowedGuilds = (): string[] => {
const g = new Set(cfg.allowedGuilds);
@@ -197,6 +201,20 @@ export async function buildServer(cfg: Config) {
hub.deviceWss.handleUpgrade(req, socket, head, (ws) => hub.attachDevice(ws, d.id));
return;
}
if (url.pathname === '/app/bot/ws') {
if (!broker) {
socket.write('HTTP/1.1 503 Service Unavailable\r\n\r\n');
return socket.destroy();
}
const a = broker.authenticate(req);
if (!a) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
return socket.destroy();
}
const b = broker;
b.wss.handleUpgrade(req, socket, head, (ws) => b.attach(ws, a));
return;
}
if (url.pathname === '/ws') {
const fakeReq: any = { cookies: parseCookies(String(req.headers.cookie || '')), unsignCookie: (v: string) => app.unsignCookie(v), log: app.log };
const s = await getSession(fakeReq);
@@ -213,12 +231,13 @@ export async function buildServer(cfg: Config) {
// 서버를 닫기 전에 WebSocket 을 먼저 끊는다 (안 끊으면 close 가 연결이 끝나길 기다리며 멈춘다)
app.addHook('preClose', async () => {
hub.close();
broker?.close();
});
app.addHook('onClose', async () => {
store.flush();
});
return { app, store, hub };
return { app, store, hub, broker };
}
function parseCookies(h: string): Record<string, string> {