v1.3.6: 목소리 깨짐(RTP 기준 쉼 채우기) · 알 수 없음 · 잡음 숨기기/삭제 · 사이트 로그 · 지금 게임 · TTS 속도 · 시작 창

- 녹음기: 패킷 도착 간격 대신 RTP 타임스탬프로 자리를 정한다. 게임 중 몰려 온 패킷 사이에 무음이 끼어 목소리가 깨졌다. 예전 녹음은 한 번 고친 뒤 다시 변환
- users.updated 를 빈 목록으로 보내 사이트에서 말한 사람이 '알 수 없음'이 되던 것
- 잡음은 숨기고 ogg 삭제, 로그에 잡음으로 남김. 짧은 목소리도 Whisper 로, 반복 고리는 줄여서 보여 줌
- 사이트: 재생 음량, 발화 우클릭(자세한 정보 · ogg 다운로드), 사이트 로그(/logs, 게임 PC 꺼져도), 지금 게임 상태
- 앱: 지금 게임 상태, 녹음 안내 말 속도 0.1~2.0, 포터블 · 앱 시작 창
- 발로란트 데스매치 가짜 라운드 · 에이스, 빈 선수 이름

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-16 05:01:14 +09:00
parent 2ffb18263c
commit fa6126e17f
66 changed files with 2265 additions and 128 deletions

View File

@@ -252,7 +252,7 @@ export function registerAppAuth(
return s && r ? { userId: s.userId, role: r } : null;
};
return { completeLogin, verifyToken };
return { completeLogin, verifyToken, roleOf };
}
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

View File

