// 로그인 E2E (리눅스 · Xvfb): 실제 Electron 앱 + 이 저장소의 사이트 서버 코드 + 가짜 디스코드 OAuth. // 겜녹이 봇 토큰은 서버에만 있다. 서버가 디스코드에 붙고, 로그인한 앱이 서버 중계(/app/bot/ws)로 봇을 쓰는지까지 본다. // GVR_E2E_BOT_TOKEN=<겜녹이 봇 토큰> node --import tsx scripts/login-e2e.mts [스크린샷 폴더] // (먼저 npm run build) import { spawn } from 'node:child_process'; 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 } from '../../site/server/src/app.ts'; import { DiscordSource } from '../../site/server/src/discord-source.ts'; import { AppAuth } from '../src/core/auth.ts'; import { SettingsStore } from '../src/core/settings.ts'; const BOT = process.env.GVR_E2E_BOT_TOKEN; if (!BOT) throw new Error('GVR_E2E_BOT_TOKEN 이 필요합니다'); const shots = process.argv[2]; const SUPER = '293719842274541579'; // 친구 = 테스트봇 계정 (F&L 서버 멤버). 봇 중계는 앱 유저가 가입한 서버만 보여 주므로 실제 멤버여야 한다 const FRIEND = '1538122882528321536'; const PORT = 18931; const base = `http://127.0.0.1:${PORT}`; const work = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-login-e2e-')); const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const results: [string, boolean, string][] = []; const check = (name: string, ok: boolean, detail = '') => { results.push([name, ok, detail]); console.log(`${ok ? '✔' : '✘'} ${name}${detail ? ` · ${detail}` : ''}`); }; // ---- 가짜 디스코드: OAuth code = 로그인할 아이디, 봇 토큰으로 /users/:id 조회 const names: Record = { [SUPER]: '사금향', [FRIEND]: '테스트친구' }; const dc = http.createServer((req, res) => { const u = new URL(req.url!, 'http://x'); res.setHeader('content-type', 'application/json'); if (u.pathname === '/oauth2/token') { let b = ''; req.on('data', (c) => (b += c)); req.on('end', () => res.end(JSON.stringify({ access_token: new URLSearchParams(b).get('code') }))); return; } if (u.pathname === '/users/@me') { const id = String(req.headers.authorization).replace('Bearer ', ''); return res.end(JSON.stringify({ id, username: names[id] ?? 'x', global_name: names[id] ?? null, avatar: null })); } const m = /^\/users\/(\d+)$/.exec(u.pathname); if (m && names[m[1]!]) return res.end(JSON.stringify({ id: m[1], username: names[m[1]!], global_name: names[m[1]!], avatar: null })); res.statusCode = 404; res.end('{}'); }); await new Promise((r) => dc.listen(0, '127.0.0.1', () => r())); const dcUrl = `http://127.0.0.1:${(dc.address() as any).port}`; const source = new DiscordSource({ info: () => undefined, error: (o, m) => console.error(m, o) }); const { app: site } = await buildServer( { port: PORT, host: '127.0.0.1', publicUrl: base, clientId: 'cid', clientSecret: 's', botToken: BOT, allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: path.join(work, 'site'), webDir: '/nonexistent', version: 'e2e', discordApi: dcUrl, assetUpstream: {}, }, { botSource: source }, ); site.log.level = 'warn'; await site.listen({ host: '127.0.0.1', port: PORT }); await source.login(BOT); // 브라우저 흉내: PATH 맨 앞에 가짜 xdg-open 을 둔다 (Electron shell.openExternal 이 부른다. 실제 브라우저는 열지 않는다) // 로그인 주소 → 가짜 디스코드 → 콜백. 로그인할 아이디는 파일에서 const loginAs = path.join(work, 'login-as'); const binDir = path.join(work, 'bin'); fs.mkdirSync(binDir); const browserSh = path.join(binDir, 'xdg-open'); fs.writeFileSync( browserSh, `#!/bin/sh\nJAR=$(mktemp)\nLOC=$(curl -s -c "$JAR" -o /dev/null -w '%{redirect_url}' "$1")\nSTATE=$(printf '%s' "$LOC" | sed -n 's/.*[?&]state=\\([^&]*\\).*/\\1/p')\ncurl -s -b "$JAR" -o /dev/null "${base}/auth/discord/callback?code=$(cat ${loginAs})&state=$STATE"\nrm -f "$JAR"\n`, { mode: 0o755 }, ); const browse = (who: string) => async (url: string) => { const start = await fetch(url, { redirect: 'manual' }); const state = new URL(start.headers.get('location')!).searchParams.get('state')!; await fetch(`${base}/auth/discord/callback?code=${who}&state=${encodeURIComponent(state)}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' }); }; // 최고 관리자 (관리자 화면 API 를 대신 부른다) const adminSt = new SettingsStore(path.join(work, 'admin')); adminSt.update({ site: { serverUrl: base } }); const admin = new AppAuth(adminSt, { version: 'e2e', openUrl: browse(SUPER), pollMs: 100 }); check('최고 관리자 로그인', (await admin.login()).role === 'superadmin'); await admin.adminAddUser(FRIEND, 'user'); check('최고 관리자가 친구를 유저로 등록', (await admin.adminUsers()).users.some((u) => u.id === FRIEND && u.role === 'user')); // ---- Electron 앱 const data = path.join(work, 'app'); fs.mkdirSync(data); fs.writeFileSync(path.join(data, 'settings.json'), JSON.stringify({ firstRunDone: true, site: { serverUrl: base }, games: { valorant: false, lol: false } })); fs.writeFileSync(loginAs, FRIEND); const electron = path.join(import.meta.dirname, '..', 'node_modules', '.bin', 'electron'); const proc = spawn('xvfb-run', ['-a', electron, '.', `--data-dir=${data}`, '--remote-debugging-port=9333', '--no-sandbox'], { cwd: path.join(import.meta.dirname, '..'), env: { ...process.env, PATH: `${binDir}:${process.env.PATH}`, WAYLAND_DISPLAY: '', XDG_SESSION_TYPE: 'x11', GVR_BOT_TOKEN: '', ELECTRON_ENABLE_LOGGING: '1' }, stdio: ['ignore', 'pipe', 'pipe'], detached: true, // 끝날 때 xvfb-run · Electron 을 프로세스 그룹째 끈다 }); const logs: string[] = []; proc.stdout.on('data', (b) => logs.push(...String(b).split('\n'))); proc.stderr.on('data', (b) => logs.push(...String(b).split('\n'))); // CDP: 설정 창에서 window.gvr 호출 let ws: WebSocket | null = null; for (let i = 0; i < 60 && !ws; i++) { await sleep(1000); try { const t = ((await (await fetch('http://127.0.0.1:9333/json')).json()) as any[]).find((x) => x.type === 'page'); if (t) { ws = new WebSocket(t.webSocketDebuggerUrl); await new Promise((r) => ws!.once('open', r)); } } catch { /* 아직 */ } } if (!ws) throw new Error('Electron 창에 붙지 못했습니다\n' + logs.join('\n')); let seq = 0; const cdp = (method: string, params: any = {}) => new Promise((res) => { const id = ++seq; const on = (m: WebSocket.RawData) => { const j = JSON.parse(String(m)); if (j.id === id) { ws!.off('message', on); res(j.result); } }; ws!.on('message', on); ws!.send(JSON.stringify({ id, method, params })); }); const gvr = async (expr: string): Promise<{ ok: boolean; v?: any; err?: string }> => { const r = await cdp('Runtime.evaluate', { expression: `(async () => JSON.stringify(await (${expr})))()`, awaitPromise: true }); if (r.exceptionDetails) return { ok: false, err: r.exceptionDetails.exception?.description ?? r.exceptionDetails.text }; return { ok: true, v: r.result.value === undefined ? undefined : JSON.parse(r.result.value) }; }; const shot = async (name: string) => { if (!shots) return; await sleep(700); const r = await cdp('Page.captureScreenshot', { format: 'png' }); fs.mkdirSync(shots, { recursive: true }); fs.writeFileSync(path.join(shots, `${name}.png`), Buffer.from(r.data, 'base64')); }; try { await sleep(1500); let a = (await gvr('window.gvr.authState()')).v; check('새 설치: 로그인 화면', a.status === 'signed_out' && !a.appReady, a.status); check('로그인 전: 코어 요청 막힘', /로그인이 필요합니다/.test((await gvr('window.gvr.getState()')).err ?? '')); await shot('electron-login'); // 로그인 (브라우저 → 가짜 디스코드 → 콜백 → 앱이 결과를 받아 감) void gvr('window.gvr.authLogin()'); for (let i = 0; i < 60 && !(a?.status === 'ok' && a.appReady); i++) { await sleep(500); a = (await gvr('window.gvr.authState()')).v; } check('등록된 친구 로그인 → 앱 열림', a.status === 'ok' && a.appReady && a.role === 'user', `${a.status} ${a.role}`); let st: any = null; for (let i = 0; i < 90; i++) { st = (await gvr('window.gvr.getState()')).v; if (st?.bot.status === 'ready' || st?.bot.status === 'error') break; await sleep(500); } check('겜녹이 봇이 사이트 서버 중계로 연결', st?.bot.status === 'ready' && st.builtinBot && /사이트 서버 중계/.test(logs.join('\n')), `${st?.bot.status} ${st?.bot.user?.name ?? ''} 서버 ${st?.bot.guilds.length ?? 0}곳 ${st?.bot.error ?? ''}`); const t = (await gvr('window.gvr.testBotToken()')).v; check('겜녹이 봇 연결 확인 버튼 (토큰 없이 서버 중계)', t?.ok && t.guilds.length > 0, JSON.stringify(t).slice(0, 120)); const mem = (await gvr('window.gvr.guildMembers()')).v; check('따라갈 사람 목록 (서버 중계)', Array.isArray(mem) && mem.length > 0, `${mem?.length}명`); const stored = fs.readdirSync(data).filter((f) => fs.statSync(path.join(data, f)).isFile() && fs.readFileSync(path.join(data, f)).includes(Buffer.from(BOT))); check('로그인 후에도 앱 데이터에 봇 토큰 없음', stored.length === 0, stored.join(',')); check('계정 표시', st?.account.user?.id === FRIEND && st.account.role === 'user'); // 창 보안: 설정 창이 바깥 페이지로 넘어가지 않는다 (넘어가면 그 페이지가 window.gvr 를 쓸 수 있다) await gvr(`(location.href = 'https://127.0.0.1:1/evil', 1)`); await sleep(1500); const where = (await gvr('location.protocol + (typeof window.gvr)')).v; check('설정 창은 바깥 주소로 넘어가지 않는다', where === 'file:object', where); // 일반 유저 권한 const r1 = await gvr(`window.gvr.updateSettings({ discord: { botMode: 'custom' } })`); check('유저: 다른 봇으로 바꾸기 거절', !r1.ok && /관리자만/.test(r1.err ?? '')); const r2 = await gvr(`window.gvr.updateSettings({ storage: { retentionDays: 30 } })`); check('유저: 보관 기간 변경 거절', !r2.ok && /관리자만/.test(r2.err ?? '')); const r3 = await gvr(`window.gvr.setSecret('botToken', 'x')`); check('유저: 봇 토큰 입력 거절', !r3.ok); const r4 = await gvr(`window.gvr.clearTrainingData()`); check('유저: 학습 데이터 삭제 거절', !r4.ok && /관리자만/.test(r4.err ?? '')); const r5 = await gvr(`window.gvr.updateSettings({ general: { sfx: false } })`); check('유저: 일반 설정은 바꿀 수 있음', r5.ok && r5.v.general.sfx === false); const r6 = await gvr(`window.gvr.adminAddUser('${SUPER}', 'user')`); check('유저: 유저 등록 API 거절 (서버)', !r6.ok && /최고 관리자만/.test(r6.err ?? '')); await gvr(`(location.hash = '#/settings/storage', 1)`); await shot('electron-user-storage'); // 등록 해제 → 다시 확인하면 잠김 · 봇 멈춤 await admin.adminRemoveUser(FRIEND); a = (await gvr('window.gvr.authRecheck()')).v; check('등록 해제 후 확인 → 등록되지 않은 아이디로 잠김', a.status === 'not_registered' && !a.appReady, a.status); check('잠긴 뒤 코어 요청 막힘', /로그인이 필요합니다/.test((await gvr('window.gvr.getState()')).err ?? '')); const secrets = fs.existsSync(path.join(data, 'secrets.bin')) ? fs.readFileSync(path.join(data, 'secrets.bin')).toString('latin1') : ''; check('잠긴 뒤 앱 토큰 삭제', !secrets.includes('appToken')); await shot('electron-not-registered'); } finally { ws?.close(); try { process.kill(-proc.pid!, 'SIGTERM'); } catch { /* 이미 끝남 */ } await sleep(1500); await site.close(); await source.destroy(); dc.close(); fs.writeFileSync(path.join(work, 'electron.log'), logs.join('\n')); console.log(`작업 폴더 ${work}`); } const failed = results.filter((r) => !r[1]); console.log(`\n${results.length - failed.length}/${results.length} 통과`); process.exit(failed.length ? 1 : 0);