// 사이트 서버 보안: 보안 헤더(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((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' 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((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((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(); } });