Files
game_voice_recorder/site/server/src/app-auth.ts
EJClaw b9431c1a15 v1.6.0: 사이트 '내 정보'(표시 이름 · 색 · 라이엇 ID · 녹음 제외) · 관리 페이지
- 사이트 오른쪽 위 내 이름 → 내 정보: 표시 이름 바꾸기/되돌리기, 색, 라이엇 ID, 녹음 제외, 로그아웃
- 관리 페이지 /admin (관리자): 게임 PC 상태 · 앱 새 버전 안내, 유저별 표시 이름 · 색 · 라이엇 ID · 녹음 제외,
  앱 등록 · 역할 · 해제(최고 관리자). /site/admin/* 는 /app/admin/* 와 같은 처리
- 서버: 표시 이름 검사(길이 · 보이지 않는 글자 · 다른 사람과 겹침), 지우면 디스코드 이름으로 되돌림,
  바뀌면 게임 PC 앱에 바로 보냄 (PUT /api/internal/names)
- 앱: PATCH /api/users/:id (본인 또는 관리자, 남의 라이엇 ID 는 관리자만), PUT /api/internal/names
- 테스트: 앱 user-settings 3개, 사이트 서버 profile-admin 3개

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 15:27:17 +09:00

329 lines
18 KiB
TypeScript

// 앱(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 → 앱이 잠긴다
// 겜녹이 봇 토큰은 앱에 보내지 않는다. 봇은 서버가 연결하고 앱은 /app/bot/ws 로 중계받는다 (bot-broker.ts)
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 { RateLimiter } from './rate-limit.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;
onRevoke?: (by: { userId?: string; token?: string }) => void;
/** 사이트 로그인 세션 (사이트 관리 화면 /site/admin/*). app.ts 가 나중에 넣는다 */
siteSession?: (req: FastifyRequest, reply: FastifyReply) => Promise<{ user: { id: string } } | null>;
/** 표시 이름이 바뀌었을 때 (게임 PC 앱에 바로 보낸다) */
onNamesChanged?: (id: string, name: string | null) => void;
},
) {
const { cfg, store, discord, secure } = deps;
const revoke = (by: { userId?: string; token?: string }) => deps.onRevoke?.(by);
const pending = new Map<string, Pending>();
// 한 곳에서 로그인 요청을 쏟아내 다른 사람의 로그인을 막지 못하게 (IP 당 10분에 10번)
const beginLimit = new RateLimiter(10, LOGIN_TTL_MS);
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 (!beginLimit.hit(req.ip)) return reply.code(429).send({ error: 'rate_limited', message: '로그인 요청이 너무 많습니다. 잠시 뒤 다시 시도해 주세요' });
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: store.nameOf(u.id, 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);
revoke({ 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, serverTime: Date.now() } satisfies AppMe;
});
app.post('/auth/app/logout', async (req) => {
const t = bearer(req);
if (t) {
store.deleteAppSession(t);
revoke({ token: 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/admins', async (req, reply) => {
if (!(await auth(req, reply))) return;
const ids = new Set(cfg.superAdmins);
for (const u of store.appUsers()) if (u.role === 'admin') ids.add(u.id);
return { ids: [...ids] };
});
// 표시 이름 (실명 숨기기): 등록된 유저는 누구나 받아 앱의 녹음 기록 · 멤버 목록에 쓴다. 바꾸기는 최고 관리자만
app.get('/app/names', async (req, reply) => {
if (!(await auth(req, reply))) return;
return { names: store.displayNames() };
});
// 관리 API 는 두 곳에서 부른다: 앱 관리자 탭(/app/admin/*, 앱 토큰) · 사이트 관리 화면(/site/admin/*, 사이트 로그인 v1.6.0~)
const siteNeed = async (req: FastifyRequest, reply: FastifyReply, level: 'admin' | 'superadmin') => {
const s = deps.siteSession ? await deps.siteSession(req, reply) : null;
if (!s) {
if (!reply.sent) reply.code(401).send({ error: 'unauthorized' });
return null;
}
// 쓰기 요청은 같은 사이트에서 온 것만 (CSRF)
const origin = String(req.headers.origin || '');
if (req.method !== 'GET' && origin && origin !== cfg.publicUrl) {
reply.code(403).send({ error: 'bad_origin' });
return null;
}
const r = siteRole(s.user.id);
const ok = r && (level === 'superadmin' ? r === 'superadmin' : r !== 'user');
if (!ok) {
reply.code(403).send({ error: 'forbidden', message: level === 'superadmin' ? '유저 등록 · 역할 바꾸기는 최고 관리자만 할 수 있습니다' : '관리자만 볼 수 있습니다' });
return null;
}
return { id: s.user.id, role: r };
};
for (const [prefix, who] of [
['/app/admin', need],
['/site/admin', siteNeed],
] as const) {
// 표시 이름: 앱에서는 최고 관리자만 (v1.2~), 사이트 관리 화면에서는 관리자도 (v1.6.0)
app.put<{ Body: { id?: string; name?: string | null } }>(`${prefix}/names`, async (req, reply) => {
const a = await who(req, reply, prefix === '/app/admin' ? 'superadmin' : 'admin');
if (!a) return;
const id = String(req.body?.id ?? '').trim();
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
const v = checkName(req.body?.name, id);
if ('error' in v) return reply.code(400).send({ error: 'bad_name', message: v.error });
store.setDisplayName(id, v.name);
req.log.info({ by: a.id, user: id, set: !!v.name }, '표시 이름 변경');
deps.onNamesChanged?.(id, v.name);
return { names: store.displayNames() };
});
app.get(`${prefix}/users`, async (req, reply) => {
if (!(await who(req, reply, 'admin'))) return;
return { users: rows(), names: store.displayNames() };
});
app.post<{ Body: { id?: string; role?: string } }>(`${prefix}/users`, async (req, reply) => {
const a = await who(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: store.nameOf(id, 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 } }>(`${prefix}/users/:id`, async (req, reply) => {
const a = await who(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 } }>(`${prefix}/users/:id`, async (req, reply) => {
const a = await who(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: '등록되지 않은 아이디입니다' });
revoke({ userId: req.params.id });
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
return { users: rows() };
});
}
/**
* 표시 이름 확인: 빈 값이면 지우기(디스코드 이름으로), 아니면 1~32자 · 제어 문자 없음 · 다른 사람의 표시 이름과 겹치지 않음
* (같은 이름이 둘이면 기록 · 범인 분석에서 누가 누군지 알 수 없다)
*/
function checkName(raw: unknown, id: string): { name: string | null } | { error: string } {
if (raw === null || raw === undefined) return { name: null };
const name = String(raw).normalize('NFC').replace(/\s+/g, ' ').trim();
if (!name) return { name: null };
if ([...name].length > 32) return { error: '이름은 32자까지입니다' };
if (/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/.test(name)) return { error: '이름에 쓸 수 없는 글자가 있습니다' };
const key = name.toLowerCase();
for (const [other, n] of Object.entries(store.displayNames())) if (other !== id && n.toLowerCase() === key) return { error: '다른 사람이 이미 쓰는 이름입니다' };
return { name };
}
const siteRole = (id: string): AppRole | null => roleOf(id) ?? (cfg.owners.includes(id) ? 'admin' : null);
/** 겜녹이 봇 중계 연결 확인: 살아 있는 앱 토큰 + 등록된 아이디 */
const verifyToken = (token: string): { userId: string; role: AppRole } | null => {
const s = store.appSession(token);
const r = s ? roleOf(s.userId) : null;
return s && r ? { userId: s.userId, role: r } : null;
};
return { completeLogin, verifyToken, roleOf, siteRole, checkName };
}
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>`,
);
}