// 앱(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(); 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( `겜녹이 · ${esc(title)}` + `` + `
${ok ? '✅' : '⛔'}

${esc(title)}

${body}

`, ); }