앱 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:
@@ -20,9 +20,11 @@
|
||||
|
||||
## 디스코드 봇
|
||||
|
||||
- 기본은 **겜녹이 봇으로 진행**: 로그인하면 사이트 서버가 겜녹이 봇 토큰을 내려주므로(암호화 저장) 토큰을 넣지 않아도 바로 연결된다.
|
||||
- 기본은 **겜녹이 봇으로 진행**: 토큰을 넣지 않아도 로그인만 하면 바로 연결된다. 봇은 사이트 서버가 디스코드에 연결하고, 앱은 로그인 토큰으로 서버 중계(`/app/bot/ws`)를 받는다.
|
||||
- **다른 봇으로 진행하기**(관리자만)를 고르면 직접 만든 봇 토큰을 넣는다 (암호화 저장). v1.0.0 에서 토큰을 넣어 쓰던 설치는 다른 봇 모드로 그대로 이어진다.
|
||||
- v1.2.0 부터 **exe 안에 봇 토큰이 없다** (v1.1.0 은 빌드 때 감춰 넣었다). 등록되지 않은 사람은 exe 를 받아도 겜녹이 봇을 쓸 수 없고, 등록이 해제되면 받아 둔 토큰도 지운다. 빌드에 비밀값이 필요 없어 공개 릴리스에 올려도 된다.
|
||||
- v1.2.1 부터 **겜녹이 봇 토큰은 사이트 서버 밖으로 나가지 않는다** (v1.1.0 은 exe 에 감춰 넣었고, v1.2.0 은 로그인한 유저에게 내려줬다). 등록된 유저의 PC 에도 토큰이 없어서 PC 를 뒤지거나 통신을 가로채도 꺼낼 수 없다.
|
||||
음성채널에 들어갈 때 서버가 디스코드에서 받은 일회용 음성 접속 정보만 그 PC 에 넘기고, 음성은 PC ↔ 디스코드로 바로 간다. 사이트 서버가 꺼져 있으면 겜녹이 봇은 쓸 수 없다 (다른 봇 모드는 상관없음). 구조: [`docs/dev/ARCHITECTURE.md` 8장](docs/dev/ARCHITECTURE.md)
|
||||
- 빌드에 비밀값이 필요 없어 공개 릴리스에 올려도 된다. 등록되지 않은 사람은 exe 를 받아도 겜녹이 봇을 쓸 수 없다.
|
||||
|
||||
## 진행 현황
|
||||
|
||||
|
||||
4
app/package-lock.json
generated
4
app/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gvr-app",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@discordjs/voice": "^0.19.2",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"productName": "겜녹이",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
||||
"private": true,
|
||||
"main": "dist/main.cjs",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// 로그인 E2E (리눅스 · Xvfb): 실제 Electron 앱 + 이 저장소의 사이트 서버 코드 + 가짜 디스코드 OAuth.
|
||||
// 겜녹이 봇 토큰은 서버에서만 받으므로, 로그인 후 봇이 실제로 디스코드에 붙는지까지 본다.
|
||||
// 겜녹이 봇 토큰은 서버에만 있다. 서버가 디스코드에 붙고, 로그인한 앱이 서버 중계(/app/bot/ws)로 봇을 쓰는지까지 본다.
|
||||
// GVR_E2E_BOT_TOKEN=<겜녹이 봇 토큰> node --import tsx scripts/login-e2e.mts [스크린샷 폴더]
|
||||
// (먼저 npm run build)
|
||||
import { spawn } from 'node:child_process';
|
||||
@@ -9,6 +9,7 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import WebSocket from 'ws';
|
||||
import { buildServer } from '../../site/server/src/app.ts';
|
||||
import { DiscordSource } from '../../site/server/src/discord-source.ts';
|
||||
import { AppAuth } from '../src/core/auth.ts';
|
||||
import { SettingsStore } from '../src/core/settings.ts';
|
||||
|
||||
@@ -50,13 +51,18 @@ const dc = http.createServer((req, res) => {
|
||||
await new Promise<void>((r) => dc.listen(0, '127.0.0.1', () => r()));
|
||||
const dcUrl = `http://127.0.0.1:${(dc.address() as any).port}`;
|
||||
|
||||
const { app: site } = await buildServer({
|
||||
port: PORT, host: '127.0.0.1', publicUrl: base, clientId: 'cid', clientSecret: 's', botToken: BOT,
|
||||
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: path.join(work, 'site'),
|
||||
webDir: '/nonexistent', version: 'e2e', discordApi: dcUrl, assetUpstream: {},
|
||||
});
|
||||
const source = new DiscordSource({ info: () => undefined, error: (o, m) => console.error(m, o) });
|
||||
const { app: site } = await buildServer(
|
||||
{
|
||||
port: PORT, host: '127.0.0.1', publicUrl: base, clientId: 'cid', clientSecret: 's', botToken: BOT,
|
||||
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: path.join(work, 'site'),
|
||||
webDir: '/nonexistent', version: 'e2e', discordApi: dcUrl, assetUpstream: {},
|
||||
},
|
||||
{ botSource: source },
|
||||
);
|
||||
site.log.level = 'warn';
|
||||
await site.listen({ host: '127.0.0.1', port: PORT });
|
||||
await source.login(BOT);
|
||||
|
||||
// 브라우저 흉내: PATH 맨 앞에 가짜 xdg-open 을 둔다 (Electron shell.openExternal 이 부른다. 실제 브라우저는 열지 않는다)
|
||||
// 로그인 주소 → 가짜 디스코드 → 콜백. 로그인할 아이디는 파일에서
|
||||
@@ -161,7 +167,13 @@ try {
|
||||
if (st?.bot.status === 'ready' || st?.bot.status === 'error') break;
|
||||
await sleep(500);
|
||||
}
|
||||
check('서버에서 받은 겜녹이 봇 토큰으로 봇 로그인', st?.bot.status === 'ready' && st.builtinBot, `${st?.bot.status} ${st?.bot.user?.name ?? ''} 서버 ${st?.bot.guilds.length ?? 0}곳 ${st?.bot.error ?? ''}`);
|
||||
check('겜녹이 봇이 사이트 서버 중계로 연결', st?.bot.status === 'ready' && st.builtinBot && /사이트 서버 중계/.test(logs.join('\n')), `${st?.bot.status} ${st?.bot.user?.name ?? ''} 서버 ${st?.bot.guilds.length ?? 0}곳 ${st?.bot.error ?? ''}`);
|
||||
const t = (await gvr('window.gvr.testBotToken()')).v;
|
||||
check('겜녹이 봇 연결 확인 버튼 (토큰 없이 서버 중계)', t?.ok && t.guilds.length > 0, JSON.stringify(t).slice(0, 120));
|
||||
const mem = (await gvr('window.gvr.guildMembers()')).v;
|
||||
check('따라갈 사람 목록 (서버 중계)', Array.isArray(mem) && mem.length > 0, `${mem?.length}명`);
|
||||
const stored = fs.readdirSync(data).filter((f) => fs.statSync(path.join(data, f)).isFile() && fs.readFileSync(path.join(data, f)).includes(Buffer.from(BOT)));
|
||||
check('로그인 후에도 앱 데이터에 봇 토큰 없음', stored.length === 0, stored.join(','));
|
||||
check('계정 표시', st?.account.user?.id === FRIEND && st.account.role === 'user');
|
||||
|
||||
// 일반 유저 권한
|
||||
@@ -185,8 +197,8 @@ try {
|
||||
a = (await gvr('window.gvr.authRecheck()')).v;
|
||||
check('등록 해제 후 확인 → 등록되지 않은 아이디로 잠김', a.status === 'not_registered' && !a.appReady, a.status);
|
||||
check('잠긴 뒤 코어 요청 막힘', /로그인이 필요합니다/.test((await gvr('window.gvr.getState()')).err ?? ''));
|
||||
const secrets = fs.existsSync(path.join(data, 'secrets.bin')) ? fs.readFileSync(path.join(data, 'secrets.bin')) : Buffer.alloc(0);
|
||||
check('잠긴 뒤 받아 둔 봇 토큰 삭제', !secrets.includes(Buffer.from(BOT)) && !secrets.toString('latin1').includes('builtinBotToken'));
|
||||
const secrets = fs.existsSync(path.join(data, 'secrets.bin')) ? fs.readFileSync(path.join(data, 'secrets.bin')).toString('latin1') : '';
|
||||
check('잠긴 뒤 앱 토큰 삭제', !secrets.includes('appToken'));
|
||||
await shot('electron-not-registered');
|
||||
} finally {
|
||||
ws?.close();
|
||||
@@ -197,6 +209,7 @@ try {
|
||||
}
|
||||
await sleep(1500);
|
||||
await site.close();
|
||||
await source.destroy();
|
||||
dc.close();
|
||||
fs.writeFileSync(path.join(work, 'electron.log'), logs.join('\n'));
|
||||
console.log(`작업 폴더 ${work}`);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// node --import tsx scripts/voice-e2e.mts <guildId> <voiceChannelId>
|
||||
// 필요: secrets.json 의 겜녹이·테스트봇 토큰, worker/.venv, tiny 모델(HF 캐시)
|
||||
// M7 실사용 시험: GVR_E2E_SET=demo (시연 대화 28문장, 문장별 CER·지연), GVR_E2E_MODEL=<모델 폴더 경로>, GVR_E2E_DEVICE=cuda
|
||||
// GVR_E2E_RELAY=1: 겜녹이 봇을 사이트 서버 중계로 쓴다 (이 저장소의 사이트 서버 코드를 띄워 봇 토큰은 서버에만 두고,
|
||||
// 앱은 로그인 토큰으로 /app/bot/ws 에 붙는다. 디스코드 OAuth 만 가짜). 끝나면 앱 데이터 폴더에 봇 토큰이 없는지도 본다
|
||||
import { Client, GatewayIntentBits } from 'discord.js';
|
||||
import { joinVoiceChannel, entersState, VoiceConnectionStatus, createAudioPlayer, createAudioResource, StreamType, AudioPlayerStatus } from '@discordjs/voice';
|
||||
import fs from 'node:fs';
|
||||
@@ -32,7 +34,62 @@ fs.writeFileSync(
|
||||
}),
|
||||
);
|
||||
process.env.GVR_RECORD_BOTS = '1';
|
||||
process.env.GVR_BOT_TOKEN = GVR_TOKEN;
|
||||
const RELAY = process.env.GVR_E2E_RELAY === '1';
|
||||
let relayStop: (() => Promise<void>) | null = null;
|
||||
let settings: any;
|
||||
if (RELAY) {
|
||||
delete process.env.GVR_BOT_TOKEN;
|
||||
const http = await import('node:http');
|
||||
const { buildServer } = await import('../../site/server/src/app.ts');
|
||||
const { DiscordSource } = await import('../../site/server/src/discord-source.ts');
|
||||
const { AppAuth } = await import('../src/core/auth.ts');
|
||||
const { SettingsStore } = await import('../src/core/settings.ts');
|
||||
const SUPER = '293719842274541579';
|
||||
// 가짜 디스코드 OAuth: code = 로그인할 아이디
|
||||
const dc = http.createServer((req, res) => {
|
||||
res.setHeader('content-type', 'application/json');
|
||||
if (req.url === '/oauth2/token') return void res.end(JSON.stringify({ access_token: SUPER }));
|
||||
if (req.url === '/users/@me') return void res.end(JSON.stringify({ id: SUPER, username: 'e2e', global_name: 'e2e', avatar: null }));
|
||||
res.statusCode = 404;
|
||||
res.end('{}');
|
||||
});
|
||||
await new Promise<void>((r) => dc.listen(0, '127.0.0.1', () => r()));
|
||||
const source = new DiscordSource({ info: (o, m) => console.log('[site]', m ?? '', JSON.stringify(o)), error: (o, m) => console.error('[site]', m ?? '', o) });
|
||||
const { app: site } = await buildServer(
|
||||
{
|
||||
port: 0, host: '127.0.0.1', publicUrl: 'http://placeholder', clientId: 'cid', clientSecret: 's', botToken: GVR_TOKEN,
|
||||
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: path.join(work, 'site'),
|
||||
webDir: '/nonexistent', version: 'e2e', discordApi: `http://127.0.0.1:${(dc.address() as any).port}`, assetUpstream: {},
|
||||
},
|
||||
{ botSource: source },
|
||||
);
|
||||
site.log.level = 'warn';
|
||||
await site.listen({ host: '127.0.0.1', port: 0 });
|
||||
const base = `http://127.0.0.1:${(site.server.address() as any).port}`;
|
||||
await source.login(GVR_TOKEN);
|
||||
const appDir = path.join(work, 'app');
|
||||
fs.mkdirSync(appDir);
|
||||
fs.copyFileSync(path.join(work, 'settings.json'), path.join(appDir, 'settings.json'));
|
||||
settings = new SettingsStore(appDir);
|
||||
settings.update({ site: { serverUrl: base }, stt: { modelsDir: models } });
|
||||
const auth = new AppAuth(settings, {
|
||||
version: 'e2e',
|
||||
pollMs: 100,
|
||||
openUrl: 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')!;
|
||||
await fetch(`${base}/auth/discord/callback?code=${SUPER}&state=${encodeURIComponent(state)}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
|
||||
},
|
||||
});
|
||||
const a = await auth.login();
|
||||
if (a.status !== 'ok') throw new Error(`앱 로그인 실패: ${a.status} ${a.error}`);
|
||||
console.log('앱 로그인 (서버 중계 모드):', a.user?.name, a.role);
|
||||
relayStop = async () => {
|
||||
await site.close();
|
||||
await source.destroy();
|
||||
dc.close();
|
||||
};
|
||||
} else process.env.GVR_BOT_TOKEN = GVR_TOKEN;
|
||||
const DEMO = process.env.GVR_E2E_SET === 'demo';
|
||||
const demoSrc = fs.readFileSync(path.join(import.meta.dirname, 'demo-stack.mts'), 'utf8');
|
||||
const SENTENCES = DEMO
|
||||
@@ -47,7 +104,7 @@ for (const [i, s] of SENTENCES.entries()) {
|
||||
clips.push(f);
|
||||
}
|
||||
const { startCore } = await import('../src/core/index.ts');
|
||||
const core = await startCore({ dataDir: work, resourcesDir: path.join(root, 'app', 'resources'), worker: { cmd: path.join(root, 'worker/.venv/bin/python'), args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') }, version: 'e2e' });
|
||||
const core = await startCore({ dataDir: RELAY ? path.join(work, 'app') : work, settings, resourcesDir: path.join(root, 'app', 'resources'), worker: { cmd: path.join(root, 'worker/.venv/bin/python'), args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') }, version: 'e2e' });
|
||||
const wait = async (fn: () => boolean, ms: number, label: string) => {
|
||||
const t = Date.now();
|
||||
while (!fn()) {
|
||||
@@ -59,6 +116,7 @@ let ok = false;
|
||||
const spk = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] });
|
||||
try {
|
||||
await wait(() => core.bot.state.status === 'ready', 30000, 'gvr bot ready');
|
||||
if (RELAY) console.log('겜녹이 봇 연결:', core.bot.gateway?.kind, core.bot.state.user?.name);
|
||||
await wait(() => core.stt.status.slots.realtime.state === 'loaded', 120000, 'model');
|
||||
await spk.login(SPEAKER_TOKEN);
|
||||
await new Promise((r) => spk.once('clientReady', r));
|
||||
@@ -120,6 +178,20 @@ try {
|
||||
console.log(`녹음 제외 후 새 발화: ${after - before}개 (0 이어야 함)`);
|
||||
const texts = rows.map((r) => r.text || '').join(' ');
|
||||
ok = rows.length >= SENTENCES.length && /레이즈|오퍼|치킨/.test(texts) && after === before && (!DEMO || cerAvg < 0.15);
|
||||
if (RELAY) {
|
||||
// 서버 중계 모드: 봇은 서버 연결이어야 하고, 앱 데이터 폴더 어디에도 봇 토큰이 없어야 한다
|
||||
const leaked: string[] = [];
|
||||
const scan = (d: string) => {
|
||||
for (const f of fs.readdirSync(d, { withFileTypes: true })) {
|
||||
const p = path.join(d, f.name);
|
||||
if (f.isDirectory()) scan(p);
|
||||
else if (f.isFile() && fs.statSync(p).size < 200 * 1024 * 1024 && fs.readFileSync(p).includes(Buffer.from(GVR_TOKEN))) leaked.push(p);
|
||||
}
|
||||
};
|
||||
scan(path.join(work, 'app'));
|
||||
console.log(`봇 연결 방식: ${core.bot.gateway?.kind} · 앱 데이터에 봇 토큰: ${leaked.length ? leaked.join(', ') : '없음'}`);
|
||||
ok &&= core.bot.gateway?.kind === 'remote' && leaked.length === 0;
|
||||
}
|
||||
conn.destroy();
|
||||
await wait(() => !core.bot.state.recording.active, 20000, 'gvr leaves after speaker').catch(() => console.log('(겜녹이 퇴장 대기 시간 초과)'));
|
||||
console.log('겜녹이 퇴장:', !core.bot.state.recording.active);
|
||||
@@ -128,6 +200,7 @@ try {
|
||||
} finally {
|
||||
await spk.destroy();
|
||||
await core.stop();
|
||||
await relayStop?.();
|
||||
console.log(ok ? 'VOICE E2E PASS' : 'VOICE E2E FAIL');
|
||||
process.exit(ok ? 0 : 1);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// 앱(exe) 디스코드 로그인. 사이트 서버(site/server/src/app-auth.ts)가 유저 명단을 갖고 있다.
|
||||
// - 로그인: 서버에 요청을 만들고 브라우저로 디스코드 로그인 → 결과를 받아 온다 (토큰은 DPAPI 로 암호화 저장)
|
||||
// - 확인: 시작할 때와 10분마다 /app/me. 등록 해제 · 로그아웃되면 바로 잠그고 받아 둔 겜녹이 봇 토큰도 지운다
|
||||
// - 확인: 시작할 때와 10분마다 /app/me. 등록 해제 · 로그아웃되면 바로 잠근다
|
||||
// - 겜녹이 봇 토큰은 받지 않는다. 봇은 사이트 서버가 연결하고 앱은 앱 토큰으로 중계받는다 (discord/gateway.ts)
|
||||
// - 서버에 잠깐 못 붙으면 마지막 확인 후 3일까지는 그대로 쓴다
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { AppLoginBegin, AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared';
|
||||
@@ -89,10 +90,10 @@ export class AppAuth extends EventEmitter {
|
||||
return json as T;
|
||||
}
|
||||
|
||||
/** 로그인 정보 · 겜녹이 봇 토큰을 지운다 (등록 해제 · 로그아웃) */
|
||||
/** 로그인 정보를 지운다 (등록 해제 · 로그아웃) */
|
||||
private forget(): void {
|
||||
this.gen++;
|
||||
for (const k of ['appToken', 'builtinBotToken', 'auth'] as const) if (this.settings.hasSecret(k)) this.settings.setSecret(k, null);
|
||||
for (const k of ['appToken', 'auth'] as const) if (this.settings.hasSecret(k)) this.settings.setSecret(k, null);
|
||||
}
|
||||
|
||||
/** 저장된 토큰으로 서버에 확인 */
|
||||
@@ -101,6 +102,8 @@ export class AppAuth extends EventEmitter {
|
||||
const token = this.settings.getSecret('appToken');
|
||||
const gen = ++this.gen;
|
||||
if (!token) {
|
||||
// 등록 해제로 잠긴 화면은 다시 확인해도 그대로 둔다 (봇 중계가 끊기며 바로 확인한 뒤 또 확인이 와도 "등록되지 않은 아이디" 유지)
|
||||
if (this.state.status === 'not_registered') return this.state;
|
||||
this.set({ status: 'signed_out', user: null, role: null, offline: false, error: null, verifiedAt: null });
|
||||
return this.state;
|
||||
}
|
||||
@@ -111,11 +114,13 @@ export class AppAuth extends EventEmitter {
|
||||
if (stale()) return this.state;
|
||||
const cache = { user: me.user, role: me.role, verifiedAt: Date.now() };
|
||||
this.settings.setSecret('auth', cache);
|
||||
if (me.botToken !== (this.settings.getSecret('builtinBotToken') ?? null)) this.settings.setSecret('builtinBotToken', me.botToken);
|
||||
this.set({ status: 'ok', user: me.user, role: me.role, offline: false, error: null, loginUrl: null, verifiedAt: cache.verifiedAt });
|
||||
} catch (e: any) {
|
||||
if (stale()) return this.state;
|
||||
if (e instanceof HttpError && (e.status === 401 || e.status === 403)) {
|
||||
const lock = e instanceof HttpError && (e.status === 401 || e.status === 403);
|
||||
// 잠그라는 응답(401 · 403)은 늦게 와도 같은 토큰이면 따른다. 두 확인이 겹치면 서버가 첫 403 에서 세션을 지워
|
||||
// 뒤 확인은 401 을 받는데, 403 을 버리면 "등록되지 않은 아이디" 대신 "로그인 만료"로 잠긴다. 로그인 진행 중에는 건드리지 않는다
|
||||
if (lock ? (this.state.status as AuthStatus) === 'waiting' || this.settings.getSecret('appToken') !== token : stale()) return this.state;
|
||||
if (lock) {
|
||||
const notReg = e.status === 403 && e.body?.error === 'not_registered';
|
||||
log.warn(notReg ? '등록이 해제된 아이디라 잠급니다' : '로그인이 만료되어 잠급니다');
|
||||
const user = notReg ? (e.body?.user ?? this.state.user) : null;
|
||||
|
||||
@@ -10,36 +10,18 @@ import {
|
||||
type AudioPlayer,
|
||||
type VoiceConnection,
|
||||
} from '@discordjs/voice';
|
||||
import {
|
||||
ChannelType,
|
||||
Client,
|
||||
Events,
|
||||
GatewayIntentBits,
|
||||
MessageFlags,
|
||||
type ChatInputCommandInteraction,
|
||||
type Guild,
|
||||
type GuildMember,
|
||||
type VoiceBasedChannel,
|
||||
type VoiceState,
|
||||
} from 'discord.js';
|
||||
import fs from 'node:fs';
|
||||
import type { Store } from '../db/db.js';
|
||||
import type { Settings } from '../settings.js';
|
||||
import type { Bus } from '../util/events.js';
|
||||
import { newId } from '../util/ids.js';
|
||||
import type { BotGateway, GChannel, GCommand, GMember, GVoiceEvent } from './gateway.js';
|
||||
import { logger } from '../util/log.js';
|
||||
import type { Recorder } from './recorder.js';
|
||||
import type { Announcer } from './tts.js';
|
||||
|
||||
const log = logger('bot');
|
||||
|
||||
export const COMMANDS = [
|
||||
{ name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' },
|
||||
{ name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' },
|
||||
{ name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' },
|
||||
{ name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' },
|
||||
];
|
||||
|
||||
export interface BotState {
|
||||
status: 'off' | 'connecting' | 'ready' | 'error';
|
||||
error: string | null;
|
||||
@@ -52,9 +34,10 @@ export interface BotState {
|
||||
/**
|
||||
* 디스코드 봇: 나를 따라 음성채널에 들어가거나(/녹음시작) 명령으로 참여하고, TTS 로 녹음 사실을 알린다 (Q7, Q8).
|
||||
* 채팅 메시지는 보내지 않는다. 명령 응답은 본인에게만 보인다.
|
||||
* 디스코드 연결은 BotGateway 가 맡는다 (겜녹이 봇 = 사이트 서버 중계, 다른 봇 = 이 PC 가 직접 연결)
|
||||
*/
|
||||
export class Bot {
|
||||
client: Client | null = null;
|
||||
gateway: BotGateway | null = null;
|
||||
private connection: VoiceConnection | null = null;
|
||||
private player: AudioPlayer | null = null;
|
||||
private sessionId: string | null = null;
|
||||
@@ -77,134 +60,162 @@ export class Bot {
|
||||
private onGuild?: (guildId: string) => void,
|
||||
) {}
|
||||
|
||||
async start(token: string): Promise<void> {
|
||||
async start(gw: BotGateway): Promise<void> {
|
||||
await this.stop();
|
||||
this.state.status = 'connecting';
|
||||
this.state.error = null;
|
||||
const client = new Client({
|
||||
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers],
|
||||
});
|
||||
this.client = client;
|
||||
client.on(Events.ClientReady, () => void this.onReady());
|
||||
client.on(Events.VoiceStateUpdate, (o, n) => void this.onVoiceState(o, n).catch((e) => log.error('voiceState 처리 오류', e)));
|
||||
client.on(Events.InteractionCreate, (i) => {
|
||||
if (i.isChatInputCommand()) void this.onCommand(i).catch((e) => log.error('명령 처리 오류', e));
|
||||
});
|
||||
client.on(Events.Error, (e) => log.error('discord 오류', e));
|
||||
client.on(Events.GuildCreate, () => this.refreshGuilds());
|
||||
this.gateway = gw;
|
||||
const mine = (fn: (...a: any[]) => void) => (...a: any[]) => {
|
||||
if (this.gateway === gw) fn(...a);
|
||||
};
|
||||
gw.on('ready', mine(() => void this.onReady().catch((e) => log.error('봇 준비 처리 오류', e))));
|
||||
gw.on('guilds', mine(() => this.refreshGuilds()));
|
||||
gw.on('voiceState', mine((e: GVoiceEvent) => void this.onVoiceState(e).catch((err) => log.error('voiceState 처리 오류', err))));
|
||||
gw.on('command', mine((c: GCommand, respond: (content: string) => void) => void this.onCommand(c).then(respond, (e) => respond(`처리하지 못했습니다: ${e.message}`))));
|
||||
gw.on('taken', mine((guildId: string) => {
|
||||
if (this.connection && this.state.recording.channelId && this.state.guild?.id === guildId) {
|
||||
log.warn('다른 PC 가 이 서버에서 겜녹이 봇을 데려가 녹음을 멈춥니다');
|
||||
this.leave('taken');
|
||||
}
|
||||
}));
|
||||
gw.on('down', mine(() => {
|
||||
this.leave('gateway-down');
|
||||
this.state.status = 'connecting';
|
||||
this.state.error = '연결이 끊겨 다시 연결하는 중입니다';
|
||||
}));
|
||||
gw.on('unauthorized', mine(() => {
|
||||
this.state.status = 'error';
|
||||
this.state.error = '로그인이 만료되었거나 등록이 해제되었습니다';
|
||||
}));
|
||||
try {
|
||||
await client.login(token);
|
||||
await gw.start();
|
||||
} catch (e: any) {
|
||||
if (this.gateway !== gw) return;
|
||||
this.state.status = 'error';
|
||||
this.state.error = e?.message?.includes('TOKEN_INVALID') || e?.code === 'TokenInvalid' ? '봇 토큰이 올바르지 않습니다' : e.message;
|
||||
this.client = null;
|
||||
// 겜녹이 봇(서버 중계)은 뒤에서 계속 다시 붙는다. 다른 봇은 토큰이 틀렸을 수 있으니 멈춘다
|
||||
if (gw.kind === 'local') {
|
||||
this.gateway = null;
|
||||
await gw.stop().catch(() => undefined);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.leave('stop');
|
||||
if (this.client) {
|
||||
await this.client.destroy();
|
||||
this.client = null;
|
||||
const gw = this.gateway;
|
||||
this.gateway = null;
|
||||
if (gw) {
|
||||
gw.removeAllListeners();
|
||||
await gw.stop();
|
||||
}
|
||||
this.state.status = 'off';
|
||||
this.state.user = null;
|
||||
}
|
||||
|
||||
/** 녹음에서 빼야 하는 다른 봇인지 */
|
||||
isBot(userId: string): boolean {
|
||||
return !!this.gateway?.isBot(userId);
|
||||
}
|
||||
|
||||
private refreshGuilds(): void {
|
||||
if (!this.client) return;
|
||||
this.state.guilds = [...this.client.guilds.cache.values()].map((g) => ({ id: g.id, name: g.name }));
|
||||
this.state.guilds = (this.gateway?.guilds() ?? []).map((g) => ({ id: g.id, name: g.name }));
|
||||
}
|
||||
|
||||
guild(): Guild | null {
|
||||
if (!this.client) return null;
|
||||
/** 녹음할 디스코드 서버 아이디 (설정값, 없으면 봇이 들어간 첫 서버) */
|
||||
guildId(): string | null {
|
||||
const gs = this.gateway?.guilds() ?? [];
|
||||
const id = this.settings().discord.guildId;
|
||||
return (id && this.client.guilds.cache.get(id)) || this.client.guilds.cache.first() || null;
|
||||
return (id && gs.find((g) => g.id === id)?.id) || gs[0]?.id || null;
|
||||
}
|
||||
|
||||
members(): Promise<GMember[]> {
|
||||
const gid = this.guildId();
|
||||
return gid && this.gateway ? this.gateway.members(gid) : Promise.resolve([]);
|
||||
}
|
||||
|
||||
private async onReady(): Promise<void> {
|
||||
const c = this.client!;
|
||||
const gw = this.gateway!;
|
||||
const me = gw.me()!;
|
||||
this.state.status = 'ready';
|
||||
this.state.user = { id: c.user!.id, name: c.user!.username, avatar: c.user!.displayAvatarURL({ size: 128 }) };
|
||||
this.state.error = null;
|
||||
this.state.user = { id: me.id, name: me.name, avatar: me.avatar };
|
||||
this.refreshGuilds();
|
||||
const g = this.guild();
|
||||
log.info(`봇 로그인: ${c.user!.tag}, 서버 ${this.state.guilds.map((x) => x.name).join(', ')}`);
|
||||
if (!g) return;
|
||||
this.state.guild = { id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) };
|
||||
log.info(`봇 로그인: ${me.name}${gw.kind === 'remote' ? ' (사이트 서버 중계)' : ''}, 서버 ${this.state.guilds.map((x) => x.name).join(', ')}`);
|
||||
const gid = this.guildId();
|
||||
if (!gid) return;
|
||||
const g = await gw.watch(gid, { commands: this.settings().discord.commandsEnabled });
|
||||
if (!g || this.gateway !== gw) return;
|
||||
this.state.guild = { id: g.id, name: g.name, icon: g.icon };
|
||||
this.onGuild?.(g.id);
|
||||
if (this.settings().discord.commandsEnabled) {
|
||||
try {
|
||||
await g.commands.set(COMMANDS);
|
||||
log.info('슬래시 명령 등록 완료');
|
||||
} catch (e) {
|
||||
log.warn('슬래시 명령 등록 실패', e);
|
||||
}
|
||||
}
|
||||
// 이미 따라갈 유저가 음성채널에 있으면 바로 들어간다
|
||||
const follow = this.settings().discord.followUserId;
|
||||
if (follow && this.settings().discord.followEnabled) {
|
||||
const m = await g.members.fetch(follow).catch(() => null);
|
||||
if (m?.voice.channel) await this.join(m.voice.channel, 'follow');
|
||||
const ch = gw.voiceChannelOf(g.id, follow);
|
||||
if (ch) await this.join(ch, 'follow').catch((e) => log.warn(`따라가기 실패: ${e.message}`));
|
||||
}
|
||||
}
|
||||
|
||||
private async onVoiceState(o: VoiceState, n: VoiceState): Promise<void> {
|
||||
const g = this.guild();
|
||||
if (!g || n.guild.id !== g.id) return;
|
||||
private async onVoiceState(e: GVoiceEvent): Promise<void> {
|
||||
const gid = this.state.guild?.id;
|
||||
if (!gid || e.guildId !== gid) return;
|
||||
const s = this.settings().discord;
|
||||
const uid = n.id;
|
||||
if (uid === this.client?.user?.id) {
|
||||
const uid = e.member.id;
|
||||
if (uid === this.state.user?.id) {
|
||||
// 누군가 봇을 끊었으면 세션 종료
|
||||
if (o.channelId && !n.channelId) this.leave('kicked');
|
||||
if (e.oldChannelId && !e.newChannelId) this.leave('kicked');
|
||||
return;
|
||||
}
|
||||
// 따라가기
|
||||
if (s.followEnabled && s.followUserId === uid && o.channelId !== n.channelId) {
|
||||
if (n.channel) await this.join(n.channel, 'follow');
|
||||
if (s.followEnabled && s.followUserId === uid && e.oldChannelId !== e.newChannelId) {
|
||||
if (e.channel) await this.join(e.channel, 'follow');
|
||||
else if (this.state.recording.reason === 'follow') this.leave('follow-left');
|
||||
}
|
||||
const myCh = this.state.recording.channelId;
|
||||
if (!myCh) return;
|
||||
// 새 사람이 들어오면 안내를 다시 튼다
|
||||
if (n.channelId === myCh && o.channelId !== myCh && n.member && (!n.member.user.bot || process.env.GVR_RECORD_BOTS === '1')) {
|
||||
this.touchUser(n.member);
|
||||
if (e.newChannelId === myCh && e.oldChannelId !== myCh && (!e.member.bot || process.env.GVR_RECORD_BOTS === '1')) {
|
||||
this.touchUser(e.member);
|
||||
this.updateParticipants();
|
||||
if (s.ttsEnabled && s.ttsOnNewMember) void this.announce();
|
||||
}
|
||||
if (o.channelId === myCh && n.channelId !== myCh) this.updateParticipants();
|
||||
if (e.oldChannelId === myCh && e.newChannelId !== myCh) this.updateParticipants();
|
||||
}
|
||||
|
||||
private touchUser(m: GuildMember): void {
|
||||
this.store.upsertUser({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }) });
|
||||
private touchUser(m: GMember): void {
|
||||
this.store.upsertUser({ id: m.id, name: m.name, avatar: m.avatar });
|
||||
}
|
||||
|
||||
private channelMembers(): GMember[] {
|
||||
const id = this.state.recording.channelId;
|
||||
const gid = this.state.guild?.id;
|
||||
return id && gid && this.gateway ? this.gateway.channelMembers(gid, id) : [];
|
||||
}
|
||||
|
||||
private updateParticipants(): void {
|
||||
const ch = this.currentChannel();
|
||||
const inCh = !!this.state.recording.channelId;
|
||||
// GVR_RECORD_BOTS=1 (테스트봇으로 시험할 때)이면 봇도 사람처럼 센다. 안 그러면 30초 뒤 '빈 방'으로 나가 버린다.
|
||||
const humans = ch ? [...ch.members.values()].filter((m) => !m.user.bot || (process.env.GVR_RECORD_BOTS === '1' && m.id !== this.client?.user?.id)) : [];
|
||||
const humans = this.channelMembers().filter((m) => !m.bot || (process.env.GVR_RECORD_BOTS === '1' && m.id !== this.state.user?.id));
|
||||
this.state.recording.participants = humans.map((m) => m.id);
|
||||
this.emitState();
|
||||
// 사람이 아무도 없으면 30초 뒤 나간다
|
||||
if (this.emptyTimer) clearTimeout(this.emptyTimer);
|
||||
this.emptyTimer = null;
|
||||
if (ch && humans.length === 0) this.emptyTimer = setTimeout(() => this.leave('empty'), 30000);
|
||||
if (inCh && humans.length === 0) this.emptyTimer = setTimeout(() => this.leave('empty'), 30000);
|
||||
}
|
||||
|
||||
private currentChannel(): VoiceBasedChannel | null {
|
||||
const id = this.state.recording.channelId;
|
||||
if (!id || !this.client) return null;
|
||||
const ch = this.client.channels.cache.get(id);
|
||||
return ch && (ch.type === ChannelType.GuildVoice || ch.type === ChannelType.GuildStageVoice) ? (ch as VoiceBasedChannel) : null;
|
||||
}
|
||||
|
||||
async join(channel: VoiceBasedChannel, reason: 'follow' | 'command'): Promise<void> {
|
||||
async join(channel: GChannel, reason: 'follow' | 'command'): Promise<void> {
|
||||
const gw = this.gateway;
|
||||
const gid = this.state.guild?.id;
|
||||
if (!gw || !gid) throw new Error('봇이 준비되지 않았습니다');
|
||||
if (this.state.recording.channelId === channel.id && this.connection) return;
|
||||
if (this.connection) this.leave('move');
|
||||
log.info(`음성채널 참여: ${channel.name} (${reason})`);
|
||||
const conn = joinVoiceChannel({
|
||||
channelId: channel.id,
|
||||
guildId: channel.guild.id,
|
||||
adapterCreator: channel.guild.voiceAdapterCreator,
|
||||
guildId: gid,
|
||||
adapterCreator: gw.adapterCreator(gid),
|
||||
selfDeaf: false,
|
||||
selfMute: false,
|
||||
daveEncryption: true,
|
||||
@@ -221,20 +232,29 @@ export class Bot {
|
||||
if (this.connection === conn) this.leave('disconnected');
|
||||
}
|
||||
});
|
||||
// 연결 통로가 끊겨 어댑터가 사라진 경우 (서버 중계 끊김 등)
|
||||
conn.on(VoiceConnectionStatus.Destroyed, () => {
|
||||
if (this.connection === conn) this.leave('destroyed');
|
||||
});
|
||||
try {
|
||||
await entersState(conn, VoiceConnectionStatus.Ready, 20000);
|
||||
} catch (e) {
|
||||
log.error('음성채널 연결 실패', e);
|
||||
conn.destroy();
|
||||
if (this.connection === conn) this.connection = null;
|
||||
try {
|
||||
conn.destroy();
|
||||
} catch {
|
||||
/* 이미 끊김 */
|
||||
}
|
||||
throw new Error('음성채널 연결 실패');
|
||||
}
|
||||
if (this.connection !== conn) throw new Error('음성채널 연결이 끊겼습니다');
|
||||
const now = Date.now();
|
||||
this.sessionId = newId(now);
|
||||
this.store.startSession(this.sessionId, channel.guild.id, channel.id, channel.name, now);
|
||||
for (const m of channel.members.values()) if (!m.user.bot || process.env.GVR_RECORD_BOTS === '1') this.touchUser(m);
|
||||
this.bus.live({ type: 'users.updated', data: [] });
|
||||
this.store.startSession(this.sessionId, gid, channel.id, channel.name, now);
|
||||
this.state.recording = { active: true, channel: channel.name, channelId: channel.id, since: now, participants: [], reason };
|
||||
for (const m of this.channelMembers()) if (!m.bot || process.env.GVR_RECORD_BOTS === '1') this.touchUser(m);
|
||||
this.bus.live({ type: 'users.updated', data: [] });
|
||||
this.recorder.attach(conn, this.sessionId);
|
||||
this.player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause } });
|
||||
conn.subscribe(this.player);
|
||||
@@ -246,15 +266,16 @@ export class Bot {
|
||||
if (this.emptyTimer) clearTimeout(this.emptyTimer);
|
||||
this.emptyTimer = null;
|
||||
this.recorder.detach();
|
||||
if (this.connection) {
|
||||
const conn = this.connection;
|
||||
this.connection = null;
|
||||
if (conn) {
|
||||
log.info(`음성채널 나감 (${why})`);
|
||||
try {
|
||||
this.connection.destroy();
|
||||
conn.destroy();
|
||||
} catch {
|
||||
/* 이미 끊김 */
|
||||
}
|
||||
}
|
||||
this.connection = null;
|
||||
this.player?.stop(true);
|
||||
this.player = null;
|
||||
if (this.sessionId) this.store.endSession(this.sessionId, Date.now());
|
||||
@@ -284,36 +305,35 @@ export class Bot {
|
||||
this.bus.live({ type: 'recording.state', data: { active: r.active, channel: r.channel, since: r.since, participants: r.participants } });
|
||||
}
|
||||
|
||||
private async onCommand(i: ChatInputCommandInteraction): Promise<void> {
|
||||
const reply = (content: string) => i.reply({ content, flags: MessageFlags.Ephemeral });
|
||||
const member = i.member as GuildMember | null;
|
||||
switch (i.commandName) {
|
||||
/** 슬래시 명령 처리. 돌려준 문장이 본인에게만 보이는 응답이 된다 */
|
||||
private async onCommand(c: GCommand): Promise<string> {
|
||||
if (c.guildId !== this.state.guild?.id) return '이 서버는 겜녹이 앱의 녹음 서버로 설정되어 있지 않습니다.';
|
||||
switch (c.name) {
|
||||
case '녹음시작': {
|
||||
const ch = member?.voice?.channel;
|
||||
if (!ch) return void (await reply('먼저 음성채널에 들어가 주세요.'));
|
||||
await i.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
const ch = c.voiceChannel;
|
||||
if (!ch) return '먼저 음성채널에 들어가 주세요.';
|
||||
try {
|
||||
await this.join(ch, 'command');
|
||||
await i.editReply(`🎙️ ${ch.name} 채널 녹음을 시작했습니다.`);
|
||||
return `🎙️ ${ch.name} 채널 녹음을 시작했습니다.`;
|
||||
} catch (e: any) {
|
||||
await i.editReply(`음성채널에 들어가지 못했습니다: ${e.message}`);
|
||||
return `음성채널에 들어가지 못했습니다: ${e.message}`;
|
||||
}
|
||||
return;
|
||||
}
|
||||
case '녹음종료':
|
||||
if (!this.connection) return void (await reply('지금은 녹음 중이 아닙니다.'));
|
||||
if (!this.connection) return '지금은 녹음 중이 아닙니다.';
|
||||
this.leave('command');
|
||||
return void (await reply('⏹️ 녹음을 끝냈습니다.'));
|
||||
return '⏹️ 녹음을 끝냈습니다.';
|
||||
case '녹음제외':
|
||||
if (member) this.touchUser(member);
|
||||
this.store.setExcluded(i.user.id, true);
|
||||
this.touchUser(c.user);
|
||||
this.store.setExcluded(c.user.id, true);
|
||||
this.bus.live({ type: 'users.updated', data: [] });
|
||||
return void (await reply('🔇 이제부터 내 목소리는 녹음하지 않습니다. 다시 참여하려면 /녹음참여 를 입력하세요.'));
|
||||
return '🔇 이제부터 내 목소리는 녹음하지 않습니다. 다시 참여하려면 /녹음참여 를 입력하세요.';
|
||||
case '녹음참여':
|
||||
if (member) this.touchUser(member);
|
||||
this.store.setExcluded(i.user.id, false);
|
||||
this.touchUser(c.user);
|
||||
this.store.setExcluded(c.user.id, false);
|
||||
this.bus.live({ type: 'users.updated', data: [] });
|
||||
return void (await reply('🎙️ 다시 녹음에 참여합니다.'));
|
||||
return '🎙️ 다시 녹음에 참여합니다.';
|
||||
}
|
||||
return '알 수 없는 명령입니다.';
|
||||
}
|
||||
}
|
||||
|
||||
437
app/src/core/discord/gateway.ts
Normal file
437
app/src/core/discord/gateway.ts
Normal file
@@ -0,0 +1,437 @@
|
||||
// 봇이 디스코드와 이야기하는 통로 두 가지
|
||||
// - LocalGateway: '다른 봇으로 진행하기' (사용자가 넣은 봇 토큰으로 이 PC 가 직접 연결)
|
||||
// - RemoteGateway: 겜녹이 봇. 봇 토큰은 사이트 서버에만 있고, 이 PC 는 서버(/app/bot/ws)를 거쳐 정보만 받는다.
|
||||
// 음성채널에 들어갈 때 서버가 디스코드에서 받은 일회용 음성 접속 정보를 넘겨주고, 음성은 이 PC ↔ 디스코드로 바로 간다
|
||||
import type { DiscordGatewayAdapterCreator, DiscordGatewayAdapterLibraryMethods } from '@discordjs/voice';
|
||||
import type { BotGwChannel, BotGwFromApp, BotGwGuild, BotGwMember, BotGwToApp } from '@gvr/shared';
|
||||
import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import WebSocket from 'ws';
|
||||
import { logger } from '../util/log.js';
|
||||
|
||||
const log = logger('gateway');
|
||||
|
||||
export type GMember = BotGwMember;
|
||||
export type GGuild = BotGwGuild;
|
||||
export type GChannel = BotGwChannel;
|
||||
export interface GVoiceEvent {
|
||||
guildId: string;
|
||||
member: GMember;
|
||||
oldChannelId: string | null;
|
||||
newChannelId: string | null;
|
||||
channel: GChannel | null;
|
||||
}
|
||||
export interface GCommand {
|
||||
name: string;
|
||||
guildId: string;
|
||||
user: GMember;
|
||||
voiceChannel: GChannel | null;
|
||||
}
|
||||
|
||||
export const COMMANDS = [
|
||||
{ name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' },
|
||||
{ name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' },
|
||||
{ name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' },
|
||||
{ name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 이벤트: 'ready' · 'guilds' · 'voiceState' (GVoiceEvent) · 'command' (GCommand, respond(content)) ·
|
||||
* 'taken' (guildId: 다른 PC 가 봇을 데려감) · 'down' (연결 끊김) · 'unauthorized' (앱 로그인 만료 · 등록 해제)
|
||||
*/
|
||||
export interface BotGateway extends EventEmitter {
|
||||
readonly kind: 'local' | 'remote';
|
||||
me(): GMember | null;
|
||||
guilds(): GGuild[];
|
||||
start(): Promise<void>;
|
||||
stop(): Promise<void>;
|
||||
/** 이 서버의 음성 상태를 따라간다 (명령 등록 포함) */
|
||||
watch(guildId: string, opts: { commands: boolean }): Promise<GGuild | null>;
|
||||
voiceChannelOf(guildId: string, userId: string): GChannel | null;
|
||||
channel(guildId: string, channelId: string): GChannel | null;
|
||||
channelMembers(guildId: string, channelId: string): GMember[];
|
||||
members(guildId: string): Promise<GMember[]>;
|
||||
isBot(userId: string): boolean;
|
||||
adapterCreator(guildId: string): DiscordGatewayAdapterCreator;
|
||||
}
|
||||
|
||||
const gm = (m: GuildMember): GMember => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }), bot: m.user.bot });
|
||||
const gg = (g: Guild): GGuild => ({ id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) });
|
||||
const isVoice = (c: { type: ChannelType } | null | undefined): c is VoiceBasedChannel => !!c && (c.type === ChannelType.GuildVoice || c.type === ChannelType.GuildStageVoice);
|
||||
|
||||
// ------------------------------------------------------------------ 다른 봇 (토큰으로 직접 연결)
|
||||
export class LocalGateway extends EventEmitter implements BotGateway {
|
||||
readonly kind = 'local';
|
||||
private client: Client | null = null;
|
||||
|
||||
constructor(private token: string) {
|
||||
super();
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
const c = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers] });
|
||||
this.client = c;
|
||||
c.on(Events.ClientReady, () => this.emit('ready'));
|
||||
c.on(Events.GuildCreate, () => this.emit('guilds'));
|
||||
c.on(Events.GuildDelete, () => this.emit('guilds'));
|
||||
c.on(Events.Error, (e) => log.error('discord 오류', e));
|
||||
c.on(Events.VoiceStateUpdate, (o, n) => {
|
||||
const m = n.member ?? o.member;
|
||||
if (!m) return;
|
||||
const ch = n.channel;
|
||||
this.emit('voiceState', { guildId: n.guild.id, member: gm(m), oldChannelId: o.channelId, newChannelId: n.channelId, channel: ch ? { id: ch.id, name: ch.name } : null } satisfies GVoiceEvent);
|
||||
});
|
||||
c.on(Events.InteractionCreate, async (i) => {
|
||||
if (!i.isChatInputCommand() || !i.guildId) return;
|
||||
try {
|
||||
await i.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
} catch (e) {
|
||||
log.error('명령 응답 실패', e);
|
||||
return;
|
||||
}
|
||||
const m = (i.member as GuildMember | null) ?? null;
|
||||
const vc = m?.voice?.channel ?? null;
|
||||
const cmd: GCommand = {
|
||||
name: i.commandName,
|
||||
guildId: i.guildId,
|
||||
user: m ? gm(m) : { id: i.user.id, name: i.user.username, avatar: null, bot: i.user.bot },
|
||||
voiceChannel: vc ? { id: vc.id, name: vc.name } : null,
|
||||
};
|
||||
this.emit('command', cmd, (content: string) => void i.editReply(content).catch((e) => log.error('명령 응답 실패', e)));
|
||||
});
|
||||
try {
|
||||
await c.login(this.token);
|
||||
} catch (e) {
|
||||
this.client = null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
const c = this.client;
|
||||
this.client = null;
|
||||
await c?.destroy();
|
||||
}
|
||||
|
||||
me(): GMember | null {
|
||||
const u = this.client?.isReady() ? this.client.user : null;
|
||||
return u ? { id: u.id, name: u.username, avatar: u.displayAvatarURL({ size: 128 }), bot: true } : null;
|
||||
}
|
||||
guilds(): GGuild[] {
|
||||
return this.client ? [...this.client.guilds.cache.values()].map(gg) : [];
|
||||
}
|
||||
private g(id: string): Guild | null {
|
||||
return this.client?.guilds.cache.get(id) ?? null;
|
||||
}
|
||||
async watch(guildId: string, opts: { commands: boolean }): Promise<GGuild | null> {
|
||||
const g = this.g(guildId);
|
||||
if (!g) return null;
|
||||
if (opts.commands) {
|
||||
try {
|
||||
await g.commands.set(COMMANDS);
|
||||
log.info('슬래시 명령 등록 완료');
|
||||
} catch (e) {
|
||||
log.warn('슬래시 명령 등록 실패', e);
|
||||
}
|
||||
}
|
||||
return gg(g);
|
||||
}
|
||||
voiceChannelOf(guildId: string, userId: string): GChannel | null {
|
||||
const ch = this.g(guildId)?.voiceStates.cache.get(userId)?.channel;
|
||||
return ch ? { id: ch.id, name: ch.name } : null;
|
||||
}
|
||||
channel(guildId: string, channelId: string): GChannel | null {
|
||||
const ch = this.g(guildId)?.channels.cache.get(channelId);
|
||||
return isVoice(ch) ? { id: ch.id, name: ch.name } : null;
|
||||
}
|
||||
channelMembers(guildId: string, channelId: string): GMember[] {
|
||||
const ch = this.g(guildId)?.channels.cache.get(channelId);
|
||||
return isVoice(ch) ? [...ch.members.values()].map(gm) : [];
|
||||
}
|
||||
async members(guildId: string): Promise<GMember[]> {
|
||||
const g = this.g(guildId);
|
||||
if (!g) return [];
|
||||
const ms = await g.members.fetch().catch(() => g.members.cache);
|
||||
return [...ms.values()].map(gm);
|
||||
}
|
||||
isBot(userId: string): boolean {
|
||||
return !!this.client?.users.cache.get(userId)?.bot;
|
||||
}
|
||||
adapterCreator(guildId: string): DiscordGatewayAdapterCreator {
|
||||
const g = this.g(guildId);
|
||||
if (!g) throw new Error('디스코드 서버를 찾지 못했습니다');
|
||||
return g.voiceAdapterCreator;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 겜녹이 봇 (사이트 서버 중계)
|
||||
export interface RemoteGatewayOptions {
|
||||
serverUrl: () => string;
|
||||
appToken: () => string | null;
|
||||
version: string;
|
||||
}
|
||||
|
||||
export class RemoteGateway extends EventEmitter implements BotGateway {
|
||||
readonly kind = 'remote';
|
||||
private ws: WebSocket | null = null;
|
||||
private stopped = true;
|
||||
private retries = 0;
|
||||
private retryTimer: NodeJS.Timeout | null = null;
|
||||
private _me: GMember | null = null;
|
||||
private _guilds: GGuild[] = [];
|
||||
private watched: { id: string; commands: boolean } | null = null;
|
||||
private wait: { resolve: (g: GGuild | null) => void } | null = null;
|
||||
private channels = new Map<string, GChannel>();
|
||||
/** userId → 음성채널 */
|
||||
private voice = new Map<string, string>();
|
||||
private known = new Map<string, GMember>();
|
||||
private adapters = new Map<string, DiscordGatewayAdapterLibraryMethods>();
|
||||
private reqs = new Map<string, { resolve: (v: any) => void; reject: (e: Error) => void }>();
|
||||
private seq = 0;
|
||||
lastError: string | null = null;
|
||||
|
||||
constructor(private opts: RemoteGatewayOptions) {
|
||||
super();
|
||||
}
|
||||
|
||||
/** 서버에 붙어 ready 를 받을 때까지 기다린다 (실패해도 뒤에서 계속 다시 붙는다) */
|
||||
start(): Promise<void> {
|
||||
this.stopped = false;
|
||||
return new Promise((resolve, reject) => {
|
||||
const t = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error(this.lastError || '사이트 서버의 겜녹이 봇에 연결하지 못했습니다'));
|
||||
}, 20000);
|
||||
const ok = () => {
|
||||
cleanup();
|
||||
resolve();
|
||||
};
|
||||
const bad = () => {
|
||||
cleanup();
|
||||
reject(new Error(this.lastError || '다시 로그인해 주세요'));
|
||||
};
|
||||
const cleanup = () => {
|
||||
clearTimeout(t);
|
||||
this.off('ready', ok);
|
||||
this.off('unauthorized', bad);
|
||||
};
|
||||
this.once('ready', ok);
|
||||
this.once('unauthorized', bad);
|
||||
this.connect();
|
||||
});
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.stopped = true;
|
||||
if (this.retryTimer) clearTimeout(this.retryTimer);
|
||||
this.retryTimer = null;
|
||||
const ws = this.ws;
|
||||
this.ws = null;
|
||||
this.reset();
|
||||
ws?.close(1000);
|
||||
}
|
||||
|
||||
private reset(): void {
|
||||
this._me = null;
|
||||
for (const a of this.adapters.values()) a.destroy();
|
||||
this.adapters.clear();
|
||||
for (const r of this.reqs.values()) r.reject(new Error('사이트 서버 연결이 끊겼습니다'));
|
||||
this.reqs.clear();
|
||||
this.wait?.resolve(null);
|
||||
this.wait = null;
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
if (this.stopped) return;
|
||||
const token = this.opts.appToken();
|
||||
if (!token) {
|
||||
this.lastError = '로그인이 필요합니다';
|
||||
this.emit('unauthorized');
|
||||
return;
|
||||
}
|
||||
const url = this.opts.serverUrl().replace(/\/$/, '').replace(/^http/, 'ws') + '/app/bot/ws';
|
||||
const ws = new WebSocket(url, { headers: { authorization: `Bearer ${token}`, 'x-gvr-version': this.opts.version }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024 });
|
||||
this.ws = ws;
|
||||
let unauthorized = false;
|
||||
let alive = Date.now();
|
||||
const ping = setInterval(() => {
|
||||
// 서버가 30초마다 ping 을 보낸다. 75초 동안 아무것도 없으면 끊고 다시 붙는다
|
||||
if (Date.now() - alive > 75000) ws.terminate();
|
||||
}, 15000);
|
||||
ws.on('ping', () => (alive = Date.now()));
|
||||
ws.on('open', () => {
|
||||
this.retries = 0;
|
||||
alive = Date.now();
|
||||
log.info('사이트 서버 겜녹이 봇 중계 연결됨');
|
||||
});
|
||||
ws.on('message', (data) => {
|
||||
alive = Date.now();
|
||||
let m: BotGwToApp;
|
||||
try {
|
||||
m = JSON.parse(String(data));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
this.onMessage(m);
|
||||
});
|
||||
ws.on('unexpected-response', (_req, res) => {
|
||||
unauthorized = res.statusCode === 401;
|
||||
this.lastError = unauthorized ? '로그인이 만료되었습니다. 다시 로그인해 주세요' : res.statusCode === 503 ? '사이트 서버에 겜녹이 봇이 켜져 있지 않습니다' : `사이트 서버 응답 ${res.statusCode}`;
|
||||
});
|
||||
ws.on('error', (e) => {
|
||||
this.lastError ||= `사이트 서버에 연결할 수 없습니다 (${e.message})`;
|
||||
});
|
||||
ws.on('close', (code) => {
|
||||
clearInterval(ping);
|
||||
if (this.ws !== ws) return;
|
||||
this.ws = null;
|
||||
const wasReady = !!this._me;
|
||||
this.reset();
|
||||
if (wasReady) this.emit('down');
|
||||
if (unauthorized || code === 4401) {
|
||||
this.lastError = '로그인이 만료되었거나 등록이 해제되었습니다';
|
||||
this.emit('unauthorized');
|
||||
}
|
||||
if (this.stopped) return;
|
||||
const delay = Math.min(30000, 1000 * 2 ** Math.min(this.retries++, 5));
|
||||
this.retryTimer = setTimeout(() => this.connect(), delay);
|
||||
});
|
||||
}
|
||||
|
||||
private send(m: BotGwFromApp): boolean {
|
||||
if (this.ws?.readyState !== WebSocket.OPEN) return false;
|
||||
this.ws.send(JSON.stringify(m));
|
||||
return true;
|
||||
}
|
||||
|
||||
private remember(m: GMember): void {
|
||||
this.known.set(m.id, m);
|
||||
}
|
||||
|
||||
private onMessage(m: BotGwToApp): void {
|
||||
switch (m.t) {
|
||||
case 'ready':
|
||||
this.lastError = null;
|
||||
this._me = m.me;
|
||||
this._guilds = m.guilds;
|
||||
this.emit('ready');
|
||||
return;
|
||||
case 'guilds':
|
||||
this._guilds = m.guilds;
|
||||
this.emit('guilds');
|
||||
return;
|
||||
case 'guild':
|
||||
if (this.watched?.id !== m.guild.id) return;
|
||||
this.channels.clear();
|
||||
this.voice.clear();
|
||||
for (const c of m.channels) this.channels.set(c.id, c);
|
||||
for (const v of m.voice) {
|
||||
this.remember(v.member);
|
||||
this.voice.set(v.member.id, v.channelId);
|
||||
}
|
||||
this.wait?.resolve(m.guild);
|
||||
this.wait = null;
|
||||
return;
|
||||
case 'voiceState':
|
||||
if (this.watched?.id !== m.guildId) return;
|
||||
this.remember(m.member);
|
||||
if (m.channel) this.channels.set(m.channel.id, m.channel);
|
||||
if (m.newChannelId) this.voice.set(m.member.id, m.newChannelId);
|
||||
else this.voice.delete(m.member.id);
|
||||
this.emit('voiceState', { guildId: m.guildId, member: m.member, oldChannelId: m.oldChannelId, newChannelId: m.newChannelId, channel: m.channel } satisfies GVoiceEvent);
|
||||
return;
|
||||
case 'cmd': {
|
||||
this.remember(m.user);
|
||||
const cmd: GCommand = { name: m.name, guildId: m.guildId, user: m.user, voiceChannel: m.voiceChannel };
|
||||
this.emit('command', cmd, (content: string) => void this.send({ t: 'cmd_res', id: m.id, content }));
|
||||
return;
|
||||
}
|
||||
case 'vserver':
|
||||
this.adapters.get(m.guildId)?.onVoiceServerUpdate(m.data);
|
||||
return;
|
||||
case 'vstate':
|
||||
this.adapters.get(m.guildId)?.onVoiceStateUpdate(m.data);
|
||||
return;
|
||||
case 'taken':
|
||||
this.emit('taken', m.guildId);
|
||||
return;
|
||||
case 'res': {
|
||||
const r = this.reqs.get(m.id);
|
||||
if (!r) return;
|
||||
this.reqs.delete(m.id);
|
||||
if (m.ok) r.resolve(m.data);
|
||||
else r.reject(new Error(m.error || '요청 실패'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
me(): GMember | null {
|
||||
return this._me;
|
||||
}
|
||||
guilds(): GGuild[] {
|
||||
return this._me ? this._guilds : [];
|
||||
}
|
||||
watch(guildId: string, opts: { commands: boolean }): Promise<GGuild | null> {
|
||||
this.watched = { id: guildId, ...opts };
|
||||
this.wait?.resolve(null);
|
||||
return new Promise((resolve) => {
|
||||
if (!this.send({ t: 'watch', guildId, commands: opts.commands })) return resolve(null);
|
||||
const t = setTimeout(() => {
|
||||
if (this.wait?.resolve === done) this.wait = null;
|
||||
resolve(null);
|
||||
}, 10000);
|
||||
const done = (g: GGuild | null) => {
|
||||
clearTimeout(t);
|
||||
resolve(g);
|
||||
};
|
||||
this.wait = { resolve: done };
|
||||
});
|
||||
}
|
||||
voiceChannelOf(_guildId: string, userId: string): GChannel | null {
|
||||
const id = this.voice.get(userId);
|
||||
return id ? (this.channels.get(id) ?? { id, name: id }) : null;
|
||||
}
|
||||
channel(_guildId: string, channelId: string): GChannel | null {
|
||||
return this.channels.get(channelId) ?? null;
|
||||
}
|
||||
channelMembers(_guildId: string, channelId: string): GMember[] {
|
||||
const out: GMember[] = [];
|
||||
for (const [uid, ch] of this.voice) if (ch === channelId) out.push(this.known.get(uid) ?? { id: uid, name: uid, avatar: null, bot: false });
|
||||
return out;
|
||||
}
|
||||
members(guildId: string): Promise<GMember[]> {
|
||||
const id = String(++this.seq);
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!this.send({ t: 'req', id, op: 'members', guildId })) return reject(new Error('사이트 서버에 연결되어 있지 않습니다'));
|
||||
const t = setTimeout(() => {
|
||||
if (this.reqs.delete(id)) reject(new Error('사이트 서버 응답 없음'));
|
||||
}, 20000);
|
||||
this.reqs.set(id, {
|
||||
resolve: (v) => {
|
||||
clearTimeout(t);
|
||||
for (const m of v as GMember[]) this.remember(m);
|
||||
resolve(v);
|
||||
},
|
||||
reject: (e) => {
|
||||
clearTimeout(t);
|
||||
reject(e);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
isBot(userId: string): boolean {
|
||||
return !!this.known.get(userId)?.bot;
|
||||
}
|
||||
adapterCreator(guildId: string): DiscordGatewayAdapterCreator {
|
||||
return (methods) => {
|
||||
this.adapters.set(guildId, methods);
|
||||
return {
|
||||
sendPayload: (payload) => this.send({ t: 'voice', guildId, payload }),
|
||||
destroy: () => {
|
||||
if (this.adapters.get(guildId) === methods) this.adapters.delete(guildId);
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { buildApi } from './api/server.js';
|
||||
import { Store } from './db/db.js';
|
||||
import { Dictionary } from './dict/dictionary.js';
|
||||
import { Bot } from './discord/bot.js';
|
||||
import { LocalGateway, RemoteGateway } from './discord/gateway.js';
|
||||
import { Recorder } from './discord/recorder.js';
|
||||
import { Announcer } from './discord/tts.js';
|
||||
import { GameAssets } from './games/assets.js';
|
||||
@@ -30,6 +31,8 @@ export interface CoreOptions {
|
||||
settings?: SettingsStore;
|
||||
/** 로컬 API 를 127.0.0.1 포트로도 연다 (설정 창·디버그용). 0 이면 열지 않음 */
|
||||
apiPort?: number;
|
||||
/** 겜녹이 봇 중계에서 로그인 만료 · 등록 해제를 알려 왔을 때 (Electron: 바로 다시 확인해서 잠근다) */
|
||||
onBotUnauthorized?: () => void;
|
||||
}
|
||||
|
||||
export type Core = Awaited<ReturnType<typeof startCore>>;
|
||||
@@ -65,7 +68,7 @@ export async function startCore(opts: CoreOptions) {
|
||||
const u = store.getUser(uid);
|
||||
if (u?.excluded) return true;
|
||||
// 다른 봇(음악봇 등)은 녹음하지 않는다. 자동 테스트에서만 GVR_RECORD_BOTS=1 로 연다.
|
||||
return process.env.GVR_RECORD_BOTS !== '1' && !!bot.client?.users.cache.get(uid)?.bot;
|
||||
return process.env.GVR_RECORD_BOTS !== '1' && bot.isBot(uid);
|
||||
},
|
||||
matchAt: (ts) => games.liveMatchAt(ts),
|
||||
});
|
||||
@@ -112,16 +115,27 @@ export async function startCore(opts: CoreOptions) {
|
||||
relay.start();
|
||||
if (opts.apiPort) await api.listen({ host: '127.0.0.1', port: opts.apiPort });
|
||||
|
||||
// 겜녹이 봇: 봇 토큰은 사이트 서버에만 있다. 앱 로그인 토큰으로 서버 중계에 붙는다.
|
||||
// 다른 봇: 사용자가 넣은 토큰으로 이 PC 가 직접 연결 (개발용 GVR_BOT_TOKEN 도 여기)
|
||||
const startBot = async () => {
|
||||
const token = settings.activeBotToken();
|
||||
if (!token) {
|
||||
log.warn(S().discord.botMode === 'builtin' ? '이 빌드에는 겜녹이 기본 봇이 없습니다. 설정에서 다른 봇 토큰을 넣어 주세요.' : '봇 토큰이 없습니다. 설정에서 입력해 주세요.');
|
||||
let gw;
|
||||
if (token) gw = new LocalGateway(token);
|
||||
else if (S().discord.botMode === 'builtin') {
|
||||
if (!settings.getSecret('appToken')) {
|
||||
log.warn('로그인하지 않아 겜녹이 봇에 연결하지 않습니다');
|
||||
return;
|
||||
}
|
||||
gw = new RemoteGateway({ serverUrl: () => S().site.serverUrl, appToken: () => settings.getSecret('appToken') ?? null, version: opts.version });
|
||||
gw.on('unauthorized', () => opts.onBotUnauthorized?.());
|
||||
} else {
|
||||
log.warn('봇 토큰이 없습니다. 설정에서 입력해 주세요.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await bot.start(token);
|
||||
await bot.start(gw);
|
||||
} catch (e: any) {
|
||||
log.error(`봇 로그인 실패: ${e.message}`);
|
||||
log.error(`봇 연결 실패: ${e.message}`);
|
||||
}
|
||||
};
|
||||
await startBot();
|
||||
|
||||
@@ -71,7 +71,7 @@ export interface Secrets {
|
||||
riotApiKey?: string;
|
||||
/** 앱 로그인 토큰 (사이트 서버가 발급) */
|
||||
appToken?: string;
|
||||
/** 겜녹이 기본 봇 토큰. exe 에 들어 있지 않고, 로그인한 등록 유저에게 사이트 서버가 내려준다 */
|
||||
/** v1.2.0 이 받아 두던 겜녹이 봇 토큰. 이제 쓰지 않고 시작할 때 지운다 */
|
||||
builtinBotToken?: string;
|
||||
/** 마지막으로 서버에서 확인한 로그인 정보 (서버에 잠깐 못 붙을 때 쓰는 사본) */
|
||||
auth?: { user: AppUserInfo; role: AppRole; verifiedAt: number };
|
||||
@@ -180,16 +180,18 @@ export class SettingsStore {
|
||||
if (saved && !saved.discord?.botMode && this.secrets.botToken) this.cur.discord.botMode = 'custom';
|
||||
// 개발/헤드리스: 환경변수 토큰이 있으면 모드와 상관없이 그것을 쓴다
|
||||
this.envBotToken = process.env.GVR_BOT_TOKEN || null;
|
||||
// v1.2.0 은 서버에서 받은 겜녹이 봇 토큰을 저장해 두었다. 이제는 서버가 봇을 대신 연결하므로 남기지 않는다
|
||||
if (this.secrets.builtinBotToken) this.setSecret('builtinBotToken', null);
|
||||
}
|
||||
|
||||
/** 겜녹이 기본 봇 토큰을 받아 두었는지 (로그인하면 사이트 서버가 내려준다) */
|
||||
/** 겜녹이 봇을 쓸 수 있는지 (로그인해 있으면 사이트 서버 중계로 연결한다. 봇 토큰은 이 PC 에 오지 않는다) */
|
||||
get hasBuiltinBot(): boolean {
|
||||
return !!this.secrets.builtinBotToken;
|
||||
return !!this.secrets.appToken;
|
||||
}
|
||||
/** 지금 모드에서 봇이 로그인할 토큰 (없으면 null) */
|
||||
/** 이 PC 가 직접 로그인할 봇 토큰: 다른 봇 모드의 토큰 또는 개발용 GVR_BOT_TOKEN (겜녹이 봇은 null) */
|
||||
activeBotToken(): string | null {
|
||||
if (this.envBotToken) return this.envBotToken;
|
||||
return (this.cur.discord.botMode === 'builtin' ? this.secrets.builtinBotToken : this.secrets.botToken) || null;
|
||||
return this.cur.discord.botMode === 'custom' ? this.secrets.botToken || null : null;
|
||||
}
|
||||
|
||||
get(): Settings {
|
||||
|
||||
@@ -87,7 +87,17 @@ export function registerIpc(ctx: IpcContext) {
|
||||
|
||||
testBotToken: async (token?: string) => {
|
||||
const t = token || core.settings.activeBotToken();
|
||||
if (!t) return { ok: false, error: core.settings.get().discord.botMode === 'builtin' ? '이 빌드에는 겜녹이 봇이 들어 있지 않습니다. 다른 봇으로 진행해 주세요' : '봇 토큰을 입력해 주세요' };
|
||||
// 겜녹이 봇은 토큰이 이 PC 에 없다: 사이트 서버 중계로 붙어 보고 결과를 알려 준다
|
||||
if (!t && core.settings.get().discord.botMode === 'builtin') {
|
||||
const b = core.bot;
|
||||
if (b.state.status !== 'ready' || b.gateway?.kind !== 'remote') {
|
||||
await b.stop();
|
||||
await core.startBot();
|
||||
}
|
||||
if (b.state.status !== 'ready' || !b.state.user) return { ok: false, error: b.state.error ?? '사이트 서버의 겜녹이 봇에 연결하지 못했습니다' };
|
||||
return { ok: true, bot: b.state.user, guilds: b.state.guilds };
|
||||
}
|
||||
if (!t) return { ok: false, error: '봇 토큰을 입력해 주세요' };
|
||||
const get = (p: string) => fetch(`https://discord.com/api/v10${p}`, { headers: { authorization: `Bot ${t}` } });
|
||||
try {
|
||||
const me = await get('/users/@me');
|
||||
@@ -110,10 +120,8 @@ export function registerIpc(ctx: IpcContext) {
|
||||
return core.bot.state.status === 'ready' || core.bot.state.status === 'connecting' ? { ok: true } : { ok: false, error: core.bot.state.error ?? '봇을 시작하지 못했습니다' };
|
||||
},
|
||||
guildMembers: async () => {
|
||||
const g = core.bot.guild();
|
||||
if (!g) return [];
|
||||
const ms = await g.members.fetch().catch(() => g.members.cache);
|
||||
return [...ms.values()].map((m) => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 64 }), bot: m.user.bot })).sort((a, b) => a.name.localeCompare(b.name, 'ko'));
|
||||
const ms = await core.bot.members().catch(() => []);
|
||||
return ms.map((m) => ({ id: m.id, name: m.name, avatar: m.avatar, bot: m.bot })).sort((a, b) => a.name.localeCompare(b.name, 'ko'));
|
||||
},
|
||||
previewTts: async (text: string, voice: string) => {
|
||||
try {
|
||||
|
||||
@@ -204,17 +204,15 @@ const refreshShell = () => {
|
||||
};
|
||||
|
||||
let starting: Promise<void> | null = null;
|
||||
/** 서버에서 받은 겜녹이 봇 토큰. 서버에서 바뀌면 봇을 다시 연결한다 */
|
||||
let builtinSeen: string | null = null;
|
||||
|
||||
/** 로그인 확인 후 코어 시작 */
|
||||
function startApp(): Promise<void> {
|
||||
if (core) return Promise.resolve();
|
||||
starting ??= (async () => {
|
||||
try {
|
||||
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings! });
|
||||
// 겜녹이 봇 중계가 로그인 만료 · 등록 해제를 알려 오면 10분을 기다리지 않고 바로 확인해서 잠근다
|
||||
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings!, onBotUnauthorized: () => void auth?.check() });
|
||||
core = c;
|
||||
builtinSeen = c.settings.getSecret('builtinBotToken') ?? null;
|
||||
ft = new Finetuner(c, pushState);
|
||||
ft.scheduleNightly();
|
||||
appError = null;
|
||||
@@ -253,15 +251,6 @@ function onAuthChange(): void {
|
||||
const st = auth!.state.status;
|
||||
if (st === 'ok') {
|
||||
if (!core) return startApp();
|
||||
const t = core.settings.getSecret('builtinBotToken') ?? null;
|
||||
if (t !== builtinSeen) {
|
||||
builtinSeen = t;
|
||||
if (core.settings.get().discord.botMode === 'builtin') {
|
||||
log.info('서버에서 받은 겜녹이 봇 토큰이 바뀌어 봇을 다시 연결합니다');
|
||||
await core.bot.stop();
|
||||
await core.startBot();
|
||||
}
|
||||
}
|
||||
} else if (st !== 'checking' && st !== 'waiting') {
|
||||
await stopApp();
|
||||
openWindow();
|
||||
|
||||
@@ -111,7 +111,7 @@ export function BotTokenSection({ wizard, onResult }: { wizard?: boolean; onResu
|
||||
<div className="radio">
|
||||
<button type="button" className={!custom ? 'on' : ''} disabled={saver.busy || (!admin && custom)} onClick={() => switchMode('builtin')}>
|
||||
<b>🤖 겜녹이 봇으로 진행 {!custom && '✓'}</b>
|
||||
<span className="muted">{state.builtinBot ? '기본값 · 토큰 입력 없이 바로 연결' : '겜녹이 봇 토큰을 아직 받지 못했습니다 (사이트 서버 연결 확인)'}</span>
|
||||
<span className="muted">{state.builtinBot ? '기본값 · 사이트 서버를 거쳐 바로 연결' : '로그인해야 쓸 수 있습니다'}</span>
|
||||
</button>
|
||||
<button type="button" className={custom ? 'on' : ''} disabled={saver.busy || !admin} onClick={() => switchMode('custom')} title={admin ? undefined : '관리자만 바꿀 수 있습니다'}>
|
||||
<b>🔑 다른 봇으로 진행하기 {custom && '✓'}</b>
|
||||
|
||||
@@ -65,7 +65,7 @@ async function stack() {
|
||||
return { base, browser, settingsFor, close: async () => (await app.close(), dc.close()) };
|
||||
}
|
||||
|
||||
test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은 로그인 후 서버에서 받는다', async () => {
|
||||
test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은 로그인해도 앱에 오지 않는다', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
// 로그인 전: 토큰 없음 → 로그인 화면
|
||||
@@ -81,13 +81,16 @@ test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은
|
||||
assert.equal(st.hasSecret('appToken'), false);
|
||||
assert.equal(st.activeBotToken(), null);
|
||||
|
||||
// 최고 관리자 로그인 → 봇 토큰 받음
|
||||
// 최고 관리자 로그인 → 앱 토큰만 받는다. 봇 토큰은 서버 응답 어디에도 없다
|
||||
const adminSt = s.settingsFor();
|
||||
const admin = new AppAuth(adminSt, { version: '1.2.0', openUrl: s.browser(SUPER), pollMs: 20 });
|
||||
const r2 = await admin.login();
|
||||
assert.equal(r2.status, 'ok');
|
||||
assert.equal(r2.role, 'superadmin');
|
||||
assert.equal(adminSt.activeBotToken(), BOT);
|
||||
assert.equal(adminSt.hasBuiltinBot, true);
|
||||
assert.equal(adminSt.activeBotToken(), null);
|
||||
const me = await (await fetch(`${s.base}/app/me`, { headers: { authorization: `Bearer ${adminSt.getSecret('appToken')}` } })).text();
|
||||
assert.ok(me.includes(SUPER) && !me.includes(BOT) && !me.includes('botToken'), me);
|
||||
|
||||
// 최고 관리자가 친구 등록 (관리자 화면 API)
|
||||
const list = await admin.adminAddUser(FRIEND, 'user');
|
||||
@@ -100,26 +103,27 @@ test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은
|
||||
const r3 = await fr.login();
|
||||
assert.equal(r3.status, 'ok');
|
||||
assert.equal(r3.role, 'user');
|
||||
assert.equal(frSt.activeBotToken(), BOT);
|
||||
assert.equal(frSt.activeBotToken(), null);
|
||||
await assert.rejects(fr.adminAddUser(STRANGER, 'user'), /최고 관리자만/);
|
||||
await assert.rejects(fr.adminUsers(), /관리자만/);
|
||||
// 다시 켜도 (새 SettingsStore) 로그인 유지
|
||||
assert.equal((await new AppAuth(s.settingsFor(dir), { version: '1.2.0', openUrl: () => undefined }).check()).status, 'ok');
|
||||
// 토큰 · 봇 토큰은 평문 settings.json 에 없다
|
||||
assert.ok(!fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes(BOT));
|
||||
// 봇 토큰은 이 PC 어디에도 저장되지 않는다 (테스트는 평문 codec 이라 secrets.bin 도 그대로 읽힌다)
|
||||
for (const f of fs.readdirSync(dir)) assert.ok(!fs.readFileSync(path.join(dir, f), 'utf8').includes(BOT), f);
|
||||
|
||||
// 등록 해제 → 다음 확인에서 잠기고 받아 둔 봇 토큰도 지운다
|
||||
// 등록 해제 → 다음 확인에서 잠기고 앱 토큰을 지운다
|
||||
await admin.adminRemoveUser(FRIEND);
|
||||
const r4 = await fr.check();
|
||||
assert.equal(r4.status, 'not_registered');
|
||||
assert.equal(r4.user?.id, FRIEND);
|
||||
assert.equal((await fr.check()).status, 'not_registered', '다시 확인해도 "등록되지 않은 아이디" 화면 유지');
|
||||
assert.equal(frSt.activeBotToken(), null);
|
||||
assert.equal(frSt.hasSecret('appToken'), false);
|
||||
|
||||
// 로그아웃 → 토큰 · 봇 토큰 삭제, 서버에서도 무효
|
||||
// 로그아웃 → 토큰 삭제, 서버에서도 무효
|
||||
await admin.logout();
|
||||
assert.equal(admin.state.status, 'signed_out');
|
||||
assert.equal(adminSt.activeBotToken(), null);
|
||||
assert.equal(adminSt.hasBuiltinBot, false);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
@@ -136,7 +140,7 @@ test('앱 로그인: 서버에 못 붙으면 마지막 확인 후 유예 기간
|
||||
const r = await auth.check();
|
||||
assert.equal(r.status, 'ok');
|
||||
assert.equal(r.offline, true);
|
||||
assert.equal(st.activeBotToken(), BOT);
|
||||
assert.equal(st.hasSecret('appToken'), true);
|
||||
// 유예 기간이 지나면 막힌다 (토큰은 남겨 두어 서버가 돌아오면 다시 확인)
|
||||
const late = new AppAuth(st, { version: '1.2.0', openUrl: () => undefined, offlineGraceMs: 0 });
|
||||
const r2 = await late.check();
|
||||
@@ -197,13 +201,12 @@ test('늦은 확인 응답: 등록 해제로 잠긴 뒤 이전 확인의 200 이
|
||||
// 그 사이 등록 해제 → B: 403 → 잠김
|
||||
await admin.adminRemoveUser(FRIEND);
|
||||
assert.equal((await fr.check()).status, 'not_registered');
|
||||
assert.equal(st.activeBotToken(), null);
|
||||
// A 의 늦은 200 도착
|
||||
release();
|
||||
await a;
|
||||
assert.equal(fr.state.status, 'not_registered', '늦은 200 이 잠금을 풀면 안 된다');
|
||||
assert.equal(st.activeBotToken(), null, '지운 봇 토큰이 되살아나면 안 된다');
|
||||
assert.equal(st.hasSecret('appToken'), false);
|
||||
assert.equal(st.hasSecret('appToken'), false, '지운 앱 토큰이 되살아나면 안 된다');
|
||||
assert.equal(st.hasSecret('auth'), false);
|
||||
} finally {
|
||||
h.restore();
|
||||
await s.close();
|
||||
@@ -225,10 +228,28 @@ test('늦은 확인 응답: 로그아웃 뒤 이전 확인의 200 이 와도 다
|
||||
release();
|
||||
await a;
|
||||
assert.equal(auth.state.status, 'signed_out', '늦은 200 이 로그아웃을 되돌리면 안 된다');
|
||||
assert.equal(st.activeBotToken(), null);
|
||||
assert.equal(st.hasSecret('appToken'), false);
|
||||
assert.equal(st.hasSecret('auth'), false);
|
||||
} finally {
|
||||
h.restore();
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('겹친 확인: 등록 해제 뒤 확인 두 개가 겹쳐도 "로그인 만료"가 아니라 "등록되지 않은 아이디"로 잠긴다', async () => {
|
||||
// 봇 중계가 끊기며 바로 확인하는 사이 10분 확인 · 다시 확인 버튼이 겹치는 경우. 서버는 첫 403 에서 세션을 지워 뒤 확인은 401 을 받는다
|
||||
const s = await stack();
|
||||
try {
|
||||
const admin = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(SUPER), pollMs: 20 });
|
||||
await admin.login();
|
||||
await admin.adminAddUser(FRIEND, 'user');
|
||||
const fr = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(FRIEND), pollMs: 20 });
|
||||
assert.equal((await fr.login()).status, 'ok');
|
||||
await admin.adminRemoveUser(FRIEND);
|
||||
await Promise.all([fr.check(), fr.check()]);
|
||||
assert.equal(fr.state.status, 'not_registered');
|
||||
assert.equal(fr.state.user?.id, FRIEND);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
309
app/test/bot-gateway.test.ts
Normal file
309
app/test/bot-gateway.test.ts
Normal file
@@ -0,0 +1,309 @@
|
||||
// 겜녹이 봇 중계: 앱 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 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[] = [];
|
||||
me() {
|
||||
return ME;
|
||||
}
|
||||
guilds(): BotGwGuild[] {
|
||||
return [
|
||||
{ id: G, name: 'M&L', icon: null },
|
||||
{ id: OTHER_G, name: '다른 서버', icon: null },
|
||||
];
|
||||
}
|
||||
snapshot(guildId: string) {
|
||||
const g = this.guilds().find((x) => x.id === guildId);
|
||||
if (!g) return null;
|
||||
const channels: BotGwChannel[] = [
|
||||
{ id: VC1, name: '일반' },
|
||||
{ id: VC2, name: '게임' },
|
||||
];
|
||||
return { guild: g, channels, voice: [{ member: m(SUPER, '관리자'), channelId: VC1 }] };
|
||||
}
|
||||
isVoiceChannel(guildId: string, channelId: string) {
|
||||
return guildId === G && (channelId === VC1 || channelId === VC2);
|
||||
}
|
||||
async members() {
|
||||
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]);
|
||||
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.equal(await cmd('녹음시작', SUPER), '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다.');
|
||||
await a.gw.start();
|
||||
await b.gw.start();
|
||||
await a.gw.watch(G, { commands: 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();
|
||||
}
|
||||
});
|
||||
@@ -7,13 +7,14 @@ import { SettingsStore } from '../src/core/settings.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-bot-'));
|
||||
const BUILTIN = 'MTExMTExMTExMTExMTExMTEx.FAKE00.builtin-token-for-tests-only-xxxxxxxx';
|
||||
const APP = 'app-login-token-for-tests';
|
||||
const OTHER = 'OTE4MTIzMzQ4NzIxMDA4NzAw.FAKE11.other-bot-token-for-tests-only-yyyy';
|
||||
delete process.env.GVR_BOT_TOKEN;
|
||||
|
||||
/** 로그인해서 서버가 겜녹이 봇 토큰을 내려준 상태 */
|
||||
/** 로그인한 상태 (앱 토큰만 있다. 겜녹이 봇 토큰은 서버에만 있다) */
|
||||
const loggedIn = (dir = tmp()) => {
|
||||
const s = new SettingsStore(dir);
|
||||
s.setSecret('builtinBotToken', BUILTIN);
|
||||
s.setSecret('appToken', APP);
|
||||
return s;
|
||||
};
|
||||
|
||||
@@ -24,10 +25,19 @@ test('로그인 전: 겜녹이 봇 토큰이 없다 (exe 에 들어 있지 않
|
||||
assert.equal(s.activeBotToken(), null);
|
||||
});
|
||||
|
||||
test('로그인 후: 겜녹이 봇이 기본이고 서버에서 받은 토큰을 쓴다', () => {
|
||||
test('로그인 후: 겜녹이 봇이 기본이고, 이 PC 가 직접 로그인할 봇 토큰은 없다 (서버 중계)', () => {
|
||||
const s = loggedIn();
|
||||
assert.equal(s.hasBuiltinBot, true);
|
||||
assert.equal(s.activeBotToken(), BUILTIN);
|
||||
assert.equal(s.activeBotToken(), null);
|
||||
});
|
||||
|
||||
test('v1.2.0 이 받아 둔 겜녹이 봇 토큰은 시작할 때 지운다', () => {
|
||||
const dir = tmp();
|
||||
loggedIn(dir).setSecret('builtinBotToken', BUILTIN);
|
||||
const s = new SettingsStore(dir);
|
||||
assert.equal(s.hasSecret('builtinBotToken'), false);
|
||||
assert.ok(!fs.readFileSync(path.join(dir, 'secrets.bin'), 'utf8').includes(BUILTIN));
|
||||
assert.equal(s.activeBotToken(), null);
|
||||
});
|
||||
|
||||
test('다른 봇으로 진행하기: 넣은 토큰을 쓰고, 다시 겜녹이 봇으로 오가도 각자 유지된다', () => {
|
||||
@@ -39,7 +49,7 @@ test('다른 봇으로 진행하기: 넣은 토큰을 쓰고, 다시 겜녹이
|
||||
assert.equal(s.activeBotToken(), OTHER);
|
||||
|
||||
s.update({ discord: { botMode: 'builtin' } });
|
||||
assert.equal(s.activeBotToken(), BUILTIN);
|
||||
assert.equal(s.activeBotToken(), null);
|
||||
s.update({ discord: { botMode: 'custom' } });
|
||||
assert.equal(s.activeBotToken(), OTHER, '저장한 다른 봇 토큰은 지워지지 않는다');
|
||||
|
||||
@@ -48,7 +58,7 @@ test('다른 봇으로 진행하기: 넣은 토큰을 쓰고, 다시 겜녹이
|
||||
assert.equal(again.get().discord.botMode, 'custom');
|
||||
assert.equal(again.activeBotToken(), OTHER);
|
||||
// 평문 설정 파일(settings.json)에는 토큰이 들어가지 않는다
|
||||
assert.ok(!fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes(BUILTIN));
|
||||
assert.ok(!fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes(OTHER));
|
||||
});
|
||||
|
||||
test('v1.0.0 에서 직접 토큰을 넣어 쓰던 설치는 다른 봇 모드로 이어진다', () => {
|
||||
|
||||
@@ -94,7 +94,7 @@ tools/ 사전 생성기, 테스트 도구(목 Riot 서버, 음성
|
||||
GVR-Data/
|
||||
settings.json 일반 설정 (평문)
|
||||
secrets.bin 비밀값 (Windows: Electron safeStorage = DPAPI, 헤드리스: 0600 평문 JSON)
|
||||
앱 로그인 토큰 · 서버가 내려준 겜녹이 봇 토큰 · 마지막 로그인 확인(오프라인 3일 유예용) 포함
|
||||
앱 로그인 토큰 · 마지막 로그인 확인(오프라인 3일 유예용) 포함. 겜녹이 봇 토큰은 없다 (8장)
|
||||
gvr.sqlite 기록 DB
|
||||
audio/YYYY-MM-DD/<utteranceId>.ogg
|
||||
training/<sampleId>.ogg 교정한 문장의 음성 조각 (자동 삭제 제외, A3)
|
||||
@@ -212,8 +212,26 @@ type TimelineItem =
|
||||
| `POST /auth/app/begin` | 앱 로그인 시작 → `{id, secret, url, expiresAt}` (url 을 브라우저로 연다, 10분 유효) |
|
||||
| `GET /auth/app/start/:id` | 브라우저: state 쿠키(`app.<id>.<nonce>`) → 디스코드 OAuth → 같은 `/auth/discord/callback` |
|
||||
| `POST /auth/app/poll` | `{id, secret}` → `{state:'pending'}` · `{state:'ok', token, user, role}` · `{state:'not_registered', user}` (결과는 한 번만) |
|
||||
| `GET /app/me` | `Authorization: Bearer <앱 토큰>` → `{user, role, botToken, serverTime}`. 미등록 403 `not_registered`, 토큰 무효 401. 겜녹이 봇 토큰은 여기서만 내려준다 |
|
||||
| `GET /app/me` | `Authorization: Bearer <앱 토큰>` → `{user, role, serverTime}`. 미등록 403 `not_registered`, 토큰 무효 401 |
|
||||
| `WS /app/bot/ws` | `Authorization: Bearer <앱 토큰>`. 겜녹이 봇 중계 (8장). 토큰 무효 · 미등록 401, 연결 중 등록 해제 · 로그아웃되면 4401 로 끊는다 |
|
||||
| `POST /auth/app/logout` | 앱 토큰 무효화 |
|
||||
| `GET /app/admin/users` | 관리자 이상 → `{users: AppUserRow[]}` (최고 관리자 고정 행 포함) |
|
||||
| `POST /app/admin/users` · `PATCH`/`DELETE /app/admin/users/:id` | 최고 관리자만: 등록(`{id, role:'admin'|'user'}`, 디스코드에서 계정 확인) · 역할 변경 · 등록 해제 |
|
||||
| `GET /game-assets/<source>/<path>` | valorant-api.com · ddragon · cdragon 이미지 캐시 프록시 |
|
||||
|
||||
## 8. 겜녹이 봇 중계 (v1.2.1~)
|
||||
|
||||
겜녹이 봇 토큰은 사이트 서버에만 있다 (앱에 보내지 않는다). 서버가 discord.js 로 디스코드 게이트웨이에 한 번 붙고
|
||||
(`site/server/src/discord-source.ts`), 로그인한 앱은 `WS /app/bot/ws` 로 필요한 정보만 받는다 (`site/server/src/bot-broker.ts`,
|
||||
앱 쪽 `app/src/core/discord/gateway.ts` 의 `RemoteGateway`. 다른 봇 모드는 `LocalGateway` 로 PC 가 직접 연결). 형식은 `packages/shared` 의 `BotGw*`.
|
||||
|
||||
- 서버 → 앱: `ready{me, guilds}` · `guilds` · `guild{guild, channels, voice}`(watch 응답) · `voiceState`(지켜보는 서버만) · `cmd`(슬래시 명령) ·
|
||||
`vserver`/`vstate`(봇 자신의 VOICE_SERVER/STATE_UPDATE 원문 = 일회용 음성 접속 정보) · `taken` · `res`
|
||||
- 앱 → 서버: `watch{guildId, commands}` · `voice{guildId, payload}`(@discordjs/voice 어댑터의 op 4) · `cmd_res{id, content}` · `req{op:'members'}`
|
||||
- 음성채널 참여: 앱의 @discordjs/voice 가 어댑터로 op 4 를 보내면 서버가 검사(지켜보는 서버 · 음성채널 · op 4 만, 필드를 다시 만들어)한 뒤 대신 보내고,
|
||||
디스코드가 준 session_id · 음성 서버 token · endpoint 를 그 앱에만 넘긴다. 음성(UDP · DAVE)은 앱 ↔ 디스코드 음성 서버로 바로 간다 (Lavalink 와 같은 방식)
|
||||
- 한 서버에서 봇은 음성채널 하나에만 있을 수 있다: 마지막으로 참여를 요청한 앱이 가져가고 이전 앱은 `taken` 을 받는다. 이전 앱의 늦은 나가기는 무시한다.
|
||||
음성을 가진 앱이 끊기면 서버가 봇을 음성채널에서 뺀다
|
||||
- 슬래시 명령: 서버가 받아 바로 defer 하고, 그 서버를 지켜보는 앱에 보낸다 (녹음시작: 명령한 사람의 PC → 녹음 중인 PC → 가장 최근 PC, 녹음종료: 녹음 중인 PC, 녹음제외 · 참여: 모든 PC). 첫 응답을 답장으로 쓴다
|
||||
- 사이트 서버에 못 붙으면 겜녹이 봇은 쓸 수 없다 (다른 봇 모드는 상관없음)
|
||||
|
||||
|
||||
@@ -250,11 +250,10 @@ export type AppLoginPoll =
|
||||
| { state: 'not_registered'; user: AppUserInfo }
|
||||
| { state: 'error'; error: string };
|
||||
|
||||
/** GET /app/me 응답 (등록된 유저만). botToken = 겜녹이 기본 봇 토큰 (서버에서만 내려준다) */
|
||||
/** GET /app/me 응답 (등록된 유저만). 겜녹이 봇 토큰은 내려주지 않는다 (봇은 서버가 대신 연결, 아래 BotGw*) */
|
||||
export interface AppMe {
|
||||
user: AppUserInfo;
|
||||
role: AppRole;
|
||||
botToken: string | null;
|
||||
serverTime: number;
|
||||
}
|
||||
|
||||
@@ -271,3 +270,44 @@ export interface AppUserRow {
|
||||
lastSeenAt: number | null;
|
||||
lastVersion: string | null;
|
||||
}
|
||||
|
||||
// 겜녹이 봇 중계 (사이트 서버 WebSocket /app/bot/ws, Authorization: Bearer <앱 토큰>)
|
||||
// 봇 토큰은 서버에만 있다. 서버가 디스코드 게이트웨이에 붙어 있고, 앱은 필요한 정보만 받는다.
|
||||
// 음성채널에 들어갈 때는 앱의 @discordjs/voice 가 보낸 op 4 를 서버가 대신 보내고,
|
||||
// 디스코드가 준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)를 앱에 넘긴다. 음성은 앱 ↔ 디스코드로 바로 간다.
|
||||
export interface BotGwMember {
|
||||
id: string;
|
||||
name: string;
|
||||
avatar: string | null;
|
||||
bot: boolean;
|
||||
}
|
||||
export interface BotGwGuild {
|
||||
id: string;
|
||||
name: string;
|
||||
icon: string | null;
|
||||
}
|
||||
export interface BotGwChannel {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export type BotGwToApp =
|
||||
| { t: 'ready'; me: BotGwMember; guilds: BotGwGuild[] }
|
||||
| { t: 'guilds'; guilds: BotGwGuild[] }
|
||||
/** watch 응답: 그 서버의 음성채널 · 음성채널에 있는 사람 */
|
||||
| { t: 'guild'; guild: BotGwGuild; channels: BotGwChannel[]; voice: { member: BotGwMember; channelId: string }[] }
|
||||
| { t: 'voiceState'; guildId: string; member: BotGwMember; oldChannelId: string | null; newChannelId: string | null; channel: BotGwChannel | null }
|
||||
| { t: 'cmd'; id: string; name: string; guildId: string; user: BotGwMember; voiceChannel: BotGwChannel | null }
|
||||
/** 음성 접속 정보 (디스코드 VOICE_SERVER_UPDATE / 봇 자신의 VOICE_STATE_UPDATE 원문) */
|
||||
| { t: 'vserver'; guildId: string; data: any }
|
||||
| { t: 'vstate'; guildId: string; data: any }
|
||||
/** 다른 PC 가 이 서버에서 봇을 데려갔다 → 녹음을 멈춘다 */
|
||||
| { t: 'taken'; guildId: string }
|
||||
| { t: 'res'; id: string; ok: boolean; data?: any; error?: string };
|
||||
|
||||
export type BotGwFromApp =
|
||||
| { t: 'watch'; guildId: string; commands: boolean }
|
||||
/** @discordjs/voice 어댑터가 보낸 게이트웨이 op 4 (음성채널 참여 · 나가기) */
|
||||
| { t: 'voice'; guildId: string; payload: any }
|
||||
| { t: 'cmd_res'; id: string; content: string }
|
||||
| { t: 'req'; id: string; op: 'members'; guildId: string };
|
||||
|
||||
231
site/server/package-lock.json
generated
231
site/server/package-lock.json
generated
@@ -10,6 +10,7 @@
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/static": "^8.2.0",
|
||||
"discord.js": "^14.27.0",
|
||||
"fastify": "^5.6.1",
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
@@ -21,6 +22,128 @@
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/builders": {
|
||||
"version": "1.14.1",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",
|
||||
"integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==",
|
||||
"dependencies": {
|
||||
"@discordjs/formatters": "^0.6.2",
|
||||
"@discordjs/util": "^1.2.0",
|
||||
"@sapphire/shapeshift": "^4.0.0",
|
||||
"discord-api-types": "^0.38.40",
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"ts-mixer": "^6.0.4",
|
||||
"tslib": "^2.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.11.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/collection": {
|
||||
"version": "1.5.3",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz",
|
||||
"integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==",
|
||||
"engines": {
|
||||
"node": ">=16.11.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/formatters": {
|
||||
"version": "0.6.2",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz",
|
||||
"integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==",
|
||||
"dependencies": {
|
||||
"discord-api-types": "^0.38.33"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.11.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/rest": {
|
||||
"version": "2.6.3",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz",
|
||||
"integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==",
|
||||
"dependencies": {
|
||||
"@discordjs/collection": "^2.1.1",
|
||||
"@discordjs/util": "^1.2.0",
|
||||
"@sapphire/async-queue": "^1.5.3",
|
||||
"@sapphire/snowflake": "^3.5.5",
|
||||
"@vladfrangu/async_event_emitter": "^2.4.6",
|
||||
"discord-api-types": "^0.38.50",
|
||||
"magic-bytes.js": "^1.13.0",
|
||||
"tslib": "^2.6.3",
|
||||
"undici": "^6.27.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/rest/node_modules/@discordjs/collection": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",
|
||||
"integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/util": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz",
|
||||
"integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==",
|
||||
"dependencies": {
|
||||
"discord-api-types": "^0.38.33"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/ws": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz",
|
||||
"integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==",
|
||||
"dependencies": {
|
||||
"@discordjs/collection": "^2.1.0",
|
||||
"@discordjs/rest": "^2.5.1",
|
||||
"@discordjs/util": "^1.1.0",
|
||||
"@sapphire/async-queue": "^1.5.2",
|
||||
"@types/ws": "^8.5.10",
|
||||
"@vladfrangu/async_event_emitter": "^2.2.4",
|
||||
"discord-api-types": "^0.38.1",
|
||||
"tslib": "^2.6.2",
|
||||
"ws": "^8.17.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.11.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/ws/node_modules/@discordjs/collection": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",
|
||||
"integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
|
||||
@@ -672,11 +795,40 @@
|
||||
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
|
||||
"integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="
|
||||
},
|
||||
"node_modules/@sapphire/async-queue": {
|
||||
"version": "1.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz",
|
||||
"integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==",
|
||||
"engines": {
|
||||
"node": ">=v14.0.0",
|
||||
"npm": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@sapphire/shapeshift": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz",
|
||||
"integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"lodash": "^4.17.21"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=v16"
|
||||
}
|
||||
},
|
||||
"node_modules/@sapphire/snowflake": {
|
||||
"version": "3.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz",
|
||||
"integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==",
|
||||
"engines": {
|
||||
"node": ">=v14.0.0",
|
||||
"npm": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
@@ -685,11 +837,19 @@
|
||||
"version": "8.18.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",
|
||||
"integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@vladfrangu/async_event_emitter": {
|
||||
"version": "2.4.7",
|
||||
"resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz",
|
||||
"integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==",
|
||||
"engines": {
|
||||
"node": ">=v14.0.0",
|
||||
"npm": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/abstract-logging": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",
|
||||
@@ -839,6 +999,37 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/discord-api-types": {
|
||||
"version": "0.38.56",
|
||||
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.56.tgz",
|
||||
"integrity": "sha512-Hti4RZsGvF5C7SM8rF2MDHtIm0Hyfrlk84GpEA29nj91tvVVMvX+oQSCodu10t2ZcjFGofq8TX0YyC04B2E69Q=="
|
||||
},
|
||||
"node_modules/discord.js": {
|
||||
"version": "14.27.0",
|
||||
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.27.0.tgz",
|
||||
"integrity": "sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A==",
|
||||
"dependencies": {
|
||||
"@discordjs/builders": "^1.14.1",
|
||||
"@discordjs/collection": "1.5.3",
|
||||
"@discordjs/formatters": "^0.6.2",
|
||||
"@discordjs/rest": "^2.6.2",
|
||||
"@discordjs/util": "^1.2.0",
|
||||
"@discordjs/ws": "^1.2.3",
|
||||
"@sapphire/snowflake": "3.5.5",
|
||||
"discord-api-types": "^0.38.49",
|
||||
"fast-deep-equal": "3.1.3",
|
||||
"lodash.snakecase": "4.1.1",
|
||||
"magic-bytes.js": "^1.13.0",
|
||||
"tslib": "^2.6.3",
|
||||
"undici": "^6.27.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/discordjs/discord.js?sponsor"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
|
||||
@@ -1156,6 +1347,16 @@
|
||||
"set-cookie-parser": "^3.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
"version": "4.18.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
|
||||
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q=="
|
||||
},
|
||||
"node_modules/lodash.snakecase": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz",
|
||||
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw=="
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "11.5.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
|
||||
@@ -1164,6 +1365,11 @@
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/magic-bytes.js": {
|
||||
"version": "1.13.1",
|
||||
"resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz",
|
||||
"integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw=="
|
||||
},
|
||||
"node_modules/mime": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",
|
||||
@@ -1487,6 +1693,16 @@
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-mixer": {
|
||||
"version": "6.0.4",
|
||||
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",
|
||||
"integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA=="
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="
|
||||
},
|
||||
"node_modules/tsx": {
|
||||
"version": "4.23.15",
|
||||
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz",
|
||||
@@ -1975,11 +2191,18 @@
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "6.29.0",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz",
|
||||
"integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==",
|
||||
"engines": {
|
||||
"node": ">=18.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/static": "^8.2.0",
|
||||
"discord.js": "^14.27.0",
|
||||
"fastify": "^5.6.1",
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
// 2) 브라우저: GET /auth/app/start/:id → 디스코드 OAuth → /auth/discord/callback (사이트 로그인과 같은 콜백, state 가 "app." 으로 시작)
|
||||
// 3) 콜백: 등록된 아이디면 앱 토큰 발급, 아니면 "등록되지 않은 아이디" 결과를 남긴다
|
||||
// 4) 앱: POST /auth/app/poll {id, secret} 로 결과를 받아 간다 (한 번만)
|
||||
// 5) 앱: GET /app/me (Bearer 토큰) 로 주기적으로 확인. 등록 해제되면 403 → 앱이 잠긴다. 겜녹이 봇 토큰은 여기서만 내려준다
|
||||
// 5) 앱: GET /app/me (Bearer 토큰) 로 주기적으로 확인. 등록 해제되면 403 → 앱이 잠긴다
|
||||
// 겜녹이 봇 토큰은 앱에 보내지 않는다. 봇은 서버가 연결하고 앱은 /app/bot/ws 로 중계받는다 (bot-broker.ts)
|
||||
import crypto from 'node:crypto';
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import type { AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared';
|
||||
@@ -24,8 +25,12 @@ interface Pending {
|
||||
|
||||
const sha = (s: string) => crypto.createHash('sha256').update(s).digest();
|
||||
|
||||
export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean }) {
|
||||
export function registerAppAuth(
|
||||
app: FastifyInstance,
|
||||
deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean; onRevoke?: (by: { userId?: string; token?: string }) => void },
|
||||
) {
|
||||
const { cfg, store, discord, secure } = deps;
|
||||
const revoke = (by: { userId?: string; token?: string }) => deps.onRevoke?.(by);
|
||||
const pending = new Map<string, Pending>();
|
||||
|
||||
const roleOf = (id: string): AppRole | null => (cfg.superAdmins.includes(id) ? 'superadmin' : (store.appUser(id)?.role ?? null));
|
||||
@@ -114,6 +119,7 @@ export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store
|
||||
const role = roleOf(s.userId);
|
||||
if (!role) {
|
||||
store.deleteAppSession(token);
|
||||
revoke({ token });
|
||||
reply.code(403).send({ error: 'not_registered', message: '등록되지 않은 아이디입니다', user: userInfo(s.userId) });
|
||||
return null;
|
||||
}
|
||||
@@ -126,12 +132,15 @@ export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store
|
||||
const user = userInfo(a.id);
|
||||
const ver = String(req.headers['x-gvr-version'] || '').slice(0, 20) || null;
|
||||
store.touchAppUser(a.id, { version: ver, name: user.name, avatar: user.avatar });
|
||||
return { user, role: a.role, botToken: cfg.botToken || null, serverTime: Date.now() } satisfies AppMe;
|
||||
return { user, role: a.role, serverTime: Date.now() } satisfies AppMe;
|
||||
});
|
||||
|
||||
app.post('/auth/app/logout', async (req) => {
|
||||
const t = bearer(req);
|
||||
if (t) store.deleteAppSession(t);
|
||||
if (t) {
|
||||
store.deleteAppSession(t);
|
||||
revoke({ token: t });
|
||||
}
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
@@ -203,11 +212,19 @@ export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store
|
||||
if (!a) return;
|
||||
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
|
||||
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
|
||||
revoke({ userId: req.params.id });
|
||||
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
|
||||
return { users: rows() };
|
||||
});
|
||||
|
||||
return { completeLogin };
|
||||
/** 겜녹이 봇 중계 연결 확인: 살아 있는 앱 토큰 + 등록된 아이디 */
|
||||
const verifyToken = (token: string): { userId: string; role: AppRole } | null => {
|
||||
const s = store.appSession(token);
|
||||
const r = s ? roleOf(s.userId) : null;
|
||||
return s && r ? { userId: s.userId, role: r } : null;
|
||||
};
|
||||
|
||||
return { completeLogin, verifyToken };
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
||||
|
||||
@@ -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> {
|
||||
|
||||
240
site/server/src/bot-broker.ts
Normal file
240
site/server/src/bot-broker.ts
Normal file
@@ -0,0 +1,240 @@
|
||||
// 겜녹이 봇 중계. 봇 토큰은 이 서버에만 있고, 앱(exe)에는 절대 보내지 않는다.
|
||||
// - 서버가 디스코드 게이트웨이에 한 번 붙는다 (BotSource). 앱은 /app/bot/ws 로 붙어 필요한 정보만 받는다
|
||||
// - 음성채널 참여: 앱의 @discordjs/voice 어댑터가 보낸 op 4 를 검사해서 서버가 대신 보내고,
|
||||
// 디스코드가 돌려준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)를 그 앱에만 넘긴다.
|
||||
// 음성 데이터는 앱 ↔ 디스코드 음성 서버로 바로 오간다 (이 서버를 거치지 않음)
|
||||
// - 한 디스코드 서버에서 봇은 음성채널 하나에만 있을 수 있다 → 마지막으로 참여를 요청한 앱이 가져가고, 이전 앱에는 taken
|
||||
import crypto from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
import { WebSocket, WebSocketServer } from 'ws';
|
||||
import type { AppRole, BotGwChannel, BotGwFromApp, BotGwGuild, BotGwMember, BotGwToApp } from '@gvr/shared';
|
||||
|
||||
export interface BotVoiceEvent {
|
||||
guildId: string;
|
||||
member: BotGwMember;
|
||||
oldChannelId: string | null;
|
||||
newChannelId: string | null;
|
||||
channel: BotGwChannel | null;
|
||||
}
|
||||
export interface BotCommand {
|
||||
name: string;
|
||||
guildId: string;
|
||||
user: BotGwMember;
|
||||
voiceChannel: BotGwChannel | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 디스코드 게이트웨이 쪽 (실서버: discord-source.ts 의 discord.js, 테스트: 가짜).
|
||||
* 이벤트: 'ready', 'guilds', 'voiceState' (BotVoiceEvent), 'command' (BotCommand, respond(content))
|
||||
*/
|
||||
export interface BotSource extends EventEmitter {
|
||||
me(): BotGwMember | null;
|
||||
guilds(): BotGwGuild[];
|
||||
/** 음성채널 목록과 음성채널에 있는 사람 */
|
||||
snapshot(guildId: string): { guild: BotGwGuild; channels: BotGwChannel[]; voice: { member: BotGwMember; channelId: string }[] } | null;
|
||||
isVoiceChannel(guildId: string, channelId: string): boolean;
|
||||
members(guildId: string): Promise<BotGwMember[]>;
|
||||
registerCommands(guildId: string): Promise<void>;
|
||||
/** 서버마다 하나. 디스코드가 보낸 봇 자신의 음성 접속 정보를 handlers 로 넘기고, send 로 op 4 를 보낸다 */
|
||||
voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }): { send: (payload: any) => boolean };
|
||||
}
|
||||
|
||||
interface Conn {
|
||||
id: string;
|
||||
ws: WebSocket;
|
||||
token: string;
|
||||
userId: string;
|
||||
guildId: string | null;
|
||||
at: number;
|
||||
}
|
||||
|
||||
const CMD_TIMEOUT_MS = 25000;
|
||||
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 adapters = new Map<string, { send: (payload: any) => boolean }>();
|
||||
private commandsDone = new Set<string>();
|
||||
private cmds = new Map<string, (content: string | null) => void>();
|
||||
private timer: NodeJS.Timeout;
|
||||
|
||||
constructor(
|
||||
private source: BotSource,
|
||||
/** 앱 토큰 확인 (등록 해제 · 로그아웃이면 null) */
|
||||
private verify: (token: string) => { userId: string; role: AppRole } | null,
|
||||
private log: { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void },
|
||||
) {
|
||||
source.on('ready', () => {
|
||||
const me = source.me();
|
||||
if (me) for (const c of this.conns) this.send(c, { t: 'ready', me, guilds: source.guilds() });
|
||||
});
|
||||
source.on('guilds', () => this.broadcast({ t: 'guilds', guilds: source.guilds() }));
|
||||
source.on('voiceState', (e: BotVoiceEvent) => {
|
||||
for (const c of this.conns) if (c.guildId === e.guildId) this.send(c, { t: 'voiceState', ...e });
|
||||
});
|
||||
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);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
clearInterval(this.timer);
|
||||
for (const c of this.conns) c.ws.terminate();
|
||||
}
|
||||
|
||||
/** 이 유저(또는 이 토큰)의 연결을 바로 끊는다 */
|
||||
kick(by: { userId?: string; token?: string }): void {
|
||||
for (const c of this.conns) if ((by.userId && c.userId === by.userId) || (by.token && c.token === by.token)) c.ws.close(4401, 'unauthorized');
|
||||
}
|
||||
|
||||
authenticate(req: IncomingMessage): { token: string; userId: string } | null {
|
||||
const token = /^Bearer\s+(\S+)$/i.exec(String(req.headers.authorization || ''))?.[1] ?? '';
|
||||
const a = token ? this.verify(token) : null;
|
||||
return a ? { token, userId: a.userId } : null;
|
||||
}
|
||||
|
||||
attach(ws: WebSocket, a: { token: string; userId: string }): void {
|
||||
const c: Conn = { id: crypto.randomBytes(6).toString('hex'), ws, token: a.token, userId: a.userId, guildId: null, at: Date.now() };
|
||||
this.conns.add(c);
|
||||
this.log.info({ user: a.userId, conn: c.id }, '겜녹이 봇 중계 연결');
|
||||
const me = this.source.me();
|
||||
if (me) this.send(c, { t: 'ready', me, guilds: this.source.guilds() });
|
||||
ws.on('message', (data, isBinary) => {
|
||||
if (isBinary || !this.conns.has(c)) return;
|
||||
let m: BotGwFromApp;
|
||||
try {
|
||||
m = JSON.parse(String(data));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.onMessage(c, m);
|
||||
} catch (e) {
|
||||
this.log.warn(e, '봇 중계 메시지 처리 실패');
|
||||
}
|
||||
});
|
||||
const drop = () => this.drop(c);
|
||||
ws.on('close', drop);
|
||||
ws.on('error', drop);
|
||||
}
|
||||
|
||||
private drop(c: Conn): void {
|
||||
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 } });
|
||||
}
|
||||
}
|
||||
|
||||
private send(c: Conn, m: BotGwToApp): void {
|
||||
if (c.ws.readyState === WebSocket.OPEN) c.ws.send(JSON.stringify(m));
|
||||
}
|
||||
private broadcast(m: BotGwToApp): void {
|
||||
for (const c of this.conns) this.send(c, m);
|
||||
}
|
||||
|
||||
private adapter(guildId: string) {
|
||||
let a = this.adapters.get(guildId);
|
||||
if (!a) {
|
||||
a = this.source.voiceAdapter(guildId, {
|
||||
server: (d) => {
|
||||
const o = this.owners.get(guildId);
|
||||
if (o) this.send(o, { t: 'vserver', guildId, data: d });
|
||||
},
|
||||
state: (d) => {
|
||||
const o = this.owners.get(guildId);
|
||||
if (o) this.send(o, { t: 'vstate', guildId, data: d });
|
||||
},
|
||||
});
|
||||
this.adapters.set(guildId, a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
private onMessage(c: Conn, m: BotGwFromApp): void {
|
||||
switch (m.t) {
|
||||
case 'watch': {
|
||||
const snap = SNOWFLAKE.test(String(m.guildId)) ? this.source.snapshot(m.guildId) : null;
|
||||
if (!snap) return;
|
||||
c.guildId = m.guildId;
|
||||
c.at = Date.now();
|
||||
this.send(c, { t: 'guild', ...snap });
|
||||
if (m.commands && !this.commandsDone.has(m.guildId)) {
|
||||
this.commandsDone.add(m.guildId);
|
||||
this.source.registerCommands(m.guildId).catch((e) => {
|
||||
this.commandsDone.delete(m.guildId);
|
||||
this.log.warn(e, '슬래시 명령 등록 실패');
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'voice': {
|
||||
// 앱이 보낼 수 있는 건 "지켜보는 서버의 음성채널 참여 · 나가기" 뿐이다
|
||||
const g = c.guildId;
|
||||
const d = m.payload?.d;
|
||||
if (!g || m.guildId !== g || m.payload?.op !== 4 || d?.guild_id !== g) return;
|
||||
const ch = d.channel_id === null ? null : String(d.channel_id);
|
||||
if (ch !== null && !this.source.isVoiceChannel(g, ch)) return;
|
||||
const owner = this.owners.get(g);
|
||||
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);
|
||||
}
|
||||
this.adapter(g).send({ op: 4, d: { guild_id: g, channel_id: ch, self_mute: !!d.self_mute, self_deaf: !!d.self_deaf } });
|
||||
return;
|
||||
}
|
||||
case 'cmd_res': {
|
||||
// 여러 PC 로 보낸 명령은 첫 응답만 쓴다
|
||||
this.cmds.get(m.id)?.(String(m.content ?? '').slice(0, 1800));
|
||||
return;
|
||||
}
|
||||
case 'req': {
|
||||
if (m.op !== 'members' || m.guildId !== c.guildId) return this.send(c, { t: 'res', id: m.id, ok: false, error: 'forbidden' });
|
||||
this.source.members(m.guildId).then(
|
||||
(data) => this.send(c, { t: 'res', id: m.id, ok: true, data }),
|
||||
(e) => this.send(c, { t: 'res', id: m.id, ok: false, error: String(e?.message ?? e) }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 슬래시 명령을 맞는 앱으로 보내고 첫 응답을 돌려준다 */
|
||||
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 mine = here.find((c) => c.userId === cmd.user.id);
|
||||
let targets: Conn[];
|
||||
if (cmd.name === '녹음제외' || cmd.name === '녹음참여') targets = here; // 각 PC 기록에 모두 남긴다
|
||||
else if (cmd.name === '녹음종료') targets = owner && here.includes(owner) ? [owner] : [];
|
||||
else targets = [mine ?? (owner && here.includes(owner) ? owner : here[0])];
|
||||
if (!targets.length) return '지금은 녹음 중이 아닙니다.';
|
||||
const id = crypto.randomBytes(8).toString('hex');
|
||||
const content = await new Promise<string | null>((resolve) => {
|
||||
const t = setTimeout(() => resolve(null), CMD_TIMEOUT_MS);
|
||||
this.cmds.set(id, (v) => {
|
||||
clearTimeout(t);
|
||||
this.cmds.delete(id);
|
||||
resolve(v);
|
||||
});
|
||||
for (const c of targets) this.send(c, { t: 'cmd', id, ...cmd });
|
||||
});
|
||||
this.cmds.delete(id);
|
||||
return content ?? '겜녹이 앱이 응답하지 않습니다. 잠시 뒤 다시 시도해 주세요.';
|
||||
}
|
||||
}
|
||||
114
site/server/src/discord-source.ts
Normal file
114
site/server/src/discord-source.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
// 서버의 겜녹이 봇 디스코드 연결 (discord.js). bot-broker.ts 의 BotSource 구현
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
|
||||
import type { BotGwChannel, BotGwGuild, BotGwMember } from '@gvr/shared';
|
||||
import type { BotCommand, BotSource, BotVoiceEvent } from './bot-broker.js';
|
||||
|
||||
/** 앱과 같은 슬래시 명령 (app/src/core/discord/bot.ts COMMANDS) */
|
||||
export const COMMANDS = [
|
||||
{ name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' },
|
||||
{ name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' },
|
||||
{ name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' },
|
||||
{ name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' },
|
||||
];
|
||||
|
||||
const member = (m: GuildMember): BotGwMember => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }), bot: m.user.bot });
|
||||
const guild = (g: Guild): BotGwGuild => ({ id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) });
|
||||
const isVoice = (c: { type: ChannelType } | null | undefined): c is VoiceBasedChannel => !!c && (c.type === ChannelType.GuildVoice || c.type === ChannelType.GuildStageVoice);
|
||||
|
||||
export class DiscordSource extends EventEmitter implements BotSource {
|
||||
readonly client: Client;
|
||||
|
||||
constructor(private log: { info: (o: any, m?: string) => void; error: (o: any, m?: string) => void }) {
|
||||
super();
|
||||
const c = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers] });
|
||||
this.client = c;
|
||||
c.on(Events.ClientReady, () => {
|
||||
log.info({ bot: c.user?.tag, guilds: c.guilds.cache.size }, '겜녹이 봇 디스코드 연결');
|
||||
this.emit('ready');
|
||||
});
|
||||
c.on(Events.GuildCreate, () => this.emit('guilds'));
|
||||
c.on(Events.GuildDelete, () => this.emit('guilds'));
|
||||
c.on(Events.Error, (e) => log.error(e, '디스코드 오류'));
|
||||
c.on(Events.VoiceStateUpdate, (o, n) => {
|
||||
const m = n.member ?? o.member;
|
||||
if (!m) return;
|
||||
const ch = n.channel;
|
||||
const e: BotVoiceEvent = { guildId: n.guild.id, member: member(m), oldChannelId: o.channelId, newChannelId: n.channelId, channel: ch ? { id: ch.id, name: ch.name } : null };
|
||||
this.emit('voiceState', e);
|
||||
});
|
||||
c.on(Events.InteractionCreate, async (i) => {
|
||||
if (!i.isChatInputCommand() || !i.guildId || !COMMANDS.some((x) => x.name === i.commandName)) return;
|
||||
try {
|
||||
await i.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
} catch (e) {
|
||||
log.error(e, '명령 응답 실패');
|
||||
return;
|
||||
}
|
||||
const m = i.guild?.members.cache.get(i.user.id) ?? (await i.guild?.members.fetch(i.user.id).catch(() => null)) ?? null;
|
||||
const vc = m?.voice.channel ?? null;
|
||||
const cmd: BotCommand = {
|
||||
name: i.commandName,
|
||||
guildId: i.guildId,
|
||||
user: m ? member(m) : { id: i.user.id, name: i.user.globalName || i.user.username, avatar: i.user.displayAvatarURL({ size: 128 }), bot: i.user.bot },
|
||||
voiceChannel: vc ? { id: vc.id, name: vc.name } : null,
|
||||
};
|
||||
this.emit('command', cmd, (content: string) => void i.editReply(content).catch((e) => log.error(e, '명령 응답 실패')));
|
||||
});
|
||||
}
|
||||
|
||||
login(token: string): Promise<string> {
|
||||
return this.client.login(token);
|
||||
}
|
||||
async destroy(): Promise<void> {
|
||||
await this.client.destroy();
|
||||
}
|
||||
|
||||
me(): BotGwMember | null {
|
||||
const u = this.client.isReady() ? this.client.user : null;
|
||||
return u ? { id: u.id, name: u.username, avatar: u.displayAvatarURL({ size: 128 }), bot: true } : null;
|
||||
}
|
||||
guilds(): BotGwGuild[] {
|
||||
return [...this.client.guilds.cache.values()].map(guild);
|
||||
}
|
||||
snapshot(guildId: string) {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
if (!g) return null;
|
||||
const channels: BotGwChannel[] = [];
|
||||
const voice: { member: BotGwMember; channelId: string }[] = [];
|
||||
for (const ch of g.channels.cache.values()) {
|
||||
if (!isVoice(ch)) continue;
|
||||
channels.push({ id: ch.id, name: ch.name });
|
||||
for (const m of ch.members.values()) voice.push({ member: member(m), channelId: ch.id });
|
||||
}
|
||||
return { guild: guild(g), channels, voice };
|
||||
}
|
||||
isVoiceChannel(guildId: string, channelId: string): boolean {
|
||||
const ch = this.client.guilds.cache.get(guildId)?.channels.cache.get(channelId);
|
||||
return isVoice(ch);
|
||||
}
|
||||
async members(guildId: string): Promise<BotGwMember[]> {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
if (!g) return [];
|
||||
const ms = await g.members.fetch().catch(() => g.members.cache);
|
||||
return [...ms.values()].map(member);
|
||||
}
|
||||
async registerCommands(guildId: string): Promise<void> {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
if (!g) return;
|
||||
await g.commands.set(COMMANDS);
|
||||
this.log.info({ guild: guildId }, '슬래시 명령 등록');
|
||||
}
|
||||
voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }) {
|
||||
// discord.js 가 @discordjs/voice 용으로 주는 어댑터를 그대로 쓴다. 봇 자신의 음성 정보만 handlers 로 온다
|
||||
this.client.voice.adapters.set(guildId, { onVoiceServerUpdate: handlers.server, onVoiceStateUpdate: handlers.state, destroy: () => undefined });
|
||||
return {
|
||||
send: (payload: any) => {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
if (!g) return false;
|
||||
g.shard.send(payload);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
import { buildServer } from './app.js';
|
||||
import { loadConfig } from './config.js';
|
||||
import { DiscordSource } from './discord-source.js';
|
||||
|
||||
const cfg = loadConfig();
|
||||
const { app } = await buildServer(cfg);
|
||||
// 겜녹이 봇은 이 서버만 디스코드에 연결한다 (봇 토큰은 앱에 보내지 않는다). BOT_GATEWAY=0 이면 끈다
|
||||
let log: { info: (o: any, m?: string) => void; error: (o: any, m?: string) => void } = { info: () => undefined, error: (o, m) => console.error(m, o) };
|
||||
const botSource = process.env.BOT_GATEWAY === '0' ? undefined : new DiscordSource({ info: (o, m) => log.info(o, m), error: (o, m) => log.error(o, m) });
|
||||
const { app } = await buildServer(cfg, { botSource });
|
||||
log = app.log;
|
||||
await app.listen({ host: cfg.host, port: cfg.port });
|
||||
if (botSource) {
|
||||
// 디스코드에 못 붙어도 사이트는 계속 돈다 (discord.js 가 알아서 다시 연결)
|
||||
botSource.login(cfg.botToken).catch((e) => app.log.error(e, '겜녹이 봇 디스코드 연결 실패'));
|
||||
}
|
||||
const stop = async () => {
|
||||
await app.close();
|
||||
await botSource?.destroy();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGTERM', stop);
|
||||
|
||||
@@ -85,9 +85,9 @@ test('앱 로그인: 최고 관리자는 바로 로그인, 미등록 아이디
|
||||
assert.equal(sup.status, 200);
|
||||
assert.equal(sup.r.state, 'ok');
|
||||
assert.equal(sup.r.role, 'superadmin');
|
||||
const meSup = (await (await s.me(sup.r.token)).json()) as any;
|
||||
assert.equal(meSup.role, 'superadmin');
|
||||
assert.equal(meSup.botToken, 'bot-token', '등록된 유저에게만 겜녹이 봇 토큰을 내려준다');
|
||||
const meText = await (await s.me(sup.r.token)).text();
|
||||
assert.equal(JSON.parse(meText).role, 'superadmin');
|
||||
assert.ok(!meText.includes('bot-token') && !meText.includes('botToken'), '봇 토큰은 등록된 유저에게도 보내지 않는다 (서버가 봇을 대신 연결)');
|
||||
|
||||
// 미등록 아이디
|
||||
const no = await s.login(STRANGER);
|
||||
|
||||
@@ -9,7 +9,7 @@ D=/home/claude/win-ci
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
[ -f $D/serve/stage2.ps1.bak-gvr ] || cp $D/serve/stage2.ps1 $D/serve/stage2.ps1.bak-gvr
|
||||
rm -f $D/results/gvr-summary.log
|
||||
# 겜녹이 봇 토큰은 exe 에 넣지 않는다 (v1.2.0~ 로그인한 등록 유저에게 사이트 서버가 내려준다). 빌드에 비밀값이 필요 없다
|
||||
# 겜녹이 봇 토큰은 exe 에 넣지 않는다 (v1.2.1~ 사이트 서버에만 있고, 앱은 서버 중계로 봇을 쓴다). 빌드에 비밀값이 필요 없다
|
||||
umask 077
|
||||
{ cat "$HERE/preamble.ps1"; sed "s/__REV__/$REV/; s/__PHASE__/$PHASE/" "$HERE/gvr.ps1"; } > $D/serve/stage2.ps1.new
|
||||
mv $D/serve/stage2.ps1.new $D/serve/stage2.ps1
|
||||
|
||||
Reference in New Issue
Block a user