- 사이트 서버: discord.js 로 디스코드 게이트웨이에 한 번 붙고(discord-source.ts), 로그인한 앱에 WS /app/bot/ws 로 중계(bot-broker.ts) · 앱이 보낸 op 4 는 지켜보는 서버의 음성채널 참여 · 나가기만 허용하고 필드를 다시 만들어 보낸다 · 디스코드가 준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)는 음성을 가진 앱에만 넘긴다. 음성은 앱 ↔ 디스코드로 바로 · 한 서버의 봇 음성은 마지막으로 요청한 앱이 가져가고 이전 앱은 taken. 이전 앱의 늦은 나가기 무시, 음성 가진 앱이 끊기면 봇을 뺀다 · 슬래시 명령은 서버가 받아 defer 후 그 서버를 지켜보는 앱으로 보낸다 · 등록 해제 · 로그아웃하면 그 유저의 중계 연결을 바로 끊는다 (4401), 30초마다 다시 확인 - /app/me 에서 botToken 제거. 앱은 v1.2.0 이 저장해 둔 봇 토큰을 시작할 때 지운다 - 앱: BotGateway 로 디스코드 연결을 분리 (RemoteGateway = 겜녹이 봇 서버 중계, LocalGateway = 다른 봇 토큰 직접 연결) Bot 은 discord.js 객체 대신 이 인터페이스만 쓴다. 중계가 로그인 만료를 알리면 바로 다시 확인해서 잠근다 - 로그인 확인: 잠그라는 응답(401 · 403)은 겹친 확인 때문에 늦게 와도 같은 토큰이면 따른다 (겹친 두 번째 확인이 401 을 받아 "등록되지 않은 아이디" 대신 "로그인 만료"로 잠기던 문제). 미등록 화면은 다시 확인해도 유지 - 테스트: 봇 중계 4건(토큰 미노출 · 음성 정보 전달 · 다른 PC 인계 · 명령 라우팅 · 해제 시 끊김), 겹친 확인 1건 실제 디스코드: voice-e2e GVR_E2E_RELAY=1 (서버 중계로 따라 들어가 녹음 · STT · 녹음 제외), login-e2e 19/19 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
170 lines
9.6 KiB
TypeScript
170 lines
9.6 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 meText = await (await s.me(sup.r.token)).text();
|
|
assert.equal(JSON.parse(meText).role, 'superadmin');
|
|
assert.ok(!meText.includes('bot-token') && !meText.includes('botToken'), '봇 토큰은 등록된 유저에게도 보내지 않는다 (서버가 봇을 대신 연결)');
|
|
|
|
// 미등록 아이디
|
|
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();
|
|
}
|
|
});
|