- 사이트 서버: 앱 로그인(/auth/app/begin·start·poll, 기존 OAuth 콜백 재사용), 앱 토큰(/app/me, 해시 저장), 유저 등록 API(/app/admin/users, 등록·역할·해제는 최고 관리자만, 목록은 관리자도). 최고 관리자 2명 고정 - 앱: 등록된 계정으로 로그인해야 코어(봇·녹음·사이트 연결)를 띄운다. 미등록이면 "등록되지 않은 아이디" + 아이디 표시. 10분마다 재확인, 등록 해제 시 즉시 잠금. 서버 연결 실패 시 마지막 확인 후 3일 유예 - 겜녹이 봇 토큰을 exe 에 넣지 않고 로그인한 등록 유저에게 서버가 내려준다 (잠기면 삭제). win-ci 토큰 주입 제거 - 관리자 탭(유저 등록·목록·접속 기록), 관리자 전용 설정(봇 변경·TTS 안내·보관 기간·사이트·학습 데이터·파인튜닝)은 일반 유저에게 잠금 표시 + 메인 프로세스에서 차단 - 테스트: 서버 앱 로그인 2건, 앱↔서버 통합 3건, Electron 로그인 E2E 스크립트(scripts/login-e2e.mts) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
170 lines
9.5 KiB
TypeScript
170 lines
9.5 KiB
TypeScript
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 '../src/app.ts';
|
|
import type { Config } from '../src/config.ts';
|
|
|
|
const SUPER = '293719842274541579';
|
|
const FRIEND = '111111111111111111';
|
|
const STRANGER = '222222222222222222';
|
|
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-appauth-'));
|
|
|
|
/** 가짜 디스코드: OAuth code 가 곧 로그인할 유저 아이디. 봇 토큰으로 /users/:id 조회 */
|
|
async function fakeDiscord() {
|
|
const known: Record<string, string> = { [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: known[id] ?? 'x', global_name: known[id] ?? null, avatar: null }));
|
|
}
|
|
const m = /^\/users\/(\d+)$/.exec(u.pathname);
|
|
if (m && req.headers.authorization === 'Bot bot-token' && known[m[1]!]) return res.end(JSON.stringify({ id: m[1], username: known[m[1]!], global_name: known[m[1]!], avatar: null }));
|
|
res.statusCode = 404;
|
|
res.end('{}');
|
|
});
|
|
await new Promise<void>((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 setup() {
|
|
const dc = await fakeDiscord();
|
|
const cfg: Config = {
|
|
port: 0, host: '127.0.0.1', publicUrl: 'http://127.0.0.1', clientId: 'cid', clientSecret: 's', botToken: 'bot-token',
|
|
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
|
|
version: 'test', discordApi: dc.url, assetUpstream: {},
|
|
};
|
|
const { app } = await buildServer(cfg);
|
|
await app.listen({ host: '127.0.0.1', port: 0 });
|
|
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
|
|
const post = (p: string, body: unknown, token?: string) =>
|
|
fetch(base + p, { method: 'POST', headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify(body) });
|
|
/** 앱 로그인 한 번: begin → (브라우저) start → callback → poll */
|
|
const login = async (userId: string) => {
|
|
const b = (await (await post('/auth/app/begin', {})).json()) as any;
|
|
assert.equal((await (await post('/auth/app/poll', { id: b.id, secret: b.secret })).json() as any).state, 'pending');
|
|
const start = await fetch(b.url.replace('http://127.0.0.1', base), { redirect: 'manual' });
|
|
assert.equal(start.status, 302);
|
|
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
|
|
assert.ok(state.startsWith('app.'));
|
|
const cookie = start.headers.getSetCookie()[0]!.split(';')[0]!;
|
|
const cb = await fetch(`${base}/auth/discord/callback?code=${userId}&state=${encodeURIComponent(state)}`, { headers: { cookie }, redirect: 'manual' });
|
|
const html = await cb.text();
|
|
const r = (await (await post('/auth/app/poll', { id: b.id, secret: b.secret })).json()) as any;
|
|
// 결과는 한 번만 받는다
|
|
assert.equal((await post('/auth/app/poll', { id: b.id, secret: b.secret })).status, 410);
|
|
return { r, status: cb.status, html };
|
|
};
|
|
const me = (t: string) => fetch(base + '/app/me', { headers: { authorization: `Bearer ${t}`, 'x-gvr-version': '1.2.0' } });
|
|
const close = async () => {
|
|
await app.close();
|
|
dc.close();
|
|
};
|
|
return { base, post, login, me, close };
|
|
}
|
|
|
|
test('앱 로그인: 최고 관리자는 바로 로그인, 미등록 아이디는 거절, 등록하면 로그인 · 해제하면 바로 잠김', async () => {
|
|
const s = await setup();
|
|
try {
|
|
// 비밀값이 틀리면 결과를 못 받는다
|
|
const b = (await (await s.post('/auth/app/begin', {})).json()) as any;
|
|
assert.equal((await s.post('/auth/app/poll', { id: b.id, secret: 'wrong' })).status, 410);
|
|
|
|
// 최고 관리자 (서버에 고정)
|
|
const sup = await s.login(SUPER);
|
|
assert.equal(sup.status, 200);
|
|
assert.equal(sup.r.state, 'ok');
|
|
assert.equal(sup.r.role, 'superadmin');
|
|
const meSup = (await (await s.me(sup.r.token)).json()) as any;
|
|
assert.equal(meSup.role, 'superadmin');
|
|
assert.equal(meSup.botToken, 'bot-token', '등록된 유저에게만 겜녹이 봇 토큰을 내려준다');
|
|
|
|
// 미등록 아이디
|
|
const no = await s.login(STRANGER);
|
|
assert.equal(no.status, 403);
|
|
assert.match(no.html, /등록되지 않은 아이디/);
|
|
assert.equal(no.r.state, 'not_registered');
|
|
assert.equal(no.r.user.id, STRANGER);
|
|
assert.equal(no.r.token, undefined);
|
|
|
|
// 토큰 없이 · 틀린 토큰으로는 아무것도 못 받는다
|
|
assert.equal((await fetch(s.base + '/app/me')).status, 401);
|
|
assert.equal((await s.me('nope')).status, 401);
|
|
|
|
// 최고 관리자가 친구를 유저로 등록
|
|
const add = await s.post('/app/admin/users', { id: FRIEND, role: 'user' }, sup.r.token);
|
|
assert.equal(add.status, 200);
|
|
const list = ((await add.json()) as any).users;
|
|
assert.deepEqual(list.map((u: any) => [u.id, u.role, u.fixed]), [[SUPER, 'superadmin', true], [FRIEND, 'user', false]]);
|
|
assert.equal(list[1].name, '친구');
|
|
assert.equal(list[1].addedBy, SUPER);
|
|
// 잘못된 아이디 · 없는 계정 · 최고 관리자 재등록
|
|
assert.equal((await s.post('/app/admin/users', { id: '123' }, sup.r.token)).status, 400);
|
|
assert.equal((await s.post('/app/admin/users', { id: '333333333333333333' }, sup.r.token)).status, 404);
|
|
assert.equal((await s.post('/app/admin/users', { id: SUPER }, sup.r.token)).status, 400);
|
|
|
|
const fr = await s.login(FRIEND);
|
|
assert.equal(fr.r.state, 'ok');
|
|
assert.equal(fr.r.role, 'user');
|
|
const meFr = (await (await s.me(fr.r.token)).json()) as any;
|
|
assert.equal(meFr.user.name, '친구');
|
|
// 일반 유저는 관리자 API 를 못 쓴다
|
|
assert.equal((await fetch(s.base + '/app/admin/users', { headers: { authorization: `Bearer ${fr.r.token}` } })).status, 403);
|
|
assert.equal((await s.post('/app/admin/users', { id: STRANGER }, fr.r.token)).status, 403);
|
|
|
|
// 관리자로 올리면 목록은 볼 수 있지만 등록은 못 한다 (등록은 최고 관리자만)
|
|
assert.equal((await fetch(`${s.base}/app/admin/users/${FRIEND}`, { method: 'PATCH', headers: { 'content-type': 'application/json', authorization: `Bearer ${sup.r.token}` }, body: JSON.stringify({ role: 'admin' }) })).status, 200);
|
|
const asAdmin = (await (await fetch(s.base + '/app/admin/users', { headers: { authorization: `Bearer ${fr.r.token}` } })).json()) as any;
|
|
assert.equal(asAdmin.users.find((u: any) => u.id === FRIEND).role, 'admin');
|
|
assert.equal(asAdmin.users.find((u: any) => u.id === FRIEND).lastVersion, '1.2.0', '마지막 접속 버전 기록');
|
|
assert.equal((await s.post('/app/admin/users', { id: STRANGER }, fr.r.token)).status, 403);
|
|
assert.equal((await fetch(`${s.base}/app/admin/users/${SUPER}`, { method: 'DELETE', headers: { authorization: `Bearer ${sup.r.token}` } })).status, 400, '최고 관리자는 못 지운다');
|
|
|
|
// 등록 해제 → 그 유저 토큰은 바로 무효
|
|
assert.equal((await fetch(`${s.base}/app/admin/users/${FRIEND}`, { method: 'DELETE', headers: { authorization: `Bearer ${sup.r.token}` } })).status, 200);
|
|
const revoked = await s.me(fr.r.token);
|
|
assert.equal(revoked.status, 403);
|
|
assert.equal(((await revoked.json()) as any).error, 'not_registered');
|
|
assert.equal((await s.me(fr.r.token)).status, 401, '한 번 거절한 토큰은 지운다');
|
|
const again = await s.login(FRIEND);
|
|
assert.equal(again.r.state, 'not_registered');
|
|
|
|
// 로그아웃하면 토큰 무효
|
|
await s.post('/auth/app/logout', {}, sup.r.token);
|
|
assert.equal((await s.me(sup.r.token)).status, 401);
|
|
} finally {
|
|
await s.close();
|
|
}
|
|
});
|
|
|
|
test('앱 로그인: 만료되거나 이미 쓴 요청 · 위조한 state 는 거절', async () => {
|
|
const s = await setup();
|
|
try {
|
|
assert.equal((await fetch(s.base + '/auth/app/start/nope', { redirect: 'manual' })).status, 410);
|
|
const b = (await (await s.post('/auth/app/begin', {})).json()) as any;
|
|
const start = await fetch(b.url.replace('http://127.0.0.1', s.base), { redirect: 'manual' });
|
|
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
|
|
// state 쿠키 없이 콜백 → 앱 로그인으로 처리하지 않는다
|
|
const cb = await fetch(`${s.base}/auth/discord/callback?code=${SUPER}&state=${encodeURIComponent(state)}`, { redirect: 'manual' });
|
|
assert.equal(cb.headers.get('location'), '/?login=invalid');
|
|
assert.equal(((await (await s.post('/auth/app/poll', { id: b.id, secret: b.secret })).json()) as any).state, 'pending');
|
|
// 디스코드에서 취소
|
|
const cookie = start.headers.getSetCookie()[0]!.split(';')[0]!;
|
|
await fetch(`${s.base}/auth/discord/callback?error=access_denied&state=${encodeURIComponent(state)}`, { headers: { cookie }, redirect: 'manual' });
|
|
const r = (await (await s.post('/auth/app/poll', { id: b.id, secret: b.secret })).json()) as any;
|
|
assert.equal(r.state, 'error');
|
|
} finally {
|
|
await s.close();
|
|
}
|
|
});
|