import cookie from '@fastify/cookie'; import fastifyStatic from '@fastify/static'; import Fastify, { type FastifyReply, type FastifyRequest } from 'fastify'; import crypto from 'node:crypto'; 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 { registerCulprit, type ModelCall } from './culprit.js'; 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; 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 }) }, }, trustProxy: true, bodyLimit: 1024 * 1024, forceCloseConnections: true, }); 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.child({ area: 'bot' }), opts.botRecheckMs); // 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시) // CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게) const wsOrigin = cfg.publicUrl.replace(/^http/, 'ws'); const csp = [ "default-src 'self'", "script-src 'self'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob: https://cdn.discordapp.com", "media-src 'self' blob: data:", "font-src 'self' data:", `connect-src 'self' ${wsOrigin}`, "object-src 'none'", "base-uri 'self'", "form-action 'self'", "frame-ancestors 'none'", ].join('; '); app.addHook('onSend', async (_req, reply, payload) => { reply.header('content-security-policy', csp); reply.header('x-content-type-options', 'nosniff'); reply.header('cross-origin-opener-policy', 'same-origin'); return payload; }); const allowedGuilds = (): string[] => { const g = new Set(cfg.allowedGuilds); const dg = store.device()?.guildId; if (dg) g.add(dg); return [...g]; }; /** 세션 확인. 10분마다 서버 멤버인지 다시 확인 (서버에서 나가면 바로 막힘) */ async function getSession(req: FastifyRequest): Promise { const raw = req.cookies[SID]; if (!raw) return null; const un = req.unsignCookie(raw); if (!un.valid || !un.value) return null; const s = store.session(un.value); if (!s) return null; if (Date.now() - s.checkedAt > RECHECK_MS && !cfg.owners.includes(s.user.id)) { try { let ok = false; for (const g of allowedGuilds()) if (await discord.memberOf(g, s.user.id)) ok = true; if (!ok) { store.deleteSession(s.id); return null; } store.touchSession(s.id); } catch { /* 디스코드 API 장애면 기존 세션 유지 */ } } return s; } const requireSession = async (req: FastifyRequest, reply: FastifyReply): Promise => { const s = await getSession(req); if (!s) { 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'); reply.setCookie('gvr_state', state, { path: '/auth', httpOnly: true, secure, sameSite: 'lax', maxAge: 600, signed: true }); return reply.redirect(discord.authorizeUrl(state)); }); app.get<{ Querystring: { code?: string; state?: string; error?: string } }>('/auth/discord/callback', async (req, reply) => { const st = req.cookies.gvr_state ? req.unsignCookie(req.cookies.gvr_state) : null; reply.clearCookie('gvr_state', { path: '/auth' }); // 앱(exe) 로그인: 같은 콜백을 쓰고 state 가 "app." 으로 시작한다 (app-auth.ts) if (st?.valid && st.value && st.value === req.query.state && st.value.startsWith('app.')) return appAuth.completeLogin(st.value, req.query.code, req.query.error, reply, req.log); if (req.query.error) return reply.redirect('/?login=cancelled'); if (!req.query.code || !st?.valid || st.value !== req.query.state) return reply.redirect('/?login=invalid'); try { const tok = await discord.exchange(req.query.code); const u = await discord.me(tok.access_token); let member: { nick: string | null } | null = null; for (const g of allowedGuilds()) { member = await discord.memberOf(g, u.id); if (member) break; } if (!member && !cfg.owners.includes(u.id)) { req.log.info({ user: u.id }, '서버 멤버가 아니라 로그인 거절'); return reply.redirect('/?login=not_member'); } const s = store.createSession({ id: u.id, name: member?.nick || u.global_name || u.username, avatar: avatarUrl(u) }); reply.setCookie(SID, s.token, { path: '/', httpOnly: true, secure, sameSite: 'lax', maxAge: 30 * 24 * 3600, signed: true }); return reply.redirect('/'); } catch (e) { req.log.error(e, 'OAuth 실패'); return reply.redirect('/?login=error'); } }); app.post('/auth/logout', async (req, reply) => { const raw = req.cookies[SID]; const un = raw ? req.unsignCookie(raw) : null; const s = un?.valid && un.value ? store.session(un.value) : null; if (s) store.deleteSession(s.id); reply.clearCookie(SID, { path: '/' }); return { ok: true }; }); 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), canViewLogs: canViewLogs(s.user.id) }; }); // ------------------------------------------------------------------ 상태 · 관리 app.get('/api/status', async (req, reply) => { const s = await requireSession(req, reply); if (!s) return; return { device: hub.status(), server: { version: cfg.version } }; }); app.post('/admin/registration-code', async (req, reply) => { const s = await requireSession(req, reply); if (!s) return; if (!cfg.owners.includes(s.user.id)) return reply.code(403).send({ error: 'forbidden' }); return store.createCode(s.user.id); }); // 등록 코드 무차별 대입 막기: IP 당 10분에 10번 틀리면 잠시 막는다 const registerFails = new RateLimiter(10, 10 * 60000); app.post<{ Body: { code?: string; name?: string } }>('/device/register', async (req, reply) => { if (registerFails.blocked(req.ip)) return reply.code(429).send({ error: 'rate_limited', message: '등록 코드를 너무 많이 틀렸습니다. 10분 뒤 다시 시도해 주세요' }); const r = store.redeem(String(req.body?.code ?? ''), String(req.body?.name ?? 'GAME-PC')); if (!r) registerFails.hit(req.ip); if (!r) return reply.code(400).send({ error: 'invalid_code', message: '등록 코드가 올바르지 않거나 만료되었습니다' }); req.log.info('게임 PC 등록'); return r; }); // ------------------------------------------------------------------ 범인찾기 (Claude API 는 이 서버만 부른다) 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) => { const s = await requireSession(req, reply); if (!s) return; // 쓰기 요청은 같은 사이트에서 온 것만 (CSRF) if (req.method !== 'GET') { const origin = String(req.headers.origin || ''); if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' }); } // 기록 묶음 지우기 · 받아오기는 관리자만 (보기 · zip 내려받기는 서버 멤버 누구나) // 주소는 풀어서(%62undles 같은 우회 막기) 소문자로 본다. 앱도 역할 헤더로 한 번 더 막는다 let p: string; try { p = decodeURIComponent(req.url.split('?')[0]).toLowerCase(); } catch { return reply.code(400).send({ error: 'bad_path' }); } const bundles = p.startsWith('/api/bundles'); const admin = canViewLogs(s.user.id); if (bundles && p !== '/api/bundles' && p !== '/api/bundles/export' && !admin) return reply.code(403).send({ error: 'forbidden', message: '기록 지우기 · 받아오기는 관리자만 할 수 있습니다' }); const headers: Record = {}; for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = String(req.headers[k]); headers['x-gvr-role'] = admin ? 'admin' : 'member'; const body = req.body === undefined || req.body === null ? null : Buffer.isBuffer(req.body) || typeof req.body === 'string' ? req.body : JSON.stringify(req.body); try { // zip 만들기 · 받아오기는 오래 걸릴 수 있다 const r = await hub.request(req.method, req.url, headers, s.user, body, bundles ? 180000 : 20000); for (const [k, v] of Object.entries(r.headers)) if (k !== 'content-length') reply.header(k, v); return reply.code(r.status).send(r.body); } catch (e: any) { if (e.message === 'device_offline') return reply.code(503).send({ error: 'device_offline' }); return reply.code(504).send({ error: 'timeout' }); } }; // zip 받아오기 본문 (300MB 까지) app.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 300 * 1024 * 1024 }, (_req, body, done) => done(null, body)); app.route({ method: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'], url: '/api/*', handler: relay }); // ------------------------------------------------------------------ 게임 이미지 캐시 (보고서 7-7) const cacheDir = path.join(cfg.dataDir, 'asset-cache'); app.get<{ Params: { src: string; '*': string } }>('/game-assets/:src/*', async (req, reply) => { const base = cfg.assetUpstream[req.params.src]; const rel = req.params['*']; if (!base || !/^[\w\-./]+\.(png|jpg|jpeg|webp)$/i.test(rel) || rel.includes('..')) return reply.code(404).send(); const file = path.join(cacheDir, req.params.src, rel); const type = rel.endsWith('.png') ? 'image/png' : rel.endsWith('.webp') ? 'image/webp' : 'image/jpeg'; reply.header('cache-control', 'public, max-age=604800').type(type); if (fs.existsSync(file)) return reply.send(fs.createReadStream(file)); const r = await fetch(base + rel).catch(() => null); if (!r || !r.ok) return reply.code(r?.status === 404 ? 404 : 502).send(); const buf = Buffer.from(await r.arrayBuffer()); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, buf); return reply.send(buf); }); app.get('/healthz', async () => 'ok\n'); // ------------------------------------------------------------------ 사이트 화면 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('/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' }); }); } // ------------------------------------------------------------------ WebSocket app.server.on('upgrade', async (req, socket, head) => { const url = new URL(req.url || '/', 'http://x'); if (url.pathname === '/device/ws') { const d = hub.authenticateDevice(req); if (!d) { socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); return socket.destroy(); } 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') { // 다른 사이트의 페이지가 로그인 쿠키로 실시간 기록을 엿보지 못하게 (Cross-Site WebSocket Hijacking) const origin = String(req.headers.origin || ''); if (origin && origin !== cfg.publicUrl) { socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); return socket.destroy(); } const fakeReq: any = { cookies: parseCookies(String(req.headers.cookie || '')), unsignCookie: (v: string) => app.unsignCookie(v), log: app.log }; const s = await getSession(fakeReq); if (!s) { socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); return socket.destroy(); } hub.browserWss.handleUpgrade(req, socket, head, (ws) => hub.attachBrowser(ws)); return; } socket.destroy(); }); // 서버를 닫기 전에 WebSocket 을 먼저 끊는다 (안 끊으면 close 가 연결이 끝나길 기다리며 멈춘다) app.addHook('preClose', async () => { hub.close(); broker?.close(); }); app.addHook('onClose', async () => { store.flush(); siteLog.close(); }); return { app, store, hub, broker, culprit, siteLog }; } /** 로그에 남길 주소: /auth/* 는 쿼리를 지우고 앱 로그인 요청 아이디를 가린다, 다른 주소도 쿼리 값은 지운다 */ export function safeLogUrl(raw: string | undefined): string { const u = String(raw ?? ''); const i = u.indexOf('?'); const path = (i < 0 ? u : u.slice(0, i)).replace(/^\/auth\/app\/start\/[^/]+/, '/auth/app/start/***'); if (i < 0) return path; const keys = [...new URLSearchParams(u.slice(i + 1)).keys()]; return `${path}?${keys.map((k) => `${k}=***`).join('&')}`; } function parseCookies(h: string): Record { const out: Record = {}; for (const part of h.split(';')) { const i = part.indexOf('='); if (i < 0) continue; out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim()); } return out; }