앱 v1.2.0: exe 디스코드 로그인 · 유저 등록 · 관리자 페이지

- 사이트 서버: 앱 로그인(/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>
This commit is contained in:
EJClaw
2026-10-15 08:08:44 +09:00
parent 4d31cfc16a
commit c2a5547a68
41 changed files with 2096 additions and 237 deletions

228
site/server/src/app-auth.ts Normal file
View File

@@ -0,0 +1,228 @@
// 앱(exe) 디스코드 로그인 · 유저 등록 · 관리자 API
// 1) 앱: POST /auth/app/begin → {id, secret, url}. url 을 브라우저로 연다
// 2) 브라우저: GET /auth/app/start/:id → 디스코드 OAuth → /auth/discord/callback (사이트 로그인과 같은 콜백, state 가 "app." 으로 시작)
// 3) 콜백: 등록된 아이디면 앱 토큰 발급, 아니면 "등록되지 않은 아이디" 결과를 남긴다
// 4) 앱: POST /auth/app/poll {id, secret} 로 결과를 받아 간다 (한 번만)
// 5) 앱: GET /app/me (Bearer 토큰) 로 주기적으로 확인. 등록 해제되면 403 → 앱이 잠긴다. 겜녹이 봇 토큰은 여기서만 내려준다
import crypto from 'node:crypto';
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import type { AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared';
import type { Config } from './config.js';
import { avatarUrl, fetchDiscordUser, type DiscordApi, type DiscordUser } from './discord.js';
import type { ServerStore } from './store.js';
const LOGIN_TTL_MS = 10 * 60000;
const MAX_PENDING = 200;
const SNOWFLAKE = /^\d{17,20}$/;
interface Pending {
secretHash: Buffer;
nonce: string;
expiresAt: number;
result: AppLoginPoll | null;
}
const sha = (s: string) => crypto.createHash('sha256').update(s).digest();
export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean }) {
const { cfg, store, discord, secure } = deps;
const pending = new Map<string, Pending>();
const roleOf = (id: string): AppRole | null => (cfg.superAdmins.includes(id) ? 'superadmin' : (store.appUser(id)?.role ?? null));
const sweep = () => {
const now = Date.now();
for (const [k, p] of pending) if (p.expiresAt <= now) pending.delete(k);
};
const userInfo = (id: string): AppUserInfo => {
const u = store.appUser(id);
const seen = store.appSeen(id);
return { id, name: u?.name || seen?.name || id, avatar: u?.avatar ?? seen?.avatar ?? null };
};
// ------------------------------------------------------------------ 로그인 시작 · 결과 받기 (앱)
app.post('/auth/app/begin', async (_req, reply) => {
sweep();
if (pending.size >= MAX_PENDING) return reply.code(429).send({ error: 'busy', message: '로그인 요청이 너무 많습니다. 잠시 뒤 다시 시도해 주세요' });
const id = crypto.randomBytes(16).toString('base64url');
const secret = crypto.randomBytes(32).toString('base64url');
const expiresAt = Date.now() + LOGIN_TTL_MS;
pending.set(id, { secretHash: sha(secret), nonce: crypto.randomBytes(16).toString('base64url'), expiresAt, result: null });
return { id, secret, url: `${cfg.publicUrl}/auth/app/start/${id}`, expiresAt };
});
app.post<{ Body: { id?: string; secret?: string } }>('/auth/app/poll', async (req, reply) => {
const id = String(req.body?.id ?? '');
const p = pending.get(id);
const ok = p && p.expiresAt > Date.now() && crypto.timingSafeEqual(p.secretHash, sha(String(req.body?.secret ?? '')));
if (!ok) return reply.code(410).send({ state: 'error', error: '로그인 요청이 만료되었습니다. 다시 로그인해 주세요' } satisfies AppLoginPoll);
if (!p.result) return { state: 'pending' } satisfies AppLoginPoll;
pending.delete(id); // 결과는 한 번만 내준다
return p.result;
});
// 브라우저: 로그인 요청 확인 → 디스코드 로그인으로
app.get<{ Params: { id: string } }>('/auth/app/start/:id', async (req, reply) => {
const p = pending.get(req.params.id);
if (!p || p.expiresAt <= Date.now() || p.result) return page(reply, 410, '로그인 요청이 만료되었습니다', '겜녹이 앱에서 로그인 버튼을 다시 눌러 주세요.');
const state = `app.${req.params.id}.${p.nonce}`;
reply.setCookie('gvr_state', state, { path: '/auth', httpOnly: true, secure, sameSite: 'lax', maxAge: 600, signed: true });
return reply.redirect(discord.authorizeUrl(state));
});
/** /auth/discord/callback 에서 state 가 "app." 이면 여기로 온다 (state 쿠키 확인은 콜백에서 끝남) */
async function completeLogin(state: string, code: string | undefined, error: string | undefined, reply: FastifyReply, log: FastifyRequest['log']) {
const [, id = '', nonce = ''] = state.split('.');
const p = pending.get(id);
if (!p || p.nonce !== nonce || p.expiresAt <= Date.now() || p.result) return page(reply, 410, '로그인 요청이 만료되었습니다', '겜녹이 앱에서 로그인 버튼을 다시 눌러 주세요.');
if (error || !code) {
p.result = { state: 'error', error: '디스코드 로그인을 취소했습니다' };
return page(reply, 200, '로그인을 취소했습니다', '겜녹이 앱에서 다시 시도할 수 있습니다.');
}
let u: DiscordUser;
try {
u = await discord.me((await discord.exchange(code)).access_token);
} catch (e) {
log.error(e, '앱 로그인 OAuth 실패');
p.result = { state: 'error', error: '디스코드 로그인에 실패했습니다. 다시 시도해 주세요' };
return page(reply, 502, '디스코드 로그인 실패', '잠시 뒤 겜녹이 앱에서 다시 시도해 주세요.');
}
const user: AppUserInfo = { id: u.id, name: u.global_name || u.username, avatar: avatarUrl(u) };
const role = roleOf(u.id);
if (!role) {
log.info({ user: u.id }, '앱 로그인 거절: 등록되지 않은 아이디');
p.result = { state: 'not_registered', user };
return page(reply, 403, '등록되지 않은 아이디입니다', `${esc(user.name)} (${u.id}) 계정은 겜녹이 사용자로 등록되어 있지 않습니다. 관리자에게 이 아이디 등록을 요청해 주세요.`);
}
// 이름 · 사진은 로그인할 때마다 최신으로
const row = store.appUser(u.id);
if (row) store.upsertAppUser({ ...row, name: user.name, avatar: user.avatar });
store.touchAppUser(u.id, { version: null, name: user.name, avatar: user.avatar });
p.result = { state: 'ok', token: store.createAppSession(u.id), user, role };
log.info({ user: u.id, role }, '앱 로그인');
return page(reply, 200, '로그인 완료', `${esc(user.name)} 님, 겜녹이 앱으로 돌아가세요. 이 창은 닫아도 됩니다.`);
}
// ------------------------------------------------------------------ 로그인 확인 (앱, Bearer 토큰)
const bearer = (req: FastifyRequest) => /^Bearer\s+(\S+)$/i.exec(String(req.headers.authorization || ''))?.[1] ?? '';
async function auth(req: FastifyRequest, reply: FastifyReply): Promise<{ id: string; role: AppRole } | null> {
const token = bearer(req);
const s = store.appSession(token);
if (!s) {
reply.code(401).send({ error: 'invalid_session', message: '다시 로그인해 주세요' });
return null;
}
const role = roleOf(s.userId);
if (!role) {
store.deleteAppSession(token);
reply.code(403).send({ error: 'not_registered', message: '등록되지 않은 아이디입니다', user: userInfo(s.userId) });
return null;
}
return { id: s.userId, role };
}
app.get('/app/me', async (req, reply) => {
const a = await auth(req, reply);
if (!a) return;
const user = userInfo(a.id);
const ver = String(req.headers['x-gvr-version'] || '').slice(0, 20) || null;
store.touchAppUser(a.id, { version: ver, name: user.name, avatar: user.avatar });
return { user, role: a.role, botToken: cfg.botToken || null, serverTime: Date.now() } satisfies AppMe;
});
app.post('/auth/app/logout', async (req) => {
const t = bearer(req);
if (t) store.deleteAppSession(t);
return { ok: true };
});
// ------------------------------------------------------------------ 관리자: 유저 등록
const rows = (): AppUserRow[] => {
const fixed: AppUserRow[] = cfg.superAdmins.map((id) => {
const seen = store.appSeen(id);
return { id, name: seen?.name ?? id, avatar: seen?.avatar ?? null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: seen?.at ?? null, lastVersion: seen?.version ?? null };
});
const rest = store
.appUsers()
.filter((u) => !cfg.superAdmins.includes(u.id))
.sort((a, b) => (a.role === b.role ? b.addedAt - a.addedAt : a.role === 'admin' ? -1 : 1))
.map((u): AppUserRow => ({ id: u.id, name: u.name, avatar: u.avatar, role: u.role, fixed: false, addedBy: u.addedBy, addedAt: u.addedAt, lastSeenAt: u.lastSeenAt, lastVersion: u.lastVersion }));
return [...fixed, ...rest];
};
const need = async (req: FastifyRequest, reply: FastifyReply, level: 'admin' | 'superadmin') => {
const a = await auth(req, reply);
if (!a) return null;
const ok = level === 'superadmin' ? a.role === 'superadmin' : a.role !== 'user';
if (!ok) {
reply.code(403).send({ error: 'forbidden', message: level === 'superadmin' ? '유저 등록은 최고 관리자만 할 수 있습니다' : '관리자만 볼 수 있습니다' });
return null;
}
return a;
};
const role = (v: unknown): 'admin' | 'user' | null => (v === 'admin' || v === 'user' ? v : null);
app.get('/app/admin/users', async (req, reply) => {
if (!(await need(req, reply, 'admin'))) return;
return { users: rows() };
});
app.post<{ Body: { id?: string; role?: string } }>('/app/admin/users', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
const id = String(req.body?.id ?? '').trim();
const r = role(req.body?.role ?? 'user');
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
if (cfg.superAdmins.includes(id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 이미 등록되어 있습니다' });
let du: DiscordUser | null;
try {
du = await fetchDiscordUser(cfg, id);
} catch (e) {
req.log.warn(e, '디스코드 계정 조회 실패');
return reply.code(502).send({ error: 'discord_error', message: '디스코드에서 계정을 확인하지 못했습니다. 잠시 뒤 다시 시도해 주세요' });
}
if (!du) return reply.code(404).send({ error: 'unknown_user', message: '디스코드에 없는 아이디입니다' });
if ((du as any).bot) return reply.code(400).send({ error: 'bot', message: '봇 계정은 등록할 수 없습니다' });
store.upsertAppUser({ id, name: du.global_name || du.username, avatar: avatarUrl(du), role: r, addedBy: a.id });
req.log.info({ by: a.id, user: id, role: r }, '앱 유저 등록');
return { users: rows() };
});
app.patch<{ Params: { id: string }; Body: { role?: string } }>('/app/admin/users/:id', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
const r = role(req.body?.role);
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 바꿀 수 없습니다' });
if (!store.setAppUserRole(req.params.id, r)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
req.log.info({ by: a.id, user: req.params.id, role: r }, '앱 유저 역할 변경');
return { users: rows() };
});
app.delete<{ Params: { id: string } }>('/app/admin/users/:id', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
return { users: rows() };
});
return { completeLogin };
}
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
/** 브라우저에 보여 줄 짧은 안내 페이지 */
function page(reply: FastifyReply, status: number, title: string, body: string) {
const ok = status === 200;
return reply
.code(status)
.type('text/html; charset=utf-8')
.send(
`<!doctype html><html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>겜녹이 · ${esc(title)}</title>` +
`<style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#0b141c;color:#e6edf3;font-family:system-ui,'Malgun Gothic',sans-serif}` +
`.c{max-width:420px;padding:32px;border-radius:14px;background:#121e29;border:1px solid #22313f;text-align:center}` +
`h1{font-size:20px;margin:12px 0;color:${ok ? '#14c1b7' : '#ff4655'}}p{color:#9fb0c0;line-height:1.6;margin:0}.i{font-size:40px}</style></head>` +
`<body><div class="c"><div class="i">${ok ? '✅' : '⛔'}</div><h1>${esc(title)}</h1><p>${body}</p></div></body></html>`,
);
}

