Files
game_voice_recorder/site/server/test/relay.test.ts
EJClaw b230443409 v1.3.3: 따라갈 사람 목록 · 롤 채팅 OCR 제거 · 표시 이름(실명 숨기기)
- 따라갈 사람: 봇이 서버를 지켜보기 전 멤버 요청을 사이트 서버가 forbidden 으로 거절하고 앱이 오류를 숨겨 빈 목록이 됐다
  → 가입한 서버면 지켜보기 전에도 응답(source.members 가 멤버 확인), 앱은 오류 · 다시 불러오기 표시
  → 내 계정 → 관리자(GET /app/admins) → 이름순, 녹음할 서버를 바꾸면 봇을 다시 붙여 새 서버를 지켜봄
- 롤 채팅 OCR 제거: 앱 설정 · 마법사 · 진단 · lol.ts · 워커 ocr.py/ocr_* op · pywinrt/mss/Pillow · win-ci ocr_lang
  롤은 게임 중 전체/팀 채팅 API 가 없어 LCU(챔피언 선택 · 게임 후) + r3dlog(남아 있을 때, LCU 채팅을 지우지 않고 추가)
- 표시 이름: 서버 store.displayNames (세션 · 앱 유저 · 접속 기록 이름까지 바꿈), GET /app/names, PUT /app/admin/names,
  cli name. 앱은 받아서 users · 지난 범인 분석 이름을 바꾸고 이후 디스코드 이름 대신 저장. 관리자 탭에 편집 UI
- 저장소 시연 · 테스트 데이터 · 화면 캡처 · 계획서 PDF 의 실제 이름을 가짜 이름으로 교체
- 테스트: 앱 41 · 서버 16 · 워커 39 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 02:42:57 +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: 'haneul', 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();
}
});