M2: 사이트 서버 · 사이트 v1 - gvr.tkrmagid.kr 배포

- site/server: Discord OAuth2 + 봇 토큰 멤버 확인, 세션, 1회용 등록 코드·기기 키 인증, 게임 PC WebSocket 중계(JSON·음성 바이너리), 15초 무응답 잠금, 게임 이미지 캐시, 관리 CLI
- site/web: 타임라인·따라 읽기 재생(단어 강조·이어듣기·현장 모드·재생 게인)·필터·검색·실시간·교정, 발로란트/롤 경기 상세, 잠금 화면(관리자 등록 코드), 모바일, 효과음
- deploy/site: Dockerfile·compose·deploy.sh·make-env.sh (.5, 포트 2972)
- 앱 코어: 사이트 필터 묶음(킬·라운드)과 유저 필터 규칙 맞춤, hello 에 서버 ID

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 01:32:51 +09:00
parent 2745af8f61
commit 9abda88046
84 changed files with 13399 additions and 21 deletions

225
site/server/src/app.ts Normal file
View File

@@ -0,0 +1,225 @@
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 { avatarUrl, DiscordApi } from './discord.js';
import { RelayHub } from './relay.js';
import { ServerStore, type Session } from './store.js';
const SID = 'gvr_sid';
const RECHECK_MS = 10 * 60000;
export async function buildServer(cfg: Config) {
const app = Fastify({ logger: { level: process.env.LOG_LEVEL || 'info' }, trustProxy: true, bodyLimit: 1024 * 1024 });
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://');
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<Session | null> {
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<Session | null> => {
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' });
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.id, { 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;
if (un?.valid && un.value) store.deleteSession(un.value);
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);
});
app.post<{ Body: { code?: string; name?: string } }>('/device/register', async (req, reply) => {
const r = store.redeem(String(req.body?.code ?? ''), String(req.body?.name ?? 'GAME-PC'));
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<string, string> = {};
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('/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 === '/ws') {
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();
});
app.addHook('onClose', async () => {
hub.close();
store.flush();
});
return { app, store, hub };
}
function parseCookies(h: string): Record<string, string> {
const out: Record<string, string> = {};
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;
}

26
site/server/src/cli.ts Normal file
View File

@@ -0,0 +1,26 @@
// 관리 명령 (컨테이너 안에서): node dist/cli.js code → 게임 PC 1회용 등록 코드 (10분)
import { loadConfig } from './config.js';
import { ServerStore } from './store.js';
const cmd = process.argv[2];
const dataDir = process.env.DATA_DIR || loadConfigSafe()?.dataDir || 'data';
const store = new ServerStore(dataDir);
if (cmd === 'code') {
const c = store.createCode('cli', Number(process.argv[3] || 10) * 60000);
console.log(`등록 코드: ${c.code} (만료 ${new Date(c.expiresAt).toLocaleString('ko-KR', { timeZone: 'Asia/Seoul' })})`);
} else if (cmd === 'device') {
console.log(JSON.stringify(store.device(), (k, v) => (k === 'keyHash' ? undefined : v), 2));
} else if (cmd === 'unregister') {
console.log(`등록 해제: ${store.removeDevices()}대 (서버를 다시 시작하면 연결도 끊긴다)`);
} else {
console.log('사용법: node dist/cli.js code [분] | device | unregister');
}
store.flush();
function loadConfigSafe() {
try {
return loadConfig();
} catch {
return null;
}
}

48
site/server/src/config.ts Normal file
View File

@@ -0,0 +1,48 @@
import path from 'node:path';
export interface Config {
port: number;
host: string;
publicUrl: string;
clientId: string;
clientSecret: string;
botToken: string;
/** 로그인 허용 디스코드 서버 (기본: M&L). 게임 PC 가 알려 준 서버도 함께 허용 */
allowedGuilds: string[];
owners: string[];
sessionSecret: string;
dataDir: string;
webDir: string;
version: string;
/** 테스트용: 디스코드 API 주소 바꾸기 */
discordApi: string;
assetUpstream: Record<string, string>;
}
export function loadConfig(env = process.env): Config {
const need = (k: string) => {
const v = env[k];
if (!v) throw new Error(`환경변수 ${k} 가 필요합니다`);
return v;
};
return {
port: Number(env.PORT || 8080),
host: env.HOST || '0.0.0.0',
publicUrl: (env.PUBLIC_URL || 'https://gvr.tkrmagid.kr').replace(/\/$/, ''),
clientId: need('DISCORD_CLIENT_ID'),
clientSecret: need('DISCORD_CLIENT_SECRET'),
botToken: need('DISCORD_BOT_TOKEN'),
allowedGuilds: (env.ALLOWED_GUILD_IDS || '').split(',').map((s) => s.trim()).filter(Boolean),
owners: (env.OWNER_DISCORD_IDS || '').split(',').map((s) => s.trim()).filter(Boolean),
sessionSecret: need('SESSION_SECRET'),
dataDir: env.DATA_DIR || path.resolve('data'),
webDir: env.WEB_DIR || path.resolve('../web/dist'),
version: env.GVR_VERSION || '1.0.0',
discordApi: env.DISCORD_API || 'https://discord.com/api/v10',
assetUpstream: {
valmedia: 'https://media.valorant-api.com/',
ddragon: 'https://ddragon.leagueoflegends.com/',
cdragon: 'https://raw.communitydragon.org/',
},
};
}

View File

@@ -0,0 +1,59 @@
import type { Config } from './config.js';
export interface DiscordUser {
id: string;
username: string;
global_name: string | null;
avatar: string | null;
}
export class DiscordApi {
constructor(private cfg: Config) {}
authorizeUrl(state: string): string {
const p = new URLSearchParams({
client_id: this.cfg.clientId,
response_type: 'code',
redirect_uri: `${this.cfg.publicUrl}/auth/discord/callback`,
scope: 'identify guilds',
state,
prompt: 'none',
});
return `https://discord.com/oauth2/authorize?${p}`;
}
async exchange(code: string): Promise<{ access_token: string }> {
const r = await fetch(`${this.cfg.discordApi}/oauth2/token`, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: this.cfg.clientId,
client_secret: this.cfg.clientSecret,
grant_type: 'authorization_code',
code,
redirect_uri: `${this.cfg.publicUrl}/auth/discord/callback`,
}),
});
if (!r.ok) throw new Error(`token ${r.status} ${await r.text()}`);
return (await r.json()) as { access_token: string };
}
async me(accessToken: string): Promise<DiscordUser> {
const r = await fetch(`${this.cfg.discordApi}/users/@me`, { headers: { authorization: `Bearer ${accessToken}` } });
if (!r.ok) throw new Error(`users/@me ${r.status}`);
return (await r.json()) as DiscordUser;
}
/** 봇 토큰으로 서버 멤버인지 확인 (OAuth guilds 목록보다 확실하고, 나중에 다시 확인할 때 사용자 토큰이 필요 없다) */
async memberOf(guildId: string, userId: string): Promise<{ nick: string | null; avatar: string | null } | null> {
const r = await fetch(`${this.cfg.discordApi}/guilds/${guildId}/members/${userId}`, { headers: { authorization: `Bot ${this.cfg.botToken}` } });
if (r.status === 404) return null;
if (!r.ok) throw new Error(`member ${r.status}`);
const m: any = await r.json();
return { nick: m.nick ?? null, avatar: m.avatar ?? null };
}
}
export function avatarUrl(u: DiscordUser): string | null {
return u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png?size=128` : null;
}

12
site/server/src/main.ts Normal file
View File

@@ -0,0 +1,12 @@
import { buildServer } from './app.js';
import { loadConfig } from './config.js';
const cfg = loadConfig();
const { app } = await buildServer(cfg);
await app.listen({ host: cfg.host, port: cfg.port });
const stop = async () => {
await app.close();
process.exit(0);
};
process.on('SIGTERM', stop);
process.on('SIGINT', stop);

205
site/server/src/relay.ts Normal file
View File

@@ -0,0 +1,205 @@
import crypto from 'node:crypto';
import type { IncomingMessage } from 'node:http';
import { WebSocket, WebSocketServer } from 'ws';
import type { BrowserMessage, DeviceStatus, LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared';
import type { ServerStore } from './store.js';
const OFFLINE_AFTER_MS = 15000;
interface Pending {
resolve: (r: RelayResponse) => void;
reject: (e: Error) => void;
timer: NodeJS.Timeout;
head?: { status: number; headers: Record<string, string> };
chunks: Buffer[];
}
export interface RelayResponse {
status: number;
headers: Record<string, string>;
body: Buffer;
}
/**
* 게임 PC 연결 하나와 브라우저 연결 여러 개를 잇는다.
* - 게임 PC 가 먼저 연결 (기기 키 인증), 5초마다 ping. 15초 동안 소식이 없으면 오프라인 → 모든 브라우저에 잠금 상태 전송 (Q2)
* - 브라우저의 /api 요청을 게임 PC 로 넘기고 응답을 돌려준다
*/
export class RelayHub {
private device: { ws: WebSocket; id: string; name: string; version: string | null; lastMsg: number } | null = null;
private browsers = new Set<WebSocket>();
private pending = new Map<string, Pending>();
readonly deviceWss = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024 });
readonly browserWss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 });
private watchdog: NodeJS.Timeout;
private lastStatus = '';
constructor(private store: ServerStore) {
this.watchdog = setInterval(() => this.checkAlive(), 2000);
}
close(): void {
clearInterval(this.watchdog);
this.device?.ws.terminate();
for (const b of this.browsers) b.terminate();
}
status(): DeviceStatus {
const d = this.store.device();
return {
registered: !!d,
online: !!this.device && Date.now() - this.device.lastMsg < OFFLINE_AFTER_MS,
name: d?.name ?? null,
lastSeen: this.device ? this.device.lastMsg : (d?.lastSeen ?? null),
version: this.device?.version ?? d?.version ?? null,
};
}
private broadcastStatus(force = false): void {
const st = this.status();
const key = `${st.registered}|${st.online}|${st.name}`;
if (!force && key === this.lastStatus) return;
this.lastStatus = key;
this.broadcast({ type: 'status', data: { device: st } });
}
private broadcast(m: BrowserMessage): void {
const txt = JSON.stringify(m);
for (const b of this.browsers) if (b.readyState === WebSocket.OPEN) b.send(txt);
}
private checkAlive(): void {
if (this.device && Date.now() - this.device.lastMsg > OFFLINE_AFTER_MS) {
this.device.ws.terminate();
this.dropDevice(this.device.ws);
}
this.broadcastStatus();
}
// ------------------------------------------------------------------ 게임 PC
authenticateDevice(req: IncomingMessage): { id: string } | null {
const h = String(req.headers.authorization || '');
const m = /^Device ([0-9a-f]+)\.([\w-]+)$/.exec(h);
if (!m) return null;
const d = this.store.verifyDevice(m[1], m[2]);
return d ? { id: d.id } : null;
}
attachDevice(ws: WebSocket, id: string): void {
if (this.device) {
// 같은 기기가 다시 연결 (네트워크 재연결) → 이전 연결을 끊는다
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.store.touchDevice(id, { lastSeen: Date.now() });
ws.send(JSON.stringify({ t: 'welcome', deviceId: id } satisfies RelayToDevice));
ws.on('message', (data, isBinary) => {
if (!this.device || this.device.ws !== ws) return;
this.device.lastMsg = Date.now();
if (isBinary) return this.onBinary(data as Buffer);
let m: RelayFromDevice;
try {
m = JSON.parse(String(data));
} catch {
return;
}
this.onDeviceMessage(m);
});
ws.on('close', () => this.dropDevice(ws));
ws.on('error', () => this.dropDevice(ws));
this.broadcastStatus(true);
}
private dropDevice(ws: WebSocket): void {
if (!this.device || this.device.ws !== ws) return;
this.store.touchDevice(this.device.id, { lastSeen: this.device.lastMsg });
this.device = null;
for (const [id, p] of this.pending) {
clearTimeout(p.timer);
p.reject(new Error('device_offline'));
this.pending.delete(id);
}
this.broadcastStatus(true);
}
private onDeviceMessage(m: RelayFromDevice): void {
const dev = this.device!;
switch (m.t) {
case 'hello':
dev.name = m.name;
dev.version = m.version;
this.store.touchDevice(dev.id, { name: m.name, version: m.version, guildId: m.guildId ?? null, lastSeen: Date.now() });
this.broadcastStatus(true);
break;
case 'ping':
dev.ws.send(JSON.stringify({ t: 'pong', ts: m.ts } satisfies RelayToDevice));
this.store.touchDevice(dev.id, { lastSeen: Date.now() });
break;
case 'res': {
const p = this.pending.get(m.id);
if (!p) return;
this.pending.delete(m.id);
clearTimeout(p.timer);
p.resolve({ status: m.status, headers: m.headers, body: Buffer.from(m.body ?? '', 'utf8') });
break;
}
case 'res_head': {
const p = this.pending.get(m.id);
if (p) p.head = { status: m.status, headers: m.headers };
break;
}
case 'res_end': {
const p = this.pending.get(m.id);
if (!p || !p.head) return;
this.pending.delete(m.id);
clearTimeout(p.timer);
p.resolve({ status: p.head.status, headers: p.head.headers, body: Buffer.concat(p.chunks) });
break;
}
case 'event':
this.broadcast(m.event as LiveEvent);
break;
}
}
private onBinary(buf: Buffer): void {
if (buf.length < 4) return;
const n = buf.readUInt32BE(0);
const id = buf.subarray(4, 4 + n).toString('utf8');
const p = this.pending.get(id);
if (p) p.chunks.push(buf.subarray(4 + n));
}
/** 브라우저 요청 하나를 게임 PC 로 넘긴다 */
request(method: string, path: string, headers: Record<string, string>, user: { id: string; name: string; avatar: string | null }, body: string | null, timeoutMs = 20000): Promise<RelayResponse> {
const dev = this.device;
if (!dev || !this.status().online) return Promise.reject(new Error('device_offline'));
const id = crypto.randomBytes(8).toString('hex');
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (this.pending.delete(id)) reject(new Error('timeout'));
}, timeoutMs);
this.pending.set(id, { resolve, reject, timer, chunks: [] });
const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body };
dev.ws.send(JSON.stringify(msg));
});
}
// ------------------------------------------------------------------ 브라우저
attachBrowser(ws: WebSocket): void {
this.browsers.add(ws);
ws.send(JSON.stringify({ type: 'status', data: { device: this.status() } } satisfies BrowserMessage));
const ping = setInterval(() => ws.readyState === WebSocket.OPEN && ws.ping(), 25000);
ws.on('close', () => {
clearInterval(ping);
this.browsers.delete(ws);
});
ws.on('message', () => undefined);
}
/** 로그아웃·세션 만료 시 해당 브라우저 연결 끊기용 */
get browserCount(): number {
return this.browsers.size;
}
}

152
site/server/src/store.ts Normal file
View File

@@ -0,0 +1,152 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
export interface Device {
id: string;
keyHash: string;
name: string;
createdAt: number;
lastSeen: number | null;
version: string | null;
guildId: string | null;
}
export interface Session {
id: string;
user: { id: string; name: string; avatar: string | null };
createdAt: number;
checkedAt: number;
expiresAt: number;
}
interface Data {
devices: Device[];
codes: { code: string; expiresAt: number; createdBy: string }[];
sessions: Session[];
}
// codes 는 server.json 에 두지 않는다 (codes.json)
const sha256 = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
/**
* 사이트 서버가 저장하는 것은 이것뿐이다: 등록된 게임 PC(기기 키 해시), 1회용 등록 코드, 로그인 세션.
* 기록 내용은 저장하지 않는다 (보고서 3장).
*/
export class ServerStore {
private file: string;
private codesFile: string;
private d: Data;
private saveTimer: NodeJS.Timeout | null = null;
constructor(dir: string) {
fs.mkdirSync(dir, { recursive: true });
this.file = path.join(dir, 'server.json');
this.codesFile = path.join(dir, 'codes.json');
try {
this.d = JSON.parse(fs.readFileSync(this.file, 'utf8'));
} catch {
this.d = { devices: [], codes: [], sessions: [] };
}
this.d.devices ||= [];
this.d.sessions ||= [];
}
private save(now = false): void {
const write = () => {
this.saveTimer = null;
const tmp = this.file + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(this.d), { mode: 0o600 });
fs.renameSync(tmp, this.file);
};
if (now) return write();
if (!this.saveTimer) this.saveTimer = setTimeout(write, 500);
}
flush(): void {
if (this.saveTimer) {
clearTimeout(this.saveTimer);
this.save(true);
}
}
// ---- 등록 코드: 관리 CLI(다른 프로세스)도 만들 수 있게 codes.json 을 매번 디스크에서 읽고 쓴다
private readCodes(): Data['codes'] {
try {
return JSON.parse(fs.readFileSync(this.codesFile, 'utf8')).filter((c: any) => c.expiresAt > Date.now());
} catch {
return [];
}
}
private writeCodes(codes: Data['codes']): void {
const tmp = this.codesFile + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(codes), { mode: 0o600 });
fs.renameSync(tmp, this.codesFile);
}
createCode(createdBy: string, ttlMs = 10 * 60000): { code: string; expiresAt: number } {
const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
let code = '';
for (const b of crypto.randomBytes(8)) code += alphabet[b % alphabet.length];
code = `${code.slice(0, 4)}-${code.slice(4)}`;
const expiresAt = Date.now() + ttlMs;
this.writeCodes([...this.readCodes(), { code, expiresAt, createdBy }]);
return { code, expiresAt };
}
/** 코드 확인 후 기기 등록. 한 게임 PC 만 쓰므로 새로 등록하면 이전 기기는 지운다. */
redeem(code: string, name: string): { deviceId: string; deviceKey: string } | null {
const norm = code.trim().toUpperCase();
const codes = this.readCodes();
const c = codes.find((x) => x.code === norm);
if (!c) return null;
this.writeCodes(codes.filter((x) => x !== c));
const deviceId = crypto.randomBytes(8).toString('hex');
const deviceKey = crypto.randomBytes(32).toString('base64url');
this.d.devices = [{ id: deviceId, keyHash: sha256(deviceKey), name: name.slice(0, 40) || 'GAME-PC', createdAt: Date.now(), lastSeen: null, version: null, guildId: null }];
this.save(true);
return { deviceId, deviceKey };
}
verifyDevice(id: string, key: string): Device | null {
const d = this.d.devices.find((x) => x.id === id);
if (!d) return null;
const a = Buffer.from(d.keyHash, 'hex');
const b = Buffer.from(sha256(key), 'hex');
return a.length === b.length && crypto.timingSafeEqual(a, b) ? d : null;
}
removeDevices(): number {
const n = this.d.devices.length;
this.d.devices = [];
this.save(true);
return n;
}
device(): Device | null {
return this.d.devices[0] ?? null;
}
touchDevice(id: string, patch: Partial<Pick<Device, 'lastSeen' | 'version' | 'guildId' | 'name'>>): void {
const d = this.d.devices.find((x) => x.id === id);
if (!d) return;
Object.assign(d, patch);
this.save();
}
// ---- 세션
createSession(user: Session['user'], ttlMs = 30 * 24 * 3600 * 1000): Session {
const s: Session = { id: crypto.randomBytes(24).toString('base64url'), user, createdAt: Date.now(), checkedAt: Date.now(), expiresAt: Date.now() + ttlMs };
this.d.sessions = this.d.sessions.filter((x) => x.expiresAt > Date.now());
this.d.sessions.push(s);
this.save();
return s;
}
session(id: string | undefined): Session | null {
if (!id) return null;
const s = this.d.sessions.find((x) => x.id === id);
return s && s.expiresAt > Date.now() ? s : null;
}
touchSession(id: string): void {
const s = this.d.sessions.find((x) => x.id === id);
if (s) {
s.checkedAt = Date.now();
this.save();
}
}
deleteSession(id: string): void {
this.d.sessions = this.d.sessions.filter((x) => x.id !== id);
this.save();
}
}