View File

@@ -5,6 +5,7 @@ import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import type { Config } from './config.js';
import { registerAppAuth } from './app-auth.js';
import { avatarUrl, DiscordApi } from './discord.js';
import { RelayHub } from './relay.js';
import { ServerStore, type Session } from './store.js';
@@ -19,6 +20,7 @@ export async function buildServer(cfg: Config) {
const discord = new DiscordApi(cfg);
await app.register(cookie, { secret: cfg.sessionSecret });
const secure = cfg.publicUrl.startsWith('https://');
const appAuth = registerAppAuth(app, { cfg, store, discord, secure });
const allowedGuilds = (): string[] => {
const g = new Set(cfg.allowedGuilds);
@@ -70,6 +72,8 @@ export async function buildServer(cfg: Config) {
app.get<{ Querystring: { code?: string; state?: string; error?: string } }>('/auth/discord/callback', async (req, reply) => {
const st = req.cookies.gvr_state ? req.unsignCookie(req.cookies.gvr_state) : null;
reply.clearCookie('gvr_state', { path: '/auth' });
// 앱(exe) 로그인: 같은 콜백을 쓰고 state 가 "app." 으로 시작한다 (app-auth.ts)
if (st?.valid && st.value && st.value === req.query.state && st.value.startsWith('app.')) return appAuth.completeLogin(st.value, req.query.code, req.query.error, reply, req.log);
if (req.query.error) return reply.redirect('/?login=cancelled');
if (!req.query.code || !st?.valid || st.value !== req.query.state) return reply.redirect('/?login=invalid');
try {
@@ -175,7 +179,7 @@ export async function buildServer(cfg: Config) {
if (fs.existsSync(cfg.webDir)) {
await app.register(fastifyStatic, { root: cfg.webDir, wildcard: false, index: ['index.html'] });
app.setNotFoundHandler((req, reply) => {
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/game-assets/'))
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/app/') && !req.url.startsWith('/game-assets/'))
return reply.type('text/html').send(fs.readFileSync(path.join(cfg.webDir, 'index.html')));
return reply.code(404).send({ error: 'not_found' });
});

View File

@@ -9,7 +9,10 @@ export interface Config {
botToken: string;
/** 로그인 허용 디스코드 서버 (기본: M&L). 게임 PC 가 알려 준 서버도 함께 허용 */
allowedGuilds: string[];
/** 사이트 관리자 (게임 PC 등록 코드). 최고 관리자도 포함된다 */
owners: string[];
/** 앱 최고 관리자: 유저 등록·역할 변경. 지우거나 바꿀 수 없다 */
superAdmins: string[];
sessionSecret: string;
dataDir: string;
webDir: string;
@@ -19,6 +22,11 @@ export interface Config {
assetUpstream: Record<string, string>;
}
/** 앱 최고 관리자 (사용자 지정, 고정). SUPER_ADMIN_IDS 환경변수로 더할 수 있다 */
export const SUPER_ADMINS = ['293719842274541579', '1352267557213573160'];
const ids = (v: string | undefined) => (v || '').split(',').map((s) => s.trim()).filter(Boolean);
export function loadConfig(env = process.env): Config {
const need = (k: string) => {
const v = env[k];
@@ -33,7 +41,8 @@ export function loadConfig(env = process.env): Config {
clientSecret: need('DISCORD_CLIENT_SECRET'),
botToken: need('DISCORD_BOT_TOKEN'),
allowedGuilds: (env.ALLOWED_GUILD_IDS || '').split(',').map((s) => s.trim()).filter(Boolean),
owners: (env.OWNER_DISCORD_IDS || '').split(',').map((s) => s.trim()).filter(Boolean),
owners: [...new Set([...ids(env.OWNER_DISCORD_IDS), ...SUPER_ADMINS, ...ids(env.SUPER_ADMIN_IDS)])],
superAdmins: [...new Set([...SUPER_ADMINS, ...ids(env.SUPER_ADMIN_IDS)])],
sessionSecret: need('SESSION_SECRET'),
dataDir: env.DATA_DIR || path.resolve('data'),
webDir: env.WEB_DIR || path.resolve('../web/dist'),

View File

@@ -54,6 +54,14 @@ export class DiscordApi {
}
}
/** 봇 토큰으로 디스코드 계정 조회 (유저 등록 때 이름 확인). 없는 아이디면 null */
export async function fetchDiscordUser(cfg: Config, id: string): Promise<DiscordUser | null> {
const r = await fetch(`${cfg.discordApi}/users/${id}`, { headers: { authorization: `Bot ${cfg.botToken}` } });
if (r.status === 404 || r.status === 400) return null;
if (!r.ok) throw new Error(`users/${id} ${r.status}`);
return (await r.json()) as DiscordUser;
}
export function avatarUrl(u: DiscordUser): string | null {
return u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png?size=128` : null;
}

View File

@@ -18,10 +18,32 @@ export interface Session {
checkedAt: number;
expiresAt: number;
}
/** 앱(exe)을 쓸 수 있게 등록된 디스코드 계정. 최고 관리자는 설정(config)에 고정이라 여기 없어도 된다 */
export interface AppUser {
id: string;
name: string;
avatar: string | null;
role: 'admin' | 'user';
addedBy: string;
addedAt: number;
lastSeenAt: number | null;
lastVersion: string | null;
}
/** 앱 로그인 토큰 (서버는 해시만 저장) */
export interface AppSession {
tokenHash: string;
userId: string;
createdAt: number;
expiresAt: number;
}
interface Data {
devices: Device[];
codes: { code: string; expiresAt: number; createdBy: string }[];
sessions: Session[];
appUsers: AppUser[];
appSessions: AppSession[];
/** 최고 관리자의 마지막 접속 (appUsers 에 없을 수 있어 따로 둔다) */
appSeen: Record<string, { at: number; version: string | null; name: string; avatar: string | null }>;
}
// codes 는 server.json 에 두지 않는다 (codes.json)
@@ -44,10 +66,13 @@ export class ServerStore {
try {
this.d = JSON.parse(fs.readFileSync(this.file, 'utf8'));
} catch {
this.d = { devices: [], codes: [], sessions: [] };
this.d = { devices: [], codes: [], sessions: [], appUsers: [], appSessions: [], appSeen: {} };
}
this.d.devices ||= [];
this.d.sessions ||= [];
this.d.appUsers ||= [];
this.d.appSessions ||= [];
this.d.appSeen ||= {};
}
private save(now = false): void {
@@ -149,4 +174,74 @@ export class ServerStore {
this.d.sessions = this.d.sessions.filter((x) => x.id !== id);
this.save();
}
// ---- 앱 유저 등록 · 앱 로그인 토큰
appUsers(): AppUser[] {
return this.d.appUsers;
}
appUser(id: string): AppUser | null {
return this.d.appUsers.find((u) => u.id === id) ?? null;
}
upsertAppUser(u: Pick<AppUser, 'id' | 'name' | 'avatar' | 'role' | 'addedBy'>): AppUser {
const cur = this.appUser(u.id);
if (cur) {
Object.assign(cur, { name: u.name, avatar: u.avatar, role: u.role });
this.save(true);
return cur;
}
const row: AppUser = { ...u, addedAt: Date.now(), lastSeenAt: null, lastVersion: null };
this.d.appUsers.push(row);
this.save(true);
return row;
}
setAppUserRole(id: string, role: AppUser['role']): AppUser | null {
const u = this.appUser(id);
if (!u) return null;
u.role = role;
this.save(true);
return u;
}
/** 등록 해제. 그 유저의 앱 토큰은 다음 확인 때 403(등록되지 않은 아이디)을 받고 지워진다 */
removeAppUser(id: string): boolean {
const n = this.d.appUsers.length;
this.d.appUsers = this.d.appUsers.filter((u) => u.id !== id);
this.save(true);
return this.d.appUsers.length !== n;
}
appSeen(id: string): Data['appSeen'][string] | null {
return this.d.appSeen[id] ?? null;
}
touchAppUser(id: string, seen: { version: string | null; name: string; avatar: string | null }): void {
const at = Date.now();
this.d.appSeen[id] = { at, ...seen };
const u = this.appUser(id);
if (u) {
u.lastSeenAt = at;
u.lastVersion = seen.version;
}
this.save();
}
createAppSession(userId: string, ttlMs = 30 * 24 * 3600 * 1000): string {
const token = crypto.randomBytes(32).toString('base64url');
const now = Date.now();
this.d.appSessions = this.d.appSessions.filter((x) => x.expiresAt > now);
this.d.appSessions.push({ tokenHash: sha256(token), userId, createdAt: now, expiresAt: now + ttlMs });
this.save(true);
return token;
}
/** 토큰 확인. 쓸 때마다 만료를 30일 뒤로 민다 */
appSession(token: string, ttlMs = 30 * 24 * 3600 * 1000): AppSession | null {
if (!token) return null;
const h = sha256(token);
const s = this.d.appSessions.find((x) => x.tokenHash === h);
if (!s || s.expiresAt <= Date.now()) return null;
s.expiresAt = Date.now() + ttlMs;
this.save();
return s;
}
deleteAppSession(token: string): void {
const h = sha256(token);
this.d.appSessions = this.d.appSessions.filter((x) => x.tokenHash !== h);
this.save(true);
}
}

View File

@@ -0,0 +1,169 @@
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();
}
});

View File

@@ -10,7 +10,7 @@ import type { Config } from '../src/config.ts';
test('사이트 서버 재시작 → 게임 PC 자동 재연결', async () => {
const dataDir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-rc-'));
const cfg = (port: number): Config => ({
port, host: '127.0.0.1', publicUrl: 'http://127.0.0.1', clientId: 'x', clientSecret: 'x', botToken: 'x', allowedGuilds: [], owners: [],
port, host: '127.0.0.1', publicUrl: 'http://127.0.0.1', clientId: 'x', clientSecret: 'x', botToken: 'x', allowedGuilds: [], owners: [], superAdmins: [],
sessionSecret: 'y'.repeat(32), dataDir, webDir: '/nonexistent', version: 't', discordApi: 'http://127.0.0.1:1', assetUpstream: {},
});
let s = await buildServer(cfg(0));

View File

@@ -42,6 +42,7 @@ test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음
botToken: 'bot',
allowedGuilds: ['111'],
owners: ['owner1'],
superAdmins: [],
sessionSecret: 'x'.repeat(32),
dataDir: tmp(),
webDir: '/nonexistent',