Files
game_voice_recorder/site/server/test/relay.test.ts
EJClaw c2a5547a68 앱 v1.2.0: exe 디스코드 로그인 · 유저 등록 · 관리자 페이지
- 사이트 서버: 앱 로그인(/auth/app/begin·start·poll, 기존 OAuth 콜백 재사용), 앱 토큰(/app/me, 해시 저장),
  유저 등록 API(/app/admin/users, 등록·역할·해제는 최고 관리자만, 목록은 관리자도). 최고 관리자 2명 고정
- 앱: 등록된 계정으로 로그인해야 코어(봇·녹음·사이트 연결)를 띄운다. 미등록이면 "등록되지 않은 아이디" + 아이디 표시.
  10분마다 재확인, 등록 해제 시 즉시 잠금. 서버 연결 실패 시 마지막 확인 후 3일 유예
- 겜녹이 봇 토큰을 exe 에 넣지 않고 로그인한 등록 유저에게 서버가 내려준다 (잠기면 삭제). win-ci 토큰 주입 제거
- 관리자 탭(유저 등록·목록·접속 기록), 관리자 전용 설정(봇 변경·TTS 안내·보관 기간·사이트·학습 데이터·파인튜닝)은
  일반 유저에게 잠금 표시 + 메인 프로세스에서 차단
- 테스트: 서버 앱 로그인 2건, 앱↔서버 통합 3건, Electron 로그인 E2E 스크립트(scripts/login-e2e.mts)

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

150 lines
8.1 KiB
TypeScript

import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import WebSocket from 'ws';
import { buildServer } from '../src/app.ts';
import type { Config } from '../src/config.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-site-'));
/** 가짜 디스코드 API: OAuth 토큰 교환, users/@me, 길드 멤버 */
async function fakeDiscord(members: Set<string>) {
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') return res.end(JSON.stringify({ access_token: 'at-' + 'member1' }));
if (u.pathname === '/users/@me') return res.end(JSON.stringify({ id: 'member1', username: 'seunghan', global_name: '승한', avatar: null }));
const m = /\/guilds\/(\d+)\/members\/(\w+)/.exec(u.pathname);
if (m) {
if (members.has(m[2])) return res.end(JSON.stringify({ nick: '승한', avatar: null }));
res.statusCode = 404;
return res.end('{}');
}
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() };
}
test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음성) → 실시간 이벤트 → 연결 끊김 잠금', async () => {
const members = new Set(['member1']);
const dc = await fakeDiscord(members);
const cfg: Config = {
port: 0,
host: '127.0.0.1',
publicUrl: 'http://127.0.0.1',
clientId: 'cid',
clientSecret: 'secret',
botToken: 'bot',
allowedGuilds: ['111'],
owners: ['owner1'],
superAdmins: [],
sessionSecret: 'x'.repeat(32),
dataDir: tmp(),
webDir: '/nonexistent',
version: 'test',
discordApi: dc.url,
assetUpstream: {},
};
const { app, store } = await buildServer(cfg);
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
try {
// 로그인 안 하면 401
assert.equal((await fetch(base + '/api/status')).status, 401);
// OAuth: state 쿠키 → callback
const start = await fetch(base + '/auth/discord', { redirect: 'manual' });
assert.equal(start.status, 302);
const loc = new URL(start.headers.get('location')!);
assert.equal(loc.searchParams.get('scope'), 'identify guilds');
const stateCookie = start.headers.getSetCookie()[0].split(';')[0];
const cb = await fetch(`${base}/auth/discord/callback?code=abc&state=${loc.searchParams.get('state')}`, { headers: { cookie: stateCookie }, redirect: 'manual' });
assert.equal(cb.headers.get('location'), '/');
const sid = cb.headers.getSetCookie().find((c) => c.startsWith('gvr_sid='))!.split(';')[0];
const me = (await (await fetch(base + '/auth/me', { headers: { cookie: sid } })).json()) as any;
assert.equal(me.user.name, '승한');
// 기기 없음 → 상태 registered:false, /api 는 503
let st = (await (await fetch(base + '/api/status', { headers: { cookie: sid } })).json()) as any;
assert.equal(st.device.registered, false);
assert.equal((await fetch(base + '/api/timeline', { headers: { cookie: sid } })).status, 503);
// 등록 코드 → 기기 등록
const code = store.createCode('test');
assert.equal((await fetch(base + '/device/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: 'WRONG', name: 'x' }) })).status, 400);
const reg = (await (await fetch(base + '/device/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: code.code, name: 'GAME-PC' }) })).json()) as any;
assert.ok(reg.deviceKey);
// 코드는 1회용
assert.equal((await fetch(base + '/device/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: code.code, name: 'x' }) })).status, 400);
// 잘못된 키는 거절
await assert.rejects(
new Promise((res, rej) => {
const w = new WebSocket(base.replace('http', 'ws') + '/device/ws', { headers: { authorization: `Device ${reg.deviceId}.wrong` } });
w.on('open', res);
w.on('error', rej);
}),
);
// 브라우저 WS
const bws = new WebSocket(base.replace('http', 'ws') + '/ws', { headers: { cookie: sid } });
const bmsgs: any[] = [];
bws.on('message', (d) => bmsgs.push(JSON.parse(String(d))));
await new Promise((r) => bws.on('open', r));
// 앱 코어 쪽 (실제 RelayClient + Fastify inject)
const { RelayClient } = await import('../../../app/src/core/relay/client.ts');
const { Bus } = await import('../../../app/src/core/util/events.ts');
const Fastify = (await import('fastify')).default;
const local = Fastify();
local.get('/api/timeline', async (req) => ({ items: [], next: null, user: req.headers['x-gvr-user'] }));
local.get('/api/audio/:id', async (_req, reply) => reply.header('content-type', 'audio/ogg').send(Buffer.from('OggS' + 'x'.repeat(5000))));
local.patch('/api/utterances/:id', async (req) => ({ ok: true, body: req.body }));
const bus = new Bus();
const rc = new RelayClient(local as any, bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: '1.0.0', guildId: '222' }));
rc.start();
const wait = async (fn: () => boolean, ms = 5000) => {
const t = Date.now();
while (!fn()) {
if (Date.now() - t > ms) throw new Error('timeout');
await new Promise((r) => setTimeout(r, 50));
}
};
await wait(() => rc.status.state === 'online');
await wait(() => bmsgs.some((m) => m.type === 'status' && m.data.device.online));
st = (await (await fetch(base + '/api/status', { headers: { cookie: sid } })).json()) as any;
assert.equal(st.device.online, true);
// JSON 중계
const tl = (await (await fetch(base + '/api/timeline?limit=5', { headers: { cookie: sid } })).json()) as any;
assert.deepEqual(tl.items, []);
assert.equal(JSON.parse(decodeURIComponent(tl.user)).id, 'member1');
// 음성(바이너리) 중계
const au = await fetch(base + '/api/audio/abc', { headers: { cookie: sid } });
assert.equal(au.headers.get('content-type'), 'audio/ogg');
assert.equal((await au.arrayBuffer()).byteLength, 5004);
// 쓰기 요청: 다른 사이트 Origin 은 거절
assert.equal((await fetch(base + '/api/utterances/a', { method: 'PATCH', headers: { cookie: sid, 'content-type': 'application/json', origin: 'https://evil.example' }, body: '{"text":"x"}' })).status, 403);
const pr = (await (await fetch(base + '/api/utterances/a', { method: 'PATCH', headers: { cookie: sid, 'content-type': 'application/json', origin: cfg.publicUrl }, body: '{"text":"고침"}' })).json()) as any;
assert.equal(pr.body.text, '고침');
// 실시간 이벤트 → 브라우저
bus.live({ type: 'recording.state', data: { active: true, channel: '음성', since: 1, participants: [] } });
await wait(() => bmsgs.some((m) => m.type === 'recording.state'));
// 기기가 알려 준 서버(222) 멤버도 로그인 허용
assert.equal(store.device()!.guildId, '222');
// 연결 끊김 → 잠금
rc.stop();
await wait(() => bmsgs.some((m) => m.type === 'status' && m.data.device.registered && !m.data.device.online));
assert.equal((await fetch(base + '/api/timeline', { headers: { cookie: sid } })).status, 503);
// 서버 멤버가 아니면 로그인 거절
members.clear();
const s2 = await fetch(base + '/auth/discord', { redirect: 'manual' });
const l2 = new URL(s2.headers.get('location')!);
const cb2 = await fetch(`${base}/auth/discord/callback?code=abc&state=${l2.searchParams.get('state')}`, { headers: { cookie: s2.headers.getSetCookie()[0].split(';')[0] }, redirect: 'manual' });
assert.equal(cb2.headers.get('location'), '/?login=not_member');
bws.close();
await local.close();
} finally {
await app.close();
dc.close();
}
});