@@ -12,15 +12,24 @@ import type { KnowledgeAuto } from './culprit-prompt.js';
import { avatarUrl, DiscordApi } from './discord.js';
import { RateLimiter } from './rate-limit.js';
import { RelayHub } from './relay.js';
import { SiteLog } from './site-log.js';
import { ServerStore, type Session } from './store.js';
const SID = 'gvr_sid';
const RECHECK_MS = 10 * 60000;
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto } = {}) {
export async function buildServer(
cfg: Config,
opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto; logEcho?: boolean } = {},
) {
// 사이트 로그: 날짜별 파일(data/logs/site-날짜.log)로 남기고 관리자가 사이트에서 본다. 게임 PC 가 꺼져 있어도 볼 수 있다
const siteLog = new SiteLog(path.join(cfg.dataDir, 'logs'), { echo: opts.logEcho ?? true });
const app = Fastify({
// 요청 기록은 아래 onResponse 에서 한 줄로 남긴다 (pino 기본 요청 로그는 두 줄 + 상태 확인 폴링으로 너무 많음)
disableRequestLogging: true,
logger: {
stream: siteLog,
level: process.env.LOG_LEVEL || 'info',
// 로그에 비밀값을 남기지 않는다: 로그인 주소의 code · state, 앱 로그인 요청 아이디, 기록 검색어(쿼리)는 지운다
serializers: { req: (req) => ({ method: req.method, url: safeLogUrl(req.url), remoteAddress: req.ip }) },
@@ -31,12 +40,13 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
});
const store = new ServerStore(cfg.dataDir);
const hub = new RelayHub(store);
hub.log = app.log.child({ area: 'relay' });
const discord = new DiscordApi(cfg);
await app.register(cookie, { secret: cfg.sessionSecret });
const secure = cfg.publicUrl.startsWith('https://');
let broker: BotBroker | null = null;
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log, opts.botRecheckMs);
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log.child({ area: 'bot' }), opts.botRecheckMs);
// 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시)
// CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게)
@@ -98,9 +108,54 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
reply.code(401).send({ error: 'unauthorized' });
return null;
}
(req as any).gvrUser = s.user.id;
return s;
};
// ------------------------------------------------------------------ 사이트 로그
// 요청 한 줄 기록: 기록 API · 로그인 · 앱 요청은 모두, 화면 파일은 실패만. 자주 부르는 상태 확인 · 음성 파일은 실패만 남긴다
app.addHook('onResponse', async (req, reply) => {
const url = safeLogUrl(req.url);
const st = reply.statusCode;
const p = url.split('?')[0];
const api = /^\/(api|auth|app|admin|device|site)\//.test(p);
if (st < 400 && (!api || p === '/api/status' || p.startsWith('/api/audio/') || p.startsWith('/site/logs') || p === '/site/client-log')) return;
const o = { area: 'http', status: st, ms: Math.round(reply.elapsedTime), ...((req as any).gvrUser ? { user: (req as any).gvrUser } : {}) };
if (st >= 500 && st !== 503) req.log.error(o, `${req.method} ${url}`);
else if (st >= 400 && st !== 401) req.log.warn(o, `${req.method} ${url}`);
else req.log.info(o, `${req.method} ${url}`);
});
const canViewLogs = (userId: string) => cfg.owners.includes(userId) || ['admin', 'superadmin'].includes(appAuth.roleOf(userId) ?? '');
app.get('/site/logs', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
if (!canViewLogs(s.user.id)) return reply.code(403).send({ error: 'forbidden', message: '사이트 로그는 관리자만 볼 수 있습니다' });
return { days: siteLog.days(), now: Date.now() };
});
app.get<{ Params: { date: string }; Querystring: { download?: string } }>('/site/logs/:date', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
if (!canViewLogs(s.user.id)) return reply.code(403).send({ error: 'forbidden', message: '사이트 로그는 관리자만 볼 수 있습니다' });
const text = siteLog.read(req.params.date);
if (text === null) return reply.code(404).send({ error: 'not_found' });
reply.header('cache-control', 'no-store').type('text/plain; charset=utf-8');
if (req.query.download) reply.header('content-disposition', `attachment; filename="gvr-site-${req.params.date}.log"`);
return text;
});
// 브라우저 오류(화면 오류 · 처리 안 된 오류 · 요청 실패)를 사이트 로그에 남긴다. 로그인한 사람만, 1분에 30개까지
const clientLogLimit = new RateLimiter(30, 60000);
app.post<{ Body: { level?: string; message?: string; detail?: string; page?: string } }>('/site/client-log', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
if (!clientLogLimit.hit(s.user.id)) return reply.code(429).send({ error: 'rate_limited' });
const b = req.body ?? {};
const cut = (v: unknown, n: number) => String(v ?? '').slice(0, n);
const o = { area: 'web', user: s.user.id, page: cut(b.page, 200), ...(b.detail ? { detail: cut(b.detail, 2000) } : {}), ua: cut(req.headers['user-agent'], 160) };
if (b.level === 'error') req.log.error(o, cut(b.message, 500));
else req.log.warn(o, cut(b.message, 500));
return reply.code(204).send();
});
// ------------------------------------------------------------------ 로그인
app.get('/auth/discord', async (req, reply) => {
const state = crypto.randomBytes(16).toString('base64url');
@@ -148,7 +203,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
app.get('/auth/me', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
return { user: s.user, isOwner: cfg.owners.includes(s.user.id) };
return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id) };
});
// ------------------------------------------------------------------ 상태 · 관리
@@ -177,7 +232,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
});
// ------------------------------------------------------------------ 범인찾기 (Claude API 는 이 서버만 부른다)
const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log, call: opts.culpritCall, knowledge: opts.culpritKnowledge });
const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log.child({ area: 'culprit' }), call: opts.culpritCall, knowledge: opts.culpritKnowledge });
// ------------------------------------------------------------------ 기록 API 중계
const relay = async (req: FastifyRequest, reply: FastifyReply) => {
@@ -226,7 +281,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
if (fs.existsSync(cfg.webDir)) {
await app.register(fastifyStatic, { root: cfg.webDir, wildcard: false, index: ['index.html'] });
app.setNotFoundHandler((req, reply) => {
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/app/') && !req.url.startsWith('/game-assets/'))
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/app/') && !req.url.startsWith('/site/') && !req.url.startsWith('/game-assets/'))
return reply.type('text/html').send(fs.readFileSync(path.join(cfg.webDir, 'index.html')));
return reply.code(404).send({ error: 'not_found' });
});
@@ -284,9 +339,10 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
});
app.addHook('onClose', async () => {
store.flush();
siteLog.close();
});
return { app, store, hub, broker, culprit };
return { app, store, hub, broker, culprit, siteLog };
}
/** 로그에 남길 주소: /auth/* 는 쿼리를 지우고 앱 로그인 요청 아이디를 가린다, 다른 주소도 쿼리 값은 지운다 */

View File

@@ -7,7 +7,7 @@ const cfg = loadConfig();
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;
log = app.log.child({ area: 'discord' });
await app.listen({ host: cfg.host, port: cfg.port });
if (botSource) {
// 디스코드에 못 붙어도 사이트는 계속 돈다 (discord.js 가 알아서 다시 연결)

View File

@@ -4,6 +4,9 @@ import { WebSocket, WebSocketServer } from 'ws';
import type { BrowserMessage, DeviceStatus, LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared';
import type { ServerStore } from './store.js';
type Log = { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void };
const NOLOG: Log = { info: () => undefined, warn: () => undefined };
const OFFLINE_AFTER_MS = 15000;
interface Pending {
@@ -33,6 +36,9 @@ export class RelayHub {
private watchdog: NodeJS.Timeout;
private lastStatus = '';
/** 사이트 로그 (app.ts 가 [relay] 영역 로거를 넣는다) */
log: Log = NOLOG;
constructor(private store: ServerStore) {
this.watchdog = setInterval(() => this.checkAlive(), 2000);
}
@@ -74,6 +80,7 @@ export class RelayHub {
private checkAlive(): void {
if (this.device && Date.now() - this.device.lastMsg > OFFLINE_AFTER_MS) {
this.log.warn({ name: this.device.name, silentMs: Date.now() - this.device.lastMsg }, '게임 PC 응답 없음 (15초) → 연결 끊음');
this.device.ws.terminate();
this.dropDevice(this.device.ws);
}
@@ -92,11 +99,13 @@ export class RelayHub {
attachDevice(ws: WebSocket, id: string): void {
if (this.device) {
// 같은 기기가 다시 연결 (네트워크 재연결) → 이전 연결을 끊는다
this.log.info({ name: this.device.name }, '게임 PC 가 다시 연결해서 이전 연결을 닫음');
this.device.ws.close(4000, 'replaced');
this.dropDevice(this.device.ws);
}
const dev = this.store.device();
this.device = { ws, id, name: dev?.name ?? 'GAME-PC', version: null, lastMsg: Date.now() };
this.log.info({ name: this.device.name }, '게임 PC 연결');
this.store.touchDevice(id, { lastSeen: Date.now() });
ws.send(JSON.stringify({ t: 'welcome', deviceId: id } satisfies RelayToDevice));
ws.on('message', (data, isBinary) => {
@@ -111,13 +120,14 @@ export class RelayHub {
}
this.onDeviceMessage(m);
});
ws.on('close', () => this.dropDevice(ws));
ws.on('error', () => this.dropDevice(ws));
ws.on('close', (code, reason) => this.dropDevice(ws, `닫힘 ${code}${reason?.length ? ' ' + String(reason) : ''}`));
ws.on('error', (e) => this.dropDevice(ws, `오류 ${e.message}`));
this.broadcastStatus(true);
}
private dropDevice(ws: WebSocket): void {
private dropDevice(ws: WebSocket, why = '응답 없음'): void {
if (!this.device || this.device.ws !== ws) return;
this.log.warn({ name: this.device.name, why, pending: this.pending.size }, '게임 PC 연결 끊김 (사이트 잠김)');
this.store.touchDevice(this.device.id, { lastSeen: this.device.lastMsg });
this.device = null;
for (const [id, p] of this.pending) {
@@ -134,6 +144,7 @@ export class RelayHub {
case 'hello':
dev.name = m.name;
dev.version = m.version;
this.log.info({ name: m.name, version: m.version, guild: m.guildId ?? null }, '게임 PC 정보');
this.store.touchDevice(dev.id, { name: m.name, version: m.version, guildId: m.guildId ?? null, lastSeen: Date.now() });
this.broadcastStatus(true);
break;
@@ -183,7 +194,10 @@ export class RelayHub {
const id = crypto.randomBytes(8).toString('hex');
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (this.pending.delete(id)) reject(new Error('timeout'));
if (this.pending.delete(id)) {
this.log.warn({ method, path: path.split('?')[0], ms: timeoutMs }, '게임 PC 가 기록 요청에 답하지 않음 (시간 초과)');
reject(new Error('timeout'));
}
}, timeoutMs);
this.pending.set(id, { resolve, reject, timer, chunks: [] });
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body };

109
site/server/src/site-log.ts Normal file
View File

@@ -0,0 +1,109 @@
import fs from 'node:fs';
import path from 'node:path';
/**
* 사이트 서버 로그 (v1.3.6~). exe 로그(gvr-날짜.log)와 같은 모양의 글 로그를 날짜별 파일로 남긴다.
* 게임 PC 와 연결이 끊겨도 사이트에서 볼 수 있다 (관리자만, /site/logs).
*
* Fastify(pino)가 한 줄씩 쓰는 JSON 을 받아 "시각 수준 [영역] 내용 {추가 값}" 으로 바꾼다. 표준 출력(docker logs)에도 그대로 낸다.
*/
const LEVELS: Record<number, string> = { 10: 'TRACE', 20: 'DEBUG', 30: 'INFO ', 40: 'WARN ', 50: 'ERROR', 60: 'FATAL' };
const SKIP_KEYS = new Set(['level', 'time', 'pid', 'hostname', 'msg', 'area', 'reqId', 'err', 'v']);
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
export interface SiteLogOptions {
keepDays?: number;
/** 표준 출력에도 쓰기 (테스트에서는 끈다) */
echo?: boolean;
}
export class SiteLog {
private day = '';
private fd: number | null = null;
private keepDays: number;
private echo: boolean;
constructor(
readonly dir: string,
opts: SiteLogOptions = {},
) {
this.keepDays = opts.keepDays ?? 14;
this.echo = opts.echo ?? true;
fs.mkdirSync(dir, { recursive: true });
}
/** pino destination: JSON 한 줄(또는 여러 줄) */
write(chunk: string): void {
if (this.echo) process.stdout.write(chunk);
for (const line of String(chunk).split('\n')) {
if (!line.trim()) continue;
let o: Record<string, any>;
try {
o = JSON.parse(line);
} catch {
o = { level: 30, time: Date.now(), msg: line };
}
this.append(format(o), typeof o.time === 'number' ? o.time : Date.now());
}
}
private append(text: string, ts: number): void {
const day = new Date(ts).toISOString().slice(0, 10);
try {
if (day !== this.day || this.fd === null) {
if (this.fd !== null) fs.closeSync(this.fd);
this.day = day;
this.fd = fs.openSync(this.file(day), 'a');
this.cleanup();
}
fs.writeSync(this.fd, text + '\n');
} catch {
/* 디스크 문제로 로그를 못 써도 서버는 계속 돈다 */
}
}
file(day: string): string {
return path.join(this.dir, `site-${day}.log`);
}
/** 남아 있는 로그 날짜 (최신 먼저) */
days(): { date: string; size: number }[] {
return fs
.readdirSync(this.dir)
.map((f) => /^site-(\d{4}-\d{2}-\d{2})\.log$/.exec(f)?.[1])
.filter((d): d is string => !!d)
.sort()
.reverse()
.map((date) => ({ date, size: fs.statSync(this.file(date)).size }));
}
/** 그날 로그 원문. 없으면 null */
read(day: string): string | null {
if (!DATE_RE.test(day)) return null;
const f = this.file(day);
return fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : null;
}
private cleanup(): void {
const cut = new Date(Date.now() - this.keepDays * 86400000).toISOString().slice(0, 10);
for (const { date } of this.days()) if (date < cut) fs.rmSync(this.file(date), { force: true });
}
close(): void {
if (this.fd !== null) fs.closeSync(this.fd);
this.fd = null;
}
}
/** exe 로그와 같은 모양: 2026-10-15T17:15:59.289Z INFO [relay] 게임 PC 연결 {"name":"TKRMAGID-PC"} */
export function format(o: Record<string, any>): string {
const time = new Date(typeof o.time === 'number' ? o.time : Date.now()).toISOString();
const lv = LEVELS[o.level] ?? 'INFO ';
const area = o.area || 'server';
const extra: Record<string, unknown> = {};
for (const [k, v] of Object.entries(o)) if (!SKIP_KEYS.has(k) && v !== undefined) extra[k] = v;
let s = `${time} ${lv} [${area}] ${o.msg ?? ''}`;
if (Object.keys(extra).length) s += ' ' + JSON.stringify(extra);
if (o.err) s += `\n ${String(o.err.stack || `${o.err.type ?? 'Error'}: ${o.err.message}`).replace(/\n/g, '\n ')}`;
return s;
}