Files
game_voice_recorder/site/server/test/security.test.ts
EJClaw 5c8ba05da4 사이트 CSP connect-src 에 blob: 추가: 3D 파일 안 텍스처를 막아 요원이 흰색 · 맵 3D 가 미니맵으로 나오던 문제
- three.js GLTFLoader 는 glb 안 이미지를 blob: 주소로 fetch 해 읽는데 connect-src 가 막아 텍스처가 모두 실패했다
  (요원 흰색, 두 층 맵 재질은 텍스처 실패로 맵 전체가 실패 → 미니맵 바닥)
- CSP 를 csp.ts 하나로 모으고 vite preview 도 같은 CSP 로 열어 헤드리스 확인이 실제와 같은 제한에서 되게 함
- 맵 B 층 텍스처 하나를 못 읽어도 맵 전체를 버리지 않음
- 시험: connect-src 에 blob: 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 22:30:00 +09:00

172 lines
8.7 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(), opts: { browserRecheckMs?: number } = {}) {
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, opts);
// 서버 로그를 모아 둔다 (비밀값이 남는지 본다)
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' blob: wss:\/\/gvr\.example(;|$)/); // blob: = 3D 파일 안 텍스처 (없으면 요원 흰색 · 맵 3D 실패)
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('실시간 WebSocket: 세션이 지워지거나(서버 탈퇴 등) 로그아웃하면 이미 열린 연결도 끊는다', async () => {
const s = await stack(tmp(), { browserRecheckMs: 50 });
try {
const connect = async (sid: string) => {
const ws = new WebSocket(s.base.replace('http', 'ws') + '/ws', { headers: { cookie: sid, origin: 'https://gvr.example' } });
await new Promise((r) => ws.on('open', r));
return { ws, closed: new Promise<number>((r) => ws.on('close', (code) => r(code))) };
};
// 1) 세션 삭제 (getSession 의 서버 멤버 재확인이 실패하면 이렇게 지운다) → 다음 확인 때 끊김
const a = await connect(await s.login());
for (const x of [...(s.store as any).d.sessions]) s.store.deleteSession(x.id);
assert.equal(await a.closed, 4401);
// 2) 로그아웃 → 바로 끊김
const sid = await s.login();
const b = await connect(sid);
await fetch(s.base + '/auth/logout', { method: 'POST', headers: { cookie: sid } });
assert.equal(await b.closed, 4401);
} 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();
}
});