앱 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:
@@ -7,6 +7,7 @@ import { EventEmitter } from 'node:events';
|
||||
import type { AppLoginBegin, AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared';
|
||||
import type { SettingsStore } from './settings.js';
|
||||
import { logger } from './util/log.js';
|
||||
import { secureServerUrl } from './util/secure-url.js';
|
||||
|
||||
const log = logger('auth');
|
||||
|
||||
@@ -60,7 +61,7 @@ export class AppAuth extends EventEmitter {
|
||||
return this.state.status === 'ok';
|
||||
}
|
||||
private get server(): string {
|
||||
return this.settings.get().site.serverUrl.replace(/\/$/, '');
|
||||
return secureServerUrl(this.settings.get().site.serverUrl);
|
||||
}
|
||||
|
||||
private set(patch: Partial<AuthState>): void {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guil
|
||||
import { EventEmitter } from 'node:events';
|
||||
import WebSocket from 'ws';
|
||||
import { logger } from '../util/log.js';
|
||||
import { wsUrl } from '../util/secure-url.js';
|
||||
|
||||
const log = logger('gateway');
|
||||
|
||||
@@ -196,6 +197,11 @@ export class RemoteGateway extends EventEmitter implements BotGateway {
|
||||
|
||||
/** 서버에 붙어 ready 를 받을 때까지 기다린다 (실패해도 뒤에서 계속 다시 붙는다) */
|
||||
start(): Promise<void> {
|
||||
try {
|
||||
wsUrl(this.opts.serverUrl(), '/app/bot/ws');
|
||||
} catch (e) {
|
||||
return Promise.reject(e);
|
||||
}
|
||||
this.stopped = false;
|
||||
return new Promise((resolve, reject) => {
|
||||
const t = setTimeout(() => {
|
||||
@@ -249,7 +255,15 @@ export class RemoteGateway extends EventEmitter implements BotGateway {
|
||||
this.emit('unauthorized');
|
||||
return;
|
||||
}
|
||||
const url = this.opts.serverUrl().replace(/\/$/, '').replace(/^http/, 'ws') + '/app/bot/ws';
|
||||
let url: string;
|
||||
try {
|
||||
url = wsUrl(this.opts.serverUrl(), '/app/bot/ws');
|
||||
} catch (e: any) {
|
||||
// 암호화되지 않은 주소로는 로그인 토큰을 보내지 않는다 (다시 시도하지 않음: 주소를 고쳐야 한다)
|
||||
this.lastError = e.message;
|
||||
log.error(e.message);
|
||||
return;
|
||||
}
|
||||
const ws = new WebSocket(url, { headers: { authorization: `Bearer ${token}`, 'x-gvr-version': this.opts.version }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024 });
|
||||
this.ws = ws;
|
||||
let unauthorized = false;
|
||||
|
||||
@@ -5,7 +5,7 @@ import https from 'node:https';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
/** Riot 로컬 API 는 자체 서명 인증서라 검증을 끈 에이전트로만 부른다 (127.0.0.1 전용) */
|
||||
/** Riot 로컬 API 는 자체 서명 인증서라 검증을 끈 에이전트로만 부른다. 이 PC 안(127.0.0.1 · localhost) 주소에만 쓴다 */
|
||||
const localAgent = new https.Agent({ rejectUnauthorized: false, keepAlive: true });
|
||||
|
||||
export interface HttpResult<T = any> {
|
||||
@@ -19,6 +19,8 @@ export function request<T = any>(
|
||||
): Promise<HttpResult<T>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const u = new URL(url);
|
||||
// 인증서 검증을 끄는 건 이 PC 안 주소뿐이다. 바깥 주소(Riot 원격 API 등)는 항상 검증한다 (local 을 잘못 넘겨도)
|
||||
if (opts.local && !isLocal(u)) return reject(new Error(`로컬 API 가 아닌 주소입니다: ${u.host}`));
|
||||
const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);
|
||||
const lib: any = u.protocol === 'http:' ? http : https;
|
||||
const req = lib.request(
|
||||
@@ -26,7 +28,7 @@ export function request<T = any>(
|
||||
{
|
||||
method: opts.method || 'GET',
|
||||
headers: { accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}), ...opts.headers },
|
||||
agent: u.protocol === 'https:' && (opts.local ?? isLocal(u)) ? localAgent : undefined,
|
||||
agent: u.protocol === 'https:' && isLocal(u) ? localAgent : undefined,
|
||||
timeout: opts.timeoutMs ?? 5000,
|
||||
},
|
||||
(res: any) => {
|
||||
@@ -52,7 +54,7 @@ export function request<T = any>(
|
||||
}
|
||||
|
||||
function isLocal(u: URL): boolean {
|
||||
return u.hostname === '127.0.0.1' || u.hostname === 'localhost';
|
||||
return u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '[::1]';
|
||||
}
|
||||
|
||||
export interface Lockfile {
|
||||
|
||||
@@ -3,6 +3,7 @@ import WebSocket from 'ws';
|
||||
import type { LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared';
|
||||
import type { Bus } from '../util/events.js';
|
||||
import { logger } from '../util/log.js';
|
||||
import { secureServerUrl, wsUrl } from '../util/secure-url.js';
|
||||
|
||||
const log = logger('relay');
|
||||
|
||||
@@ -60,7 +61,14 @@ export class RelayClient {
|
||||
this.status = { state: 'off', error: '사이트 서버에 등록되지 않았습니다', since: null, serverUrl: c.serverUrl };
|
||||
return;
|
||||
}
|
||||
const url = c.serverUrl.replace(/^http/, 'ws').replace(/\/$/, '') + '/device/ws';
|
||||
let url: string;
|
||||
try {
|
||||
url = wsUrl(c.serverUrl, '/device/ws');
|
||||
} catch (e: any) {
|
||||
// 암호화되지 않은 주소로는 기기 키 · 기록을 보내지 않는다
|
||||
this.status = { state: 'error', error: e.message, since: null, serverUrl: c.serverUrl };
|
||||
return;
|
||||
}
|
||||
this.status = { ...this.status, state: 'connecting', serverUrl: c.serverUrl };
|
||||
const ws = new WebSocket(url, { headers: { authorization: `Device ${c.deviceId}.${c.deviceKey}` }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024 });
|
||||
this.ws = ws;
|
||||
@@ -149,7 +157,7 @@ export class RelayClient {
|
||||
|
||||
/** 1회용 등록 코드로 이 PC 를 사이트 서버에 등록한다 */
|
||||
export async function registerDevice(serverUrl: string, code: string, name: string): Promise<{ deviceId: string; deviceKey: string }> {
|
||||
const r = await fetch(serverUrl.replace(/\/$/, '') + '/device/register', {
|
||||
const r = await fetch(secureServerUrl(serverUrl) + '/device/register', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ code: code.trim(), name }),
|
||||
|
||||
22
app/src/core/util/secure-url.ts
Normal file
22
app/src/core/util/secure-url.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
// 사이트 서버 주소 검사. 로그인 토큰 · 기기 키 · 기록이 오가므로 암호화(https/wss)되지 않은 주소로는 보내지 않는다.
|
||||
// 이 PC 안(127.0.0.1 · localhost)만 http 를 허용한다 (개발 · 테스트용)
|
||||
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
||||
|
||||
export class InsecureServerUrlError extends Error {}
|
||||
|
||||
/** 안전한 주소면 끝의 / 를 뗀 주소를, 아니면 오류를 던진다 */
|
||||
export function secureServerUrl(raw: string): string {
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(String(raw).trim());
|
||||
} catch {
|
||||
throw new InsecureServerUrlError('사이트 서버 주소가 올바르지 않습니다');
|
||||
}
|
||||
if (u.username || u.password) throw new InsecureServerUrlError('사이트 서버 주소에 아이디 · 비밀번호를 넣을 수 없습니다');
|
||||
const ok = u.protocol === 'https:' || (u.protocol === 'http:' && LOOPBACK.has(u.hostname));
|
||||
if (!ok) throw new InsecureServerUrlError('사이트 서버 주소는 https:// 로 시작해야 합니다 (암호화되지 않은 주소로는 로그인 정보와 기록을 보내지 않습니다)');
|
||||
return u.origin + u.pathname.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
/** http(s) 주소를 같은 보안 수준의 WebSocket 주소로 (https → wss, http → ws) */
|
||||
export const wsUrl = (base: string, path: string) => secureServerUrl(base).replace(/^http/, 'ws') + path;
|
||||
@@ -8,6 +8,7 @@ import { synthesize } from '../core/discord/tts.js';
|
||||
import type { Core } from '../core/index.js';
|
||||
import { registerDevice } from '../core/relay/client.js';
|
||||
import { dirSize } from '../core/retention.js';
|
||||
import { secureServerUrl } from '../core/util/secure-url.js';
|
||||
import { ADMIN_ONLY_ACTIONS, ADMIN_ONLY_MESSAGE, adminOnlyPaths, isAdminRole } from '../core/roles.js';
|
||||
import type { AppState, AuthView, DownloadProgress, GvrApi } from './api-types.js';
|
||||
import type { Finetuner } from './finetune.js';
|
||||
@@ -77,6 +78,8 @@ export function registerIpc(ctx: IpcContext) {
|
||||
getState: () => buildState(core, { ...ctx, auth: ctx.auth.state }),
|
||||
updateSettings: (patch) => {
|
||||
if (!isAdminRole(role()) && adminOnlyPaths(patch).length) throw new Error(ADMIN_ONLY_MESSAGE);
|
||||
// 사이트 서버 주소는 https 만 (로그인 토큰 · 기기 키 · 기록이 오간다)
|
||||
if (patch?.site?.serverUrl !== undefined) patch = { ...patch, site: { ...patch.site, serverUrl: secureServerUrl(patch.site.serverUrl) } };
|
||||
return core.settings.update(patch);
|
||||
},
|
||||
setSecret: (key, value) => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// 겜녹이 Electron 메인 프로세스: 트레이 아이콘 + 설정 창 + 첫 실행 마법사. 실제 일은 코어(src/core)가 한다.
|
||||
import { app, BrowserWindow, Menu, nativeImage, safeStorage, shell, Tray } from 'electron';
|
||||
import { app, BrowserWindow, Menu, nativeImage, safeStorage, session, shell, Tray } from 'electron';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { AppAuth } from '../core/auth.js';
|
||||
import { startCore, type Core } from '../core/index.js';
|
||||
import { plainCodec, SettingsStore, type SecretCodec } from '../core/settings.js';
|
||||
@@ -33,6 +34,24 @@ let tray: Tray | null = null;
|
||||
let quitting = false;
|
||||
const dataDir = resolveDataDir(opt('data-dir'));
|
||||
|
||||
// 창 보안: 설정 창(window.gvr 로 로그인 · 관리자 기능을 부를 수 있다)에는 앱에 들어 있는 화면만 띄운다.
|
||||
// 링크를 눌러 바깥 페이지가 이 창에 열리면 그 페이지가 window.gvr 를 쓸 수 있으므로, 바깥 주소는 브라우저로만 연다
|
||||
app.on('web-contents-created', (_e, wc) => {
|
||||
const own = pathToFileURL(path.join(rendererDir(), 'index.html')).href;
|
||||
const guard = (e: Electron.Event, url: string) => {
|
||||
if (url.split(/[?#]/)[0] === own) return;
|
||||
e.preventDefault();
|
||||
if (/^https?:\/\//.test(url)) void shell.openExternal(url);
|
||||
};
|
||||
wc.on('will-navigate', guard);
|
||||
wc.on('will-redirect', guard);
|
||||
wc.on('will-attach-webview', (e) => e.preventDefault());
|
||||
wc.setWindowOpenHandler(({ url }) => {
|
||||
if (/^https?:\/\//.test(url)) void shell.openExternal(url);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
});
|
||||
|
||||
function dpapiCodec(): SecretCodec {
|
||||
// Windows: safeStorage = DPAPI (현재 사용자 계정에 묶인 암호화, N-03)
|
||||
if (safeStorage.isEncryptionAvailable()) return { name: process.platform === 'win32' ? 'dpapi' : 'os-keychain', encrypt: (s) => safeStorage.encryptString(s), decrypt: (b) => safeStorage.decryptString(b) };
|
||||
@@ -80,10 +99,6 @@ function openWindow(route?: string): void {
|
||||
win?.hide();
|
||||
}
|
||||
});
|
||||
win.webContents.setWindowOpenHandler(({ url }) => {
|
||||
if (/^https?:\/\//.test(url)) void shell.openExternal(url);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
}
|
||||
|
||||
function updateTray(): void {
|
||||
@@ -260,6 +275,8 @@ function onAuthChange(): void {
|
||||
}
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
// 마이크 · 카메라 · 위치 · 알림 등 권한 요청은 모두 거절한다 (아이디 복사용 클립보드 쓰기만 허용)
|
||||
session.defaultSession.setPermissionRequestHandler((_wc, perm, cb) => cb(perm === 'clipboard-sanitized-write'));
|
||||
if (SMOKE) return smoke();
|
||||
settings = new SettingsStore(dataDir, dpapiCodec());
|
||||
auth = new AppAuth(settings, { version: app.getVersion(), openUrl: (u) => shell.openExternal(u) });
|
||||
|
||||
Reference in New Issue
Block a user