- tools/map-extract (C#, CUE4Parse 고정 커밋): 게임 파일을 받지 않고 매니페스트 조각만 HTTP Range 로 읽어 맵 22개(일반 13 · 팀 데스매치 5 · 스커미시 3 · 어빌리티 드래프트)를 월드 좌표 glb 로. 3.1분 · 587MB 받음 - scripts/pack.py (gltfpack -cc + gzip, 맵당 0.5~4.6MB) · update.sh (uedb 매핑 · 라이브 패치 확인 → 매핑 보관 → 추출 → .5 data/maps3d 반영) · install.sh (systemd 사용자 타이머 30분, 메모리 6GB 상한) - 사이트 서버: GET /site/maps3d* (로그인 필요, gzip 그대로). CSP 에 'wasm-unsafe-eval' (meshopt 압축 풀기만) - 3D 재생기: 맵 3D 위에 선수 표시, 천장 자르기(자동 · 없음 · 직접), 높이 색칠. 맵이 없거나 실패하면 미니맵 - 리플레이 칸: 리플레이를 아직 안 보내는 앱 버전이면 그렇게 안내 - 테스트: maps3d.test.ts 2개, CSP 테스트 갱신 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
150 lines
7.5 KiB
TypeScript
150 lines
7.5 KiB
TypeScript
// 사이트 서버 보안: 보안 헤더(CSP), 실시간 WebSocket 출처 확인, 세션 토큰 해시 저장, 로그 가리기, 횟수 제한
|
|
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, safeLogUrl } from '../src/app.ts';
|
|
import type { Config } from '../src/config.ts';
|
|
import { ServerStore } from '../src/store.ts';
|
|
|
|
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-sec-'));
|
|
|
|
async function fakeDiscord() {
|
|
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' }));
|
|
if (u.pathname === '/users/@me') return res.end(JSON.stringify({ id: 'member1', username: 'm', global_name: '멤버', avatar: null }));
|
|
if (/\/guilds\/\d+\/members\/member1$/.test(u.pathname)) return res.end(JSON.stringify({ nick: '멤버', avatar: null }));
|
|
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() };
|
|
}
|
|
|
|
async function stack(dataDir = tmp()) {
|
|
const dc = await fakeDiscord();
|
|
const cfg: Config = {
|
|
port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot',
|
|
allowedGuilds: ['111'], owners: [], superAdmins: [], sessionSecret: 'x'.repeat(32), dataDir, webDir: '/nonexistent',
|
|
version: 'test', discordApi: dc.url, assetUpstream: {},
|
|
};
|
|
const lines: string[] = [];
|
|
const { app, store } = await buildServer(cfg);
|
|
// 서버 로그를 모아 둔다 (비밀값이 남는지 본다)
|
|
const orig = process.stdout.write.bind(process.stdout);
|
|
(process.stdout as any).write = (chunk: any, ...rest: any[]) => (lines.push(String(chunk)), orig(chunk, ...rest));
|
|
await app.listen({ host: '127.0.0.1', port: 0 });
|
|
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
|
|
const login = async () => {
|
|
const start = await fetch(base + '/auth/discord', { redirect: 'manual' });
|
|
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
|
|
const cb = await fetch(`${base}/auth/discord/callback?code=secret-oauth-code&state=${state}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
|
|
return cb.headers.getSetCookie().find((c) => c.startsWith('gvr_sid='))!.split(';')[0]!;
|
|
};
|
|
return {
|
|
base, store, lines, login, dataDir,
|
|
close: async () => {
|
|
(process.stdout as any).write = orig;
|
|
await app.close();
|
|
dc.close();
|
|
},
|
|
};
|
|
}
|
|
|
|
test('보안 헤더: CSP 는 이 사이트 스크립트 · 접속만 허용하고 다른 사이트가 틀(frame)로 넣지 못한다', async () => {
|
|
const s = await stack();
|
|
try {
|
|
const r = await fetch(s.base + '/healthz');
|
|
const csp = r.headers.get('content-security-policy') ?? '';
|
|
assert.match(csp, /default-src 'self'/);
|
|
assert.match(csp, /script-src 'self' 'wasm-unsafe-eval'(;|$)/); // WebAssembly(맵 3D 압축 풀기)만, eval 은 안 됨
|
|
assert.match(csp, /connect-src 'self' wss:\/\/gvr\.example/);
|
|
assert.match(csp, /frame-ancestors 'none'/);
|
|
assert.equal(r.headers.get('x-content-type-options'), 'nosniff');
|
|
} finally {
|
|
await s.close();
|
|
}
|
|
});
|
|
|
|
test('실시간 WebSocket: 다른 사이트에서 로그인 쿠키로 붙으면 막는다', async () => {
|
|
const s = await stack();
|
|
try {
|
|
const sid = await s.login();
|
|
const open = (origin: string) =>
|
|
new Promise<number>((resolve) => {
|
|
const ws = new WebSocket(s.base.replace('http', 'ws') + '/ws', { headers: { cookie: sid, origin } });
|
|
ws.on('open', () => (ws.close(), resolve(101)));
|
|
ws.on('unexpected-response', (_q, res) => resolve(res.statusCode!));
|
|
ws.on('error', () => resolve(0));
|
|
});
|
|
assert.equal(await open('https://evil.example'), 403);
|
|
assert.equal(await open('https://gvr.example'), 101);
|
|
} finally {
|
|
await s.close();
|
|
}
|
|
});
|
|
|
|
test('세션: 서버 파일에는 세션 토큰 대신 해시만 남고, 예전 파일의 세션도 그대로 이어진다', async () => {
|
|
const s = await stack();
|
|
try {
|
|
const sid = await s.login();
|
|
const token = decodeURIComponent(sid.split('=')[1]!).split('.')[0]!; // 서명 쿠키: <토큰>.<서명>
|
|
assert.equal((await fetch(s.base + '/auth/me', { headers: { cookie: sid } })).status, 200);
|
|
s.store.flush();
|
|
const file = fs.readFileSync(path.join(s.dataDir, 'server.json'), 'utf8');
|
|
assert.ok(token.length > 20 && !file.includes(token), '세션 토큰이 server.json 에 그대로 있으면 안 된다');
|
|
// 로그아웃하면 그 세션은 끝
|
|
await fetch(s.base + '/auth/logout', { method: 'POST', headers: { cookie: sid } });
|
|
assert.equal((await fetch(s.base + '/auth/me', { headers: { cookie: sid } })).status, 401);
|
|
} finally {
|
|
await s.close();
|
|
}
|
|
// 예전 형식(토큰을 그대로 저장) → 읽을 때 해시로 바꾸고 같은 토큰으로 계속 로그인된다
|
|
const dir = tmp();
|
|
const old = 'old-raw-session-token-abcdefghijklmnop';
|
|
fs.writeFileSync(path.join(dir, 'server.json'), JSON.stringify({ devices: [], sessions: [{ id: old, user: { id: 'u1', name: 'n', avatar: null }, createdAt: 1, checkedAt: Date.now(), expiresAt: Date.now() + 86400000 }], appUsers: [], appSessions: [], appSeen: {} }));
|
|
const st = new ServerStore(dir);
|
|
assert.equal(st.session(old)?.user.id, 'u1');
|
|
assert.ok(!fs.readFileSync(path.join(dir, 'server.json'), 'utf8').includes(old));
|
|
});
|
|
|
|
test('로그: 로그인 code · state · 앱 로그인 요청 아이디 · 검색어는 남기지 않는다', async () => {
|
|
assert.equal(safeLogUrl('/auth/discord/callback?code=abc&state=xyz'), '/auth/discord/callback?code=***&state=***');
|
|
assert.equal(safeLogUrl('/auth/app/start/Zk3j_secretid'), '/auth/app/start/***');
|
|
assert.equal(safeLogUrl('/api/search?q=비밀 이야기'), '/api/search?q=***');
|
|
assert.equal(safeLogUrl('/healthz'), '/healthz');
|
|
const prev = process.env.LOG_LEVEL;
|
|
process.env.LOG_LEVEL = 'info'; // 요청 로그가 실제로 찍히게
|
|
const s = await stack();
|
|
if (prev === undefined) delete process.env.LOG_LEVEL;
|
|
else process.env.LOG_LEVEL = prev;
|
|
try {
|
|
await s.login();
|
|
const all = s.lines.join('');
|
|
assert.ok(all.includes('/auth/discord/callback'), '요청 로그는 남는다');
|
|
assert.ok(!all.includes('secret-oauth-code'), 'OAuth code 가 로그에 있으면 안 된다');
|
|
} finally {
|
|
await s.close();
|
|
}
|
|
});
|
|
|
|
test('횟수 제한: 등록 코드를 계속 틀리면 막고, 로그인 요청을 쏟아내면 막는다', async () => {
|
|
const s = await stack();
|
|
try {
|
|
const reg = (code: string) => fetch(s.base + '/device/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code, name: 'x' }) });
|
|
for (let i = 0; i < 10; i++) assert.equal((await reg('WRONG-' + i)).status, 400);
|
|
const good = s.store.createCode('t');
|
|
assert.equal((await reg(good.code)).status, 429, '10번 틀린 뒤에는 맞는 코드도 잠시 막힌다');
|
|
const begin = () => fetch(s.base + '/auth/app/begin', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
|
|
for (let i = 0; i < 10; i++) assert.equal((await begin()).status, 200);
|
|
assert.equal((await begin()).status, 429);
|
|
} finally {
|
|
await s.close();
|
|
}
|
|
});
|