// 앱 로그인(core/auth.ts) ↔ 실제 사이트 서버 코드(site/server) 통합 테스트. 디스코드만 가짜. 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 { buildServer } from '../../site/server/src/app.ts'; import { AppAuth } from '../src/core/auth.ts'; import { adminOnlyPaths } from '../src/core/roles.ts'; import { SettingsStore } from '../src/core/settings.ts'; const SUPER = '1352267557213573160'; const FRIEND = '111111111111111111'; const STRANGER = '222222222222222222'; const BOT = 'MTExMTExMTExMTExMTExMTEx.FAKE00.server-delivered-token-xxxxxxxx'; const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-auth-')); delete process.env.GVR_BOT_TOKEN; async function fakeDiscord() { const names: Record = { [SUPER]: '관리자', [FRIEND]: '친구', [STRANGER]: '모르는사람' }; 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') { 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], global_name: names[id], 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) => 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() { const dc = await fakeDiscord(); const { app } = await buildServer({ port: 0, host: '127.0.0.1', publicUrl: 'http://placeholder', clientId: 'cid', clientSecret: 's', botToken: BOT, allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent', version: 'test', discordApi: dc.url, assetUpstream: {}, }); await app.listen({ host: '127.0.0.1', port: 0 }); const base = `http://127.0.0.1:${(app.server.address() as any).port}`; /** 브라우저 흉내: 로그인 주소 → 디스코드(가짜) → 콜백. who = 디스코드에서 로그인한 계정 */ const browser = (who: string) => async (url: string) => { const start = await fetch(url.replace('http://placeholder', base), { redirect: 'manual' }); const state = new URL(start.headers.get('location')!).searchParams.get('state')!; const cookie = start.headers.getSetCookie()[0]!.split(';')[0]!; await fetch(`${base}/auth/discord/callback?code=${who}&state=${encodeURIComponent(state)}`, { headers: { cookie }, redirect: 'manual' }); }; const settingsFor = (dir = tmp()) => { const s = new SettingsStore(dir); s.update({ site: { serverUrl: base } }); return s; }; return { base, browser, settingsFor, close: async () => (await app.close(), dc.close()) }; } test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은 로그인해도 앱에 오지 않는다', async () => { const s = await stack(); try { // 로그인 전: 토큰 없음 → 로그인 화면 const st = s.settingsFor(); const auth = new AppAuth(st, { version: '1.2.0', openUrl: s.browser(STRANGER), pollMs: 20 }); assert.equal((await auth.check()).status, 'signed_out'); assert.equal(st.activeBotToken(), null); // 미등록 아이디 → 등록되지 않은 아이디, 토큰 없음 const r1 = await auth.login(); assert.equal(r1.status, 'not_registered'); assert.equal(r1.user?.id, STRANGER); assert.equal(st.hasSecret('appToken'), false); assert.equal(st.activeBotToken(), null); // 최고 관리자 로그인 → 앱 토큰만 받는다. 봇 토큰은 서버 응답 어디에도 없다 const adminSt = s.settingsFor(); const admin = new AppAuth(adminSt, { version: '1.2.0', openUrl: s.browser(SUPER), pollMs: 20 }); const r2 = await admin.login(); assert.equal(r2.status, 'ok'); assert.equal(r2.role, 'superadmin'); assert.equal(adminSt.hasBuiltinBot, true); assert.equal(adminSt.activeBotToken(), null); const me = await (await fetch(`${s.base}/app/me`, { headers: { authorization: `Bearer ${adminSt.getSecret('appToken')}` } })).text(); assert.ok(me.includes(SUPER) && !me.includes(BOT) && !me.includes('botToken'), me); // 최고 관리자가 친구 등록 (관리자 화면 API) const list = await admin.adminAddUser(FRIEND, 'user'); assert.ok(list.users.some((u) => u.id === FRIEND && u.role === 'user')); // 친구 로그인 → 일반 유저 const dir = tmp(); const frSt = s.settingsFor(dir); const fr = new AppAuth(frSt, { version: '1.2.0', openUrl: s.browser(FRIEND), pollMs: 20 }); const r3 = await fr.login(); assert.equal(r3.status, 'ok'); assert.equal(r3.role, 'user'); assert.equal(frSt.activeBotToken(), null); await assert.rejects(fr.adminAddUser(STRANGER, 'user'), /최고 관리자만/); await assert.rejects(fr.adminUsers(), /관리자만/); // 다시 켜도 (새 SettingsStore) 로그인 유지 assert.equal((await new AppAuth(s.settingsFor(dir), { version: '1.2.0', openUrl: () => undefined }).check()).status, 'ok'); // 봇 토큰은 이 PC 어디에도 저장되지 않는다 (테스트는 평문 codec 이라 secrets.bin 도 그대로 읽힌다) for (const f of fs.readdirSync(dir)) assert.ok(!fs.readFileSync(path.join(dir, f), 'utf8').includes(BOT), f); // 등록 해제 → 다음 확인에서 잠기고 앱 토큰을 지운다 await admin.adminRemoveUser(FRIEND); const r4 = await fr.check(); assert.equal(r4.status, 'not_registered'); assert.equal(r4.user?.id, FRIEND); assert.equal((await fr.check()).status, 'not_registered', '다시 확인해도 "등록되지 않은 아이디" 화면 유지'); assert.equal(frSt.activeBotToken(), null); assert.equal(frSt.hasSecret('appToken'), false); // 로그아웃 → 토큰 삭제, 서버에서도 무효 await admin.logout(); assert.equal(admin.state.status, 'signed_out'); assert.equal(adminSt.hasBuiltinBot, false); } finally { await s.close(); } }); test('앱 로그인: 서버에 못 붙으면 마지막 확인 후 유예 기간까지만 쓴다', async () => { const s = await stack(); const dir = tmp(); const st = s.settingsFor(dir); const auth = new AppAuth(st, { version: '1.2.0', openUrl: s.browser(SUPER), pollMs: 20 }); assert.equal((await auth.login()).status, 'ok'); await s.close(); // 서버 꺼짐 → 마지막 확인이 방금이라 오프라인으로 계속 const r = await auth.check(); assert.equal(r.status, 'ok'); assert.equal(r.offline, true); assert.equal(st.hasSecret('appToken'), true); // 유예 기간이 지나면 막힌다 (토큰은 남겨 두어 서버가 돌아오면 다시 확인) const late = new AppAuth(st, { version: '1.2.0', openUrl: () => undefined, offlineGraceMs: 0 }); const r2 = await late.check(); assert.equal(r2.status, 'error'); assert.match(r2.error!, /연결할 수 없습니다/); assert.equal(st.hasSecret('appToken'), true); }); test('관리자 전용 설정: 일반 유저가 바꾸면 안 되는 경로만 골라낸다', () => { assert.deepEqual(adminOnlyPaths({ discord: { botMode: 'custom' } }), ['discord.botMode']); assert.deepEqual(adminOnlyPaths({ discord: { guildId: 'g', ttsVoice: 'x' }, stt: { realtimeModel: 'small' } }), []); assert.deepEqual(adminOnlyPaths({ discord: { ttsEnabled: false, ttsText: 'x', ttsVoice: 'y' } }), ['discord.ttsEnabled', 'discord.ttsText']); assert.deepEqual(adminOnlyPaths({ storage: { retentionDays: 30, audioDir: 'D:/a' } }), ['storage.retentionDays']); assert.deepEqual(adminOnlyPaths({ site: { deviceName: 'x' } }), ['site']); assert.deepEqual(adminOnlyPaths({ finetune: { schedule: 'nightly' } }), ['finetune']); assert.deepEqual(adminOnlyPaths({ firstRunDone: true, general: { sfx: false } }), []); }); /** /app/me 응답을 서버가 처리한 뒤 앱에 늦게 도착하게 붙잡는다 (hold() 로 다음 요청 하나를 잡고, 반환값으로 놓아준다) */ function holdMe() { const real = globalThis.fetch; let gate: { promise: Promise; release: () => void } | null = null; globalThis.fetch = (async (input: any, init?: any) => { const r = await real(input, init); if (gate && String(input).endsWith('/app/me')) { const g = gate; gate = null; await g.promise; } return r; }) as typeof fetch; return { hold: () => { let release!: () => void; const promise = new Promise((r) => (release = r)); gate = { promise, release }; return release; }, restore: () => (globalThis.fetch = real), }; } test('늦은 확인 응답: 등록 해제로 잠긴 뒤 이전 확인의 200 이 와도 다시 열리지 않는다', async () => { const s = await stack(); const h = holdMe(); try { const admin = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(SUPER), pollMs: 20 }); await admin.login(); await admin.adminAddUser(FRIEND, 'user'); const st = s.settingsFor(); const fr = new AppAuth(st, { version: 't', openUrl: s.browser(FRIEND), pollMs: 20 }); assert.equal((await fr.login()).status, 'ok'); // A: 서버는 200 을 줬지만 응답이 늦게 온다 const release = h.hold(); const a = fr.check(); await new Promise((r) => setTimeout(r, 100)); // 그 사이 등록 해제 → B: 403 → 잠김 await admin.adminRemoveUser(FRIEND); assert.equal((await fr.check()).status, 'not_registered'); // A 의 늦은 200 도착 release(); await a; assert.equal(fr.state.status, 'not_registered', '늦은 200 이 잠금을 풀면 안 된다'); assert.equal(st.hasSecret('appToken'), false, '지운 앱 토큰이 되살아나면 안 된다'); assert.equal(st.hasSecret('auth'), false); } finally { h.restore(); await s.close(); } }); test('늦은 확인 응답: 로그아웃 뒤 이전 확인의 200 이 와도 다시 열리지 않는다', async () => { const s = await stack(); const h = holdMe(); try { const st = s.settingsFor(); const auth = new AppAuth(st, { version: 't', openUrl: s.browser(SUPER), pollMs: 20 }); assert.equal((await auth.login()).status, 'ok'); const release = h.hold(); const a = auth.check(); await new Promise((r) => setTimeout(r, 100)); await auth.logout(); assert.equal(auth.state.status, 'signed_out'); release(); await a; assert.equal(auth.state.status, 'signed_out', '늦은 200 이 로그아웃을 되돌리면 안 된다'); assert.equal(st.hasSecret('appToken'), false); assert.equal(st.hasSecret('auth'), false); } finally { h.restore(); await s.close(); } }); test('겹친 확인: 등록 해제 뒤 확인 두 개가 겹쳐도 "로그인 만료"가 아니라 "등록되지 않은 아이디"로 잠긴다', async () => { // 봇 중계가 끊기며 바로 확인하는 사이 10분 확인 · 다시 확인 버튼이 겹치는 경우. 서버는 첫 403 에서 세션을 지워 뒤 확인은 401 을 받는다 const s = await stack(); try { const admin = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(SUPER), pollMs: 20 }); await admin.login(); await admin.adminAddUser(FRIEND, 'user'); const fr = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(FRIEND), pollMs: 20 }); assert.equal((await fr.login()).status, 'ok'); await admin.adminRemoveUser(FRIEND); await Promise.all([fr.check(), fr.check()]); assert.equal(fr.state.status, 'not_registered'); assert.equal(fr.state.user?.id, FRIEND); } finally { await s.close(); } });