앱 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>
This commit is contained in:
@@ -10,6 +10,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import type { AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared';
|
||||
import type { Config } from './config.js';
|
||||
import { avatarUrl, fetchDiscordUser, type DiscordApi, type DiscordUser } from './discord.js';
|
||||
import { RateLimiter } from './rate-limit.js';
|
||||
import type { ServerStore } from './store.js';
|
||||
|
||||
const LOGIN_TTL_MS = 10 * 60000;
|
||||
@@ -32,6 +33,8 @@ export function registerAppAuth(
|
||||
const { cfg, store, discord, secure } = deps;
|
||||
const revoke = (by: { userId?: string; token?: string }) => deps.onRevoke?.(by);
|
||||
const pending = new Map<string, Pending>();
|
||||
// 한 곳에서 로그인 요청을 쏟아내 다른 사람의 로그인을 막지 못하게 (IP 당 10분에 10번)
|
||||
const beginLimit = new RateLimiter(10, LOGIN_TTL_MS);
|
||||
|
||||
const roleOf = (id: string): AppRole | null => (cfg.superAdmins.includes(id) ? 'superadmin' : (store.appUser(id)?.role ?? null));
|
||||
const sweep = () => {
|
||||
@@ -45,8 +48,9 @@ export function registerAppAuth(
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ 로그인 시작 · 결과 받기 (앱)
|
||||
app.post('/auth/app/begin', async (_req, reply) => {
|
||||
app.post('/auth/app/begin', async (req, reply) => {
|
||||
sweep();
|
||||
if (!beginLimit.hit(req.ip)) return reply.code(429).send({ error: 'rate_limited', message: '로그인 요청이 너무 많습니다. 잠시 뒤 다시 시도해 주세요' });
|
||||
if (pending.size >= MAX_PENDING) return reply.code(429).send({ error: 'busy', message: '로그인 요청이 너무 많습니다. 잠시 뒤 다시 시도해 주세요' });
|
||||
const id = crypto.randomBytes(16).toString('base64url');
|
||||
const secret = crypto.randomBytes(32).toString('base64url');
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { Config } from './config.js';
|
||||
import { registerAppAuth } from './app-auth.js';
|
||||
import { BotBroker, type BotSource } from './bot-broker.js';
|
||||
import { avatarUrl, DiscordApi } from './discord.js';
|
||||
import { RateLimiter } from './rate-limit.js';
|
||||
import { RelayHub } from './relay.js';
|
||||
import { ServerStore, type Session } from './store.js';
|
||||
|
||||
@@ -16,7 +17,16 @@ const RECHECK_MS = 10 * 60000;
|
||||
|
||||
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
|
||||
export async function buildServer(cfg: Config, opts: { botSource?: BotSource } = {}) {
|
||||
const app = Fastify({ logger: { level: process.env.LOG_LEVEL || 'info' }, trustProxy: true, bodyLimit: 1024 * 1024, forceCloseConnections: true });
|
||||
const app = Fastify({
|
||||
logger: {
|
||||
level: process.env.LOG_LEVEL || 'info',
|
||||
// 로그에 비밀값을 남기지 않는다: 로그인 주소의 code · state, 앱 로그인 요청 아이디, 기록 검색어(쿼리)는 지운다
|
||||
serializers: { req: (req) => ({ method: req.method, url: safeLogUrl(req.url), remoteAddress: req.ip }) },
|
||||
},
|
||||
trustProxy: true,
|
||||
bodyLimit: 1024 * 1024,
|
||||
forceCloseConnections: true,
|
||||
});
|
||||
const store = new ServerStore(cfg.dataDir);
|
||||
const hub = new RelayHub(store);
|
||||
const discord = new DiscordApi(cfg);
|
||||
@@ -26,6 +36,29 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource } =
|
||||
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
|
||||
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log);
|
||||
|
||||
// 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시)
|
||||
// CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게)
|
||||
const wsOrigin = cfg.publicUrl.replace(/^http/, 'ws');
|
||||
const csp = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: blob: https://cdn.discordapp.com",
|
||||
"media-src 'self' blob: data:",
|
||||
"font-src 'self' data:",
|
||||
`connect-src 'self' ${wsOrigin}`,
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
].join('; ');
|
||||
app.addHook('onSend', async (_req, reply, payload) => {
|
||||
reply.header('content-security-policy', csp);
|
||||
reply.header('x-content-type-options', 'nosniff');
|
||||
reply.header('cross-origin-opener-policy', 'same-origin');
|
||||
return payload;
|
||||
});
|
||||
|
||||
const allowedGuilds = (): string[] => {
|
||||
const g = new Set(cfg.allowedGuilds);
|
||||
const dg = store.device()?.guildId;
|
||||
@@ -93,7 +126,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource } =
|
||||
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 });
|
||||
reply.setCookie(SID, s.token, { path: '/', httpOnly: true, secure, sameSite: 'lax', maxAge: 30 * 24 * 3600, signed: true });
|
||||
return reply.redirect('/');
|
||||
} catch (e) {
|
||||
req.log.error(e, 'OAuth 실패');
|
||||
@@ -104,7 +137,8 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource } =
|
||||
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);
|
||||
const s = un?.valid && un.value ? store.session(un.value) : null;
|
||||
if (s) store.deleteSession(s.id);
|
||||
reply.clearCookie(SID, { path: '/' });
|
||||
return { ok: true };
|
||||
});
|
||||
@@ -129,8 +163,12 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource } =
|
||||
return store.createCode(s.user.id);
|
||||
});
|
||||
|
||||
// 등록 코드 무차별 대입 막기: IP 당 10분에 10번 틀리면 잠시 막는다
|
||||
const registerFails = new RateLimiter(10, 10 * 60000);
|
||||
app.post<{ Body: { code?: string; name?: string } }>('/device/register', async (req, reply) => {
|
||||
if (registerFails.blocked(req.ip)) return reply.code(429).send({ error: 'rate_limited', message: '등록 코드를 너무 많이 틀렸습니다. 10분 뒤 다시 시도해 주세요' });
|
||||
const r = store.redeem(String(req.body?.code ?? ''), String(req.body?.name ?? 'GAME-PC'));
|
||||
if (!r) registerFails.hit(req.ip);
|
||||
if (!r) return reply.code(400).send({ error: 'invalid_code', message: '등록 코드가 올바르지 않거나 만료되었습니다' });
|
||||
req.log.info('게임 PC 등록');
|
||||
return r;
|
||||
@@ -216,6 +254,12 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource } =
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/ws') {
|
||||
// 다른 사이트의 페이지가 로그인 쿠키로 실시간 기록을 엿보지 못하게 (Cross-Site WebSocket Hijacking)
|
||||
const origin = String(req.headers.origin || '');
|
||||
if (origin && origin !== cfg.publicUrl) {
|
||||
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
|
||||
return socket.destroy();
|
||||
}
|
||||
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) {
|
||||
@@ -240,6 +284,16 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource } =
|
||||
return { app, store, hub, broker };
|
||||
}
|
||||
|
||||
/** 로그에 남길 주소: /auth/* 는 쿼리를 지우고 앱 로그인 요청 아이디를 가린다, 다른 주소도 쿼리 값은 지운다 */
|
||||
export function safeLogUrl(raw: string | undefined): string {
|
||||
const u = String(raw ?? '');
|
||||
const i = u.indexOf('?');
|
||||
const path = (i < 0 ? u : u.slice(0, i)).replace(/^\/auth\/app\/start\/[^/]+/, '/auth/app/start/***');
|
||||
if (i < 0) return path;
|
||||
const keys = [...new URLSearchParams(u.slice(i + 1)).keys()];
|
||||
return `${path}?${keys.map((k) => `${k}=***`).join('&')}`;
|
||||
}
|
||||
|
||||
function parseCookies(h: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const part of h.split(';')) {
|
||||
|
||||
29
site/server/src/rate-limit.ts
Normal file
29
site/server/src/rate-limit.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
/** 아주 작은 메모리 속 횟수 제한 (IP 별). 무차별 대입 · 요청 폭주로 로그인 · 등록을 막는 것을 줄인다 */
|
||||
export class RateLimiter {
|
||||
private hits = new Map<string, number[]>();
|
||||
|
||||
constructor(
|
||||
private max: number,
|
||||
private windowMs: number,
|
||||
) {}
|
||||
|
||||
/** 한 번 센다. 창 안에서 max 를 넘으면 false */
|
||||
hit(key: string): boolean {
|
||||
const now = Date.now();
|
||||
const list = (this.hits.get(key) ?? []).filter((t) => now - t < this.windowMs);
|
||||
if (list.length >= this.max) {
|
||||
this.hits.set(key, list);
|
||||
return false;
|
||||
}
|
||||
list.push(now);
|
||||
this.hits.set(key, list);
|
||||
if (this.hits.size > 10000) for (const [k, v] of this.hits) if (!v.some((t) => now - t < this.windowMs)) this.hits.delete(k);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 세지 않고 막혔는지만 본다 */
|
||||
blocked(key: string): boolean {
|
||||
const now = Date.now();
|
||||
return (this.hits.get(key) ?? []).filter((t) => now - t < this.windowMs).length >= this.max;
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,9 @@ export interface Device {
|
||||
guildId: string | null;
|
||||
}
|
||||
export interface Session {
|
||||
/** 쿠키 값(세션 토큰)의 sha256. 토큰 자체는 저장하지 않는다 (server.json 이 새어도 로그인을 빼앗을 수 없게) */
|
||||
id: string;
|
||||
hashed?: true;
|
||||
user: { id: string; name: string; avatar: string | null };
|
||||
createdAt: number;
|
||||
checkedAt: number;
|
||||
@@ -70,9 +72,18 @@ export class ServerStore {
|
||||
}
|
||||
this.d.devices ||= [];
|
||||
this.d.sessions ||= [];
|
||||
// 예전 server.json 은 세션 토큰을 그대로 저장했다 → 해시로 바꾼다 (로그인은 유지)
|
||||
let migrated = false;
|
||||
for (const s of this.d.sessions) {
|
||||
if (s.hashed) continue;
|
||||
s.id = sha256(s.id);
|
||||
s.hashed = true;
|
||||
migrated = true;
|
||||
}
|
||||
this.d.appUsers ||= [];
|
||||
this.d.appSessions ||= [];
|
||||
this.d.appSeen ||= {};
|
||||
if (migrated) this.save(true);
|
||||
}
|
||||
|
||||
private save(now = false): void {
|
||||
@@ -151,16 +162,20 @@ export class ServerStore {
|
||||
}
|
||||
|
||||
// ---- 세션
|
||||
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 };
|
||||
/** 새 세션. token 은 쿠키에만 넣고, 서버에는 해시(id)만 남는다 */
|
||||
createSession(user: Session['user'], ttlMs = 30 * 24 * 3600 * 1000): Session & { token: string } {
|
||||
const token = crypto.randomBytes(24).toString('base64url');
|
||||
const s: Session = { id: sha256(token), hashed: true, 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;
|
||||
return { ...s, token };
|
||||
}
|
||||
session(id: string | undefined): Session | null {
|
||||
if (!id) return null;
|
||||
const s = this.d.sessions.find((x) => x.id === id);
|
||||
/** 쿠키의 세션 토큰으로 찾는다 */
|
||||
session(token: string | undefined): Session | null {
|
||||
if (!token) return null;
|
||||
const h = sha256(token);
|
||||
const s = this.d.sessions.find((x) => x.id === h);
|
||||
return s && s.expiresAt > Date.now() ? s : null;
|
||||
}
|
||||
touchSession(id: string): void {
|
||||
|
||||
Reference in New Issue
Block a user