Files
game_voice_recorder/site/server/test/security.test.ts
EJClaw b90a895501 앱 v1.2.2 · 사이트: 통신 · 데이터 보안 강화
앱
- 사이트 서버 주소는 https 만 (127.0.0.1 · localhost 만 http 허용). 로그인 · 봇 중계 · 기기 중계 · 기기 등록 모두
  암호화되지 않은 주소로는 아무것도 보내지 않고, 설정에서도 http 주소를 거절한다 (core/util/secure-url.ts)
- Riot 로컬 API 의 인증서 검증 예외를 이 PC 안 주소로만 제한 (local 을 잘못 넘겨도 바깥 주소는 거절)
- 설정 창: 바깥 주소로 이동 · 리다이렉트 · webview 를 막고 브라우저로 연다.
  막기 전에는 이동한 바깥 페이지에서도 window.gvr 가 살아 있었다 (login-e2e 로 재현 · 확인)
- 권한 요청은 클립보드 쓰기만 허용
- Electron fuses: RunAsNode · NODE_OPTIONS/NODE_EXTRA_CA_CERTS · --inspect 끄기, app.asar 만 로드, 쿠키 암호화

사이트 서버
- CSP (이 사이트 스크립트 · 접속만, frame-ancestors none), nosniff, COOP
- 실시간 WebSocket(/ws) 은 이 사이트 출처만 (Cross-Site WebSocket Hijacking 방지)
- 로그인 세션 토큰은 해시로만 저장 (예전 파일은 읽을 때 해시로 바꾸고 로그인 유지)
- 요청 로그에서 OAuth code · state, 앱 로그인 요청 아이디, 쿼리 값 제거
- IP 별 횟수 제한: 기기 등록 코드 10회 실패 · 앱 로그인 시작 10회 / 10분

검증: 앱 테스트 28 · 서버 테스트 9, login-e2e 20/20, demo-stack 화면 7종 CSP 위반 0 · 실시간 잠금/해제 정상

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 10:54:33 +09:00

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'(;|$)/);
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();
}
});