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:
3
site/server/.gitignore
vendored
Normal file
3
site/server/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
dist/
|
||||
data/
|
||||
2019
site/server/package-lock.json
generated
Normal file
2019
site/server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
27
site/server/package.json
Normal file
27
site/server/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "gvr-site-server",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "겜녹이 사이트 서버: 디스코드 로그인, 게임 PC 연결 확인·중계, 게임 이미지 캐시",
|
||||
"scripts": {
|
||||
"build": "esbuild src/main.ts src/cli.ts --bundle --platform=node --format=esm --target=node22 --outdir=dist --packages=external --alias:@gvr/shared=../../packages/shared/src/index.ts",
|
||||
"start": "node dist/main.js",
|
||||
"dev": "node --import tsx src/main.ts",
|
||||
"typecheck": "tsc --noEmit -p .",
|
||||
"test": "node --import tsx --test test/*.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/static": "^8.2.0",
|
||||
"fastify": "^5.6.1",
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.18.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"esbuild": "^0.25.10",
|
||||
"tsx": "^4.20.6",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
225
site/server/src/app.ts
Normal file
225
site/server/src/app.ts
Normal 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
26
site/server/src/cli.ts
Normal 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
48
site/server/src/config.ts
Normal 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/',
|
||||
},
|
||||
};
|
||||
}
|
||||
59
site/server/src/discord.ts
Normal file
59
site/server/src/discord.ts
Normal 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
12
site/server/src/main.ts
Normal 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
205
site/server/src/relay.ts
Normal 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
152
site/server/src/store.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
148
site/server/test/relay.test.ts
Normal file
148
site/server/test/relay.test.ts
Normal file
@@ -0,0 +1,148 @@
|
||||
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: 'seunghan', 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'],
|
||||
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();
|
||||
}
|
||||
});
|
||||
17
site/server/tsconfig.json
Normal file
17
site/server/tsconfig.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"types": ["node"],
|
||||
"lib": ["ES2023"],
|
||||
"baseUrl": ".",
|
||||
"paths": { "@gvr/shared": ["../../packages/shared/src/index.ts"] }
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts", "../../packages/shared/src/**/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user