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 { avatarUrl, DiscordApi } from './discord.js'; import { RateLimiter } from './rate-limit.js'; import { RelayHub } from './relay.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 } = {}) { const app = Fastify({ logger: { 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); 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); // 보안 헤더. 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; } return s; }; // ------------------------------------------------------------------ 로그인 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) }; }); // ------------------------------------------------------------------ 상태 · 관리 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; }); // ------------------------------------------------------------------ 기록 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' }); } const headers: Record = {}; for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = String(req.headers[k]); const body = req.body === undefined || req.body === null ? null : typeof req.body === 'string' ? req.body : JSON.stringify(req.body); try { const r = await hub.request(req.method, req.url, headers, s.user, body); 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' }); } }; 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('/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(); }); return { app, store, hub, broker }; } /** 로그에 남길 주소: /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; }