From b9431c1a15b1122121f6937b2be3690732088312 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sat, 17 Oct 2026 15:27:17 +0900 Subject: [PATCH] =?UTF-8?q?v1.6.0:=20=EC=82=AC=EC=9D=B4=ED=8A=B8=20'?= =?UTF-8?q?=EB=82=B4=20=EC=A0=95=EB=B3=B4'(=ED=91=9C=EC=8B=9C=20=EC=9D=B4?= =?UTF-8?q?=EB=A6=84=20=C2=B7=20=EC=83=89=20=C2=B7=20=EB=9D=BC=EC=9D=B4?= =?UTF-8?q?=EC=97=87=20ID=20=C2=B7=20=EB=85=B9=EC=9D=8C=20=EC=A0=9C?= =?UTF-8?q?=EC=99=B8)=20=C2=B7=20=EA=B4=80=EB=A6=AC=20=ED=8E=98=EC=9D=B4?= =?UTF-8?q?=EC=A7=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 사이트 오른쪽 위 내 이름 → 내 정보: 표시 이름 바꾸기/되돌리기, 색, 라이엇 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 --- README.md | 7 + app/package-lock.json | 4 +- app/package.json | 2 +- app/src/core/api/server.ts | 35 +++ app/src/core/db/db.ts | 27 +++ app/src/core/index.ts | 1 + app/src/main/ipc.ts | 8 +- app/test/user-settings.test.ts | 82 +++++++ site/server/src/app-auth.ts | 169 +++++++++----- site/server/src/app.ts | 85 ++++++- site/server/src/config.ts | 3 + site/server/src/store.ts | 9 + site/server/test/profile-admin.test.ts | 132 +++++++++++ site/web/mock/server.mjs | 54 ++++- site/web/src/App.tsx | 2 + site/web/src/components/Header.tsx | 20 +- site/web/src/components/UserEdit.tsx | 234 +++++++++++++++++++ site/web/src/lib/api.ts | 23 ++ site/web/src/pages/AdminPage.tsx | 299 +++++++++++++++++++++++++ site/web/src/store/app.tsx | 15 +- site/web/src/styles.css | 270 ++++++++++++++++++++++ 21 files changed, 1398 insertions(+), 83 deletions(-) create mode 100644 app/test/user-settings.test.ts create mode 100644 site/server/test/profile-admin.test.ts create mode 100644 site/web/src/components/UserEdit.tsx create mode 100644 site/web/src/pages/AdminPage.tsx diff --git a/README.md b/README.md index f37db16..6bb4345 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,13 @@ - 앱은 시작할 때와 10분마다 등록 여부를 다시 확인한다. 등록이 해제되면 바로 잠그고 봇 · 녹음 · 사이트 연결을 멈춘다. 사이트 서버에 못 붙으면 마지막 확인 뒤 3일까지는 그대로 쓴다. - 서버 쪽: `site/server/src/app-auth.ts` (`/auth/app/*`, `/app/me`, `/app/admin/users`), 앱 쪽: `app/src/core/auth.ts`, 권한 목록: `app/src/core/roles.ts`. 로그인 E2E: `app/scripts/login-e2e.mts`. +## v1.6.0 바뀐 점 + +- **내 정보** (사이트 오른쪽 위 내 이름 누르기, `site/web/src/components/UserEdit.tsx`): 표시 이름 바꾸기 · 되돌리기(디스코드 서버 별명으로), 내 색, 라이엇 ID, 녹음 제외, 내 기록 보기 · 관리 페이지 · 로그아웃 + - 표시 이름은 사이트 서버에 저장하고(`PUT /site/profile/name`, 1~32자 · 보이지 않는 글자 금지 · 다른 사람 표시 이름과 겹치면 거절 · 10분에 10번) 게임 PC 앱에 바로 보낸다(`PUT /api/internal/names`, 예전 앱은 10분마다 받아 감) + - 색 · 라이엇 ID · 녹음 제외는 게임 PC 앱 기록에 저장 (`PATCH /api/users/:id`, 본인 또는 관리자. 다른 사람에게 연결된 라이엇 ID 는 본인이 가져갈 수 없음) +- **관리 페이지** `/admin` (관리자 · 최고 관리자, `site/web/src/pages/AdminPage.tsx`): 게임 PC 연결 · 앱 버전 · 새 버전 안내(Gitea 최신 릴리스), 녹음된 사람 + 앱 등록 유저 목록에서 표시 이름 · 색 · 라이엇 ID · 녹음 제외 바꾸기, 앱 등록 · 역할 · 해제(최고 관리자). 서버 `/site/admin/*` 는 앱 관리자 탭 `/app/admin/*` 와 같은 코드 (`site/server/src/app-auth.ts`). 표시 이름은 사이트에서는 관리자도 바꿀 수 있다 + ## v1.5.0 바뀐 점 - **3D 리플레이**: 발로란트 경력 탭에서 경기 리플레이를 내려받아 두면, 사이트 경기 화면 "3D 리플레이"를 열 때 게임 PC 앱이 `%LOCALAPPDATA%\VALORANT\Saved` 아래 `<경기 ID>.vrf` 를 찾아 변환해 보낸다 (처음 한 번 10초 안팎, 그 뒤로는 `GVR-Data/replays/<경기 ID>.json.gz` 보관본). 선수 10명이 3D 맵 위에서 움직이고 그때 대화가 같이 재생된다 diff --git a/app/package-lock.json b/app/package-lock.json index 1e40d3a..ac23c4e 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -1,12 +1,12 @@ { "name": "gvr-app", - "version": "1.5.0", + "version": "1.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gvr-app", - "version": "1.5.0", + "version": "1.6.0", "license": "UNLICENSED", "dependencies": { "@discordjs/voice": "^0.19.2", diff --git a/app/package.json b/app/package.json index eea9575..80590f5 100644 --- a/app/package.json +++ b/app/package.json @@ -1,7 +1,7 @@ { "name": "gvr-app", "productName": "겜녹이", - "version": "1.5.0", + "version": "1.6.0", "description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록", "private": true, "main": "dist/main.cjs", diff --git a/app/src/core/api/server.ts b/app/src/core/api/server.ts index 3a34749..d5c25f3 100644 --- a/app/src/core/api/server.ts +++ b/app/src/core/api/server.ts @@ -40,6 +40,8 @@ export interface ApiDeps { bundles?: Bundles; /** 발로란트 리플레이 (없으면 /api/replays 없음) */ replays?: Replays; + /** 사이트 서버가 새 표시 이름을 보내 왔을 때 (녹음 파일 이름 다시 맞추기) */ + onNamesChanged?: () => void; } const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']); @@ -118,6 +120,39 @@ export async function buildApi(d: ApiDeps): Promise { return { user: toUser(u, store.listAccounts()), stats: { talkMs: st.ms, count: st.n, topWords }, matches }; }); + // 유저 설정 (v1.6.0, 사이트 "내 정보" · 관리 화면): 색 · 녹음 제외 · 라이엇 ID. 본인 또는 관리자만 + app.patch<{ Params: { id: string }; Body: { color?: string; excluded?: boolean; riotIds?: string[] } }>('/api/users/:id', async (req, reply) => { + const u = store.getUser(req.params.id); + if (!u) return reply.code(404).send({ error: 'not_found', message: '이 PC 기록에 없는 유저입니다 (음성채널에서 한 번 녹음되면 생깁니다)' }); + const admin = req.headers['x-gvr-role'] === 'admin' || !req.headers['x-gvr-user']; + if (!admin && !canDelete(req, u.id)) return reply.code(403).send({ error: 'forbidden', message: '본인 또는 관리자만 바꿀 수 있습니다' }); + const b = req.body ?? {}; + if (b.color !== undefined && !/^#[0-9a-fA-F]{6}$/.test(String(b.color))) return reply.code(400).send({ error: 'bad_color', message: '색은 #rrggbb 형식입니다' }); + if (b.riotIds !== undefined && (!Array.isArray(b.riotIds) || b.riotIds.length > 5 || b.riotIds.some((r) => typeof r !== 'string' || r.length > 45))) + return reply.code(400).send({ error: 'bad_riot_ids', message: '라이엇 ID 는 5개까지, 이름#태그 형식입니다' }); + let taken: string[] = []; + store.db.transaction(() => { + if (b.color !== undefined) store.setColor(u.id, String(b.color).toLowerCase()); + if (b.excluded !== undefined) store.setExcluded(u.id, !!b.excluded); + if (b.riotIds !== undefined) taken = store.setRiotIds(u.id, b.riotIds, admin).taken; + })(); + log.info(`유저 설정 바뀜 ${u.id}: ${Object.keys(b).join(', ')}${taken.length ? ` (이미 다른 사람에게 연결된 라이엇 ID ${taken.length}개 뺌)` : ''}`); + d.bus.live({ type: 'users.updated', data: [] }); + return { user: toUser(store.getUser(u.id)!, store.listAccounts()), taken }; + }); + + // 표시 이름 (v1.6.0): 사이트에서 이름을 바꾸면 사이트 서버가 바로 보낸다 (예전 앱은 10분마다 받아 감) + app.put<{ Body: { names?: Record } }>('/api/internal/names', async (req, reply) => { + if (req.headers['x-gvr-internal'] !== '1') return reply.code(403).send({ error: 'forbidden' }); + const names = req.body?.names; + if (!names || typeof names !== 'object') return reply.code(400).send({ error: 'bad_names' }); + store.setDisplayNames(names); + timeline.invalidate(); + d.onNamesChanged?.(); + d.bus.live({ type: 'users.updated', data: [] }); + return { ok: true }; + }); + app.get<{ Querystring: Record }>('/api/timeline', async (req) => { const q = req.query; const tq: TimelineQuery = { diff --git a/app/src/core/db/db.ts b/app/src/core/db/db.ts index 07ba822..7e6a3d2 100644 --- a/app/src/core/db/db.ts +++ b/app/src/core/db/db.ts @@ -241,6 +241,10 @@ export class Store { setExcluded(id: string, excluded: boolean): void { this.db.prepare('UPDATE users SET excluded=?, updated_at=? WHERE id=?').run(excluded ? 1 : 0, Date.now(), id); } + /** 사이트 · 타임라인에서 쓰는 유저 색 (#rrggbb) */ + setColor(id: string, color: string): void { + this.db.prepare('UPDATE users SET color=?, updated_at=? WHERE id=?').run(color, Date.now(), id); + } /** 유저 평소 음량 누적 평균 (최근값에 가중치) */ updateGainProfile(id: string, lufs: number): void { const u = this.getUser(id); @@ -252,6 +256,29 @@ export class Store { listAccounts(): { user_id: string; puuid: string; riot_id: string }[] { return this.db.prepare('SELECT * FROM game_accounts').all() as any[]; } + /** + * 라이엇 ID (이름#태그) 목록으로 연결 계정을 바꾼다. 이미 연결된 것은 puuid 를 그대로 두고, 새것은 riotid: 로 두었다가 + * 경기에서 만나면 실제 puuid 로 바뀐다. 다른 사람에게 연결된 라이엇 ID 는 넣지 않고 돌려준다 (관리자는 allowTaken 으로 같이 연결) + */ + setRiotIds(userId: string, riotIds: string[], allowTaken = false): { taken: string[] } { + const all = this.listAccounts(); + const cur = all.filter((a) => a.user_id === userId); + const taken: string[] = []; + const seen = new Set(); + const next: { puuid: string; riot_id: string }[] = []; + for (const raw of riotIds) { + const r = raw.trim(); + if (!/^[^#]{1,32}#[^#]{1,8}$/.test(r) || seen.has(r.toLowerCase())) continue; + seen.add(r.toLowerCase()); + if (!allowTaken && all.some((a) => a.user_id !== userId && a.riot_id.toLowerCase() === r.toLowerCase())) { + taken.push(r); + continue; + } + next.push(cur.find((a) => a.riot_id.toLowerCase() === r.toLowerCase()) ?? { puuid: `riotid:${r}`, riot_id: r }); + } + this.setAccounts(userId, next.map((a) => ({ puuid: a.puuid, riotId: a.riot_id }))); + return { taken }; + } setAccounts(userId: string, accounts: { puuid: string; riotId: string }[]): void { const tx = this.db.transaction(() => { this.db.prepare('DELETE FROM game_accounts WHERE user_id=?').run(userId); diff --git a/app/src/core/index.ts b/app/src/core/index.ts index ad98724..9afefaa 100644 --- a/app/src/core/index.ts +++ b/app/src/core/index.ts @@ -106,6 +106,7 @@ export async function startCore(opts: CoreOptions) { trainingDir: () => paths().training, version: opts.version, replays, + onNamesChanged: () => audioNames.refreshAll(), bundles: new Bundles(store, games, () => paths().audio, opts.version, (ids) => ids.forEach((id) => audioNames.refresh(id))), overviewExtra: () => ({ guild: bot.state.guild, diff --git a/app/src/main/ipc.ts b/app/src/main/ipc.ts index ca74d19..61ae8c4 100644 --- a/app/src/main/ipc.ts +++ b/app/src/main/ipc.ts @@ -241,12 +241,8 @@ export function registerIpc(ctx: IpcContext) { return core.store.listUsers().map((u) => toUser(u, acc)); }, setRiotIds: (userId: string, riotIds: string[]) => { - const cur = core.store.listAccounts().filter((a) => a.user_id === userId); - const next = riotIds - .map((r) => r.trim()) - .filter((r) => /^.+#.+$/.test(r)) - .map((r) => cur.find((a) => a.riot_id.toLowerCase() === r.toLowerCase()) ?? { puuid: `riotid:${r}`, riot_id: r }); - core.store.setAccounts(userId, next.map((a) => ({ puuid: a.puuid, riotId: a.riot_id }))); + core.store.setRiotIds(userId, riotIds, true); + core.bus.live({ type: 'users.updated', data: [] }); }, setExcluded: (userId: string, excluded: boolean) => { core.store.setExcluded(userId, excluded); diff --git a/app/test/user-settings.test.ts b/app/test/user-settings.test.ts new file mode 100644 index 0000000..0ff4d8a --- /dev/null +++ b/app/test/user-settings.test.ts @@ -0,0 +1,82 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { Store } from '../src/core/db/db.ts'; +import { buildApi } from '../src/core/api/server.ts'; +import { Timeline } from '../src/core/timeline.ts'; +import { Bus } from '../src/core/util/events.ts'; + +const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-uset-')); +const as = (id: string, role: 'admin' | 'member' = 'member') => ({ 'x-gvr-user': encodeURIComponent(JSON.stringify({ id, name: id, avatar: null })), 'x-gvr-role': role }); + +async function setup() { + const dir = tmp(); + const store = new Store(path.join(dir, 'db.sqlite')); + const bus = new Bus(); + bus.usersProvider = () => store.listUsers().map((u) => ({ id: u.id, name: u.name, color: u.color, avatar: u.avatar, excluded: !!u.excluded, riot: [] })); + const live: any[] = []; + bus.on('live', (e) => live.push(e)); + store.upsertUser({ id: 'u1', name: '하늘', avatar: null }); + store.upsertUser({ id: 'u2', name: '민수', avatar: null }); + store.setAccounts('u2', [{ puuid: 'p2', riotId: '민수#KR1' }]); + let renamed = 0; + const app = await buildApi({ + store, + timeline: new Timeline(store), + games: {} as any, + dict: {} as any, + culprit: {} as any, + bus, + settings: () => ({}) as any, + trainingDir: () => path.join(dir, 'training'), + overviewExtra: () => ({ guild: null, recording: {} as any }), + version: 'test', + onNamesChanged: () => renamed++, + }); + return { store, app, live, renamed: () => renamed }; +} + +test('유저 설정: 본인은 색 · 녹음 제외 · 라이엇 ID 를 바꾸고, 바뀌면 사이트에 실시간으로 알린다', async () => { + const s = await setup(); + const r = await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { color: '#45D39A', excluded: true, riotIds: ['하늘#KR1', ' 하늘#KR1 ', '별빛#0001'] } }); + assert.equal(r.statusCode, 200); + const u = r.json().user; + assert.equal(u.color, '#45d39a'); + assert.equal(u.excluded, true); + assert.deepEqual(u.riot.map((x: any) => x.riotId), ['하늘#KR1', '별빛#0001'], '같은 ID 는 한 번만'); + assert.equal(s.live.at(-1).type, 'users.updated'); + assert.ok(s.live.at(-1).data.length >= 2, '실제 유저 목록을 보낸다'); + // 이미 연결된 puuid 는 그대로 둔다 + s.store.setAccounts('u1', [{ puuid: 'p1', riotId: '하늘#KR1' }]); + await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['하늘#KR1'] } }); + assert.deepEqual(s.store.listAccounts().filter((a) => a.user_id === 'u1'), [{ user_id: 'u1', puuid: 'p1', riot_id: '하늘#KR1' }]); +}); + +test('유저 설정: 다른 사람 것은 관리자만, 남의 라이엇 ID 는 본인이 가져갈 수 없다, 형식 검사', async () => { + const s = await setup(); + assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u2', headers: as('u1'), payload: { excluded: true } })).statusCode, 403); + assert.equal(s.store.getUser('u2')!.excluded, 0); + const taken = await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['민수#KR1', '하늘#KR1'] } }); + assert.deepEqual(taken.json().taken, ['민수#KR1']); + assert.deepEqual(taken.json().user.riot.map((x: any) => x.riotId), ['하늘#KR1']); + // 관리자는 다른 사람 설정도 바꾼다 + const adm = await s.app.inject({ method: 'PATCH', url: '/api/users/u2', headers: as('u1', 'admin'), payload: { excluded: true, color: '#ff4655' } }); + assert.equal(adm.statusCode, 200); + assert.equal(s.store.getUser('u2')!.excluded, 1); + assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { color: 'red' } })).statusCode, 400); + assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['a#1', 'b#2', 'c#3', 'd#4', 'e#5', 'f#6'] } })).statusCode, 400); + assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/nobody', headers: as('nobody'), payload: { excluded: true } })).statusCode, 404); +}); + +test('표시 이름: 사이트 서버(내부 요청)만 보낼 수 있고, 받으면 이름 · 녹음 파일 이름을 맞추고 알린다', async () => { + const s = await setup(); + const bad = await s.app.inject({ method: 'PUT', url: '/api/internal/names', headers: as('u1', 'admin'), payload: { names: { u1: '해커' } } }); + assert.equal(bad.statusCode, 403); + const ok = await s.app.inject({ method: 'PUT', url: '/api/internal/names', headers: { ...as('server'), 'x-gvr-internal': '1' }, payload: { names: { u1: '하늘별' } } }); + assert.equal(ok.statusCode, 200); + assert.equal(s.store.getUser('u1')!.name, '하늘별'); + assert.equal(s.renamed(), 1); + assert.equal(s.live.at(-1).type, 'users.updated'); +}); diff --git a/site/server/src/app-auth.ts b/site/server/src/app-auth.ts index c83d4c4..4ad72a6 100644 --- a/site/server/src/app-auth.ts +++ b/site/server/src/app-auth.ts @@ -28,7 +28,17 @@ 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 }, + 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); @@ -186,64 +196,109 @@ export function registerAppAuth( if (!(await auth(req, reply))) return; return { names: store.displayNames() }; }); - app.put<{ Body: { id?: string; name?: string | null } }>('/app/admin/names', async (req, reply) => { - const a = await need(req, reply, 'superadmin'); - if (!a) return; - const id = String(req.body?.id ?? '').trim(); - const name = String(req.body?.name ?? '').trim().slice(0, 32); - if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' }); - store.setDisplayName(id, name || null); - req.log.info({ by: a.id, user: id, set: !!name }, '표시 이름 변경'); - return { names: store.displayNames() }; - }); - - 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: '디스코드에서 계정을 확인하지 못했습니다. 잠시 뒤 다시 시도해 주세요' }); + // 관리 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; } - 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() }; - }); + // 쓰기 요청은 같은 사이트에서 온 것만 (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.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.get(`${prefix}/users`, async (req, reply) => { + if (!(await who(req, reply, 'admin'))) return; + return { users: rows(), names: store.displayNames() }; + }); - 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: '등록되지 않은 아이디입니다' }); - revoke({ userId: req.params.id }); - req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제'); - return { users: rows() }; - }); + 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 => { @@ -252,7 +307,7 @@ export function registerAppAuth( return s && r ? { userId: s.userId, role: r } : null; }; - return { completeLogin, verifyToken, roleOf }; + return { completeLogin, verifyToken, roleOf, siteRole, checkName }; } const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); diff --git a/site/server/src/app.ts b/site/server/src/app.ts index 2b7328f..7130a72 100644 --- a/site/server/src/app.ts +++ b/site/server/src/app.ts @@ -9,7 +9,7 @@ import { registerAppAuth } from './app-auth.js'; import { BotBroker, type BotSource } from './bot-broker.js'; import { registerCulprit, type ModelCall } from './culprit.js'; import type { KnowledgeAuto } from './culprit-prompt.js'; -import { avatarUrl, DiscordApi } from './discord.js'; +import { avatarUrl, DiscordApi, fetchDiscordUser } from './discord.js'; import { registerMaps3d } from './maps3d.js'; import { RateLimiter } from './rate-limit.js'; import { RelayHub } from './relay.js'; @@ -46,7 +46,15 @@ export async function buildServer( await app.register(cookie, { secret: cfg.sessionSecret }); const secure = cfg.publicUrl.startsWith('https://'); let broker: BotBroker | null = null; - const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) }); + const appAuth = registerAppAuth(app, { + cfg, + store, + discord, + secure, + onRevoke: (by) => broker?.kick(by), + siteSession: (req, reply) => requireSession(req, reply), + onNamesChanged: (id, name) => (name ? pushNames() : void restoreName(id).then(pushNames)), + }); if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log.child({ area: 'bot' }), opts.botRecheckMs); // 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시) @@ -214,7 +222,78 @@ export async function buildServer( app.get('/auth/me', async (req, reply) => { const s = await requireSession(req, reply); if (!s) return; - return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id) }; + return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id), role: appAuth.siteRole(s.user.id) }; + }); + + // ------------------------------------------------------------------ 내 정보 · 표시 이름 (v1.6.0) + /** 표시 이름을 게임 PC 앱에 바로 보낸다 (v1.6.0 앱. 예전 앱은 10분마다 받아 간다) */ + function pushNames(): void { + if (!hub.status().online) return; + hub + .request('PUT', '/api/internal/names', { 'x-gvr-internal': '1', 'content-type': 'application/json', accept: 'application/json' }, { id: 'server', name: '사이트 서버', avatar: null }, JSON.stringify({ names: store.displayNames() }), 10000) + .then((r) => r.status >= 400 && app.log.info({ area: 'names', status: r.status }, '게임 PC 앱이 표시 이름을 바로 받지 못함 (예전 앱은 10분 안에 받아 감)')) + .catch(() => undefined); + } + /** 표시 이름을 지우면 디스코드 이름(서버 별명 → 전역 이름 → 아이디)으로 되돌린다 */ + async function restoreName(id: string): Promise { + try { + let nick: string | null = null; + for (const g of allowedGuilds()) { + const m = await discord.memberOf(g, id); + if (m?.nick) nick = m.nick; + if (m) break; + } + const u = nick ? null : await fetchDiscordUser(cfg, id); + const name = nick || u?.global_name || u?.username; + if (name) store.restoreDiscordName(id, name); + } catch (e) { + app.log.warn({ area: 'names', err: String(e) }, '디스코드 이름 다시 받기 실패'); + } + } + // 관리 화면 머리: 게임 PC 상태 + 최신 앱 릴리스 (Gitea, 1시간 보관). 새 버전이 있으면 관리자에게 알린다 + let latest: { at: number; v: { version: string; url: string; publishedAt: string | null } | null } = { at: 0, v: null }; + async function latestRelease() { + if (!cfg.releasesApi || Date.now() - latest.at < 3600000) return latest.v; + latest.at = Date.now(); + try { + const r = await fetch(cfg.releasesApi, { signal: AbortSignal.timeout(5000), headers: { accept: 'application/json' } }); + if (r.ok) { + const j: any = await r.json(); + if (typeof j.tag_name === 'string') latest.v = { version: j.tag_name.replace(/^v/, ''), url: String(j.html_url ?? ''), publishedAt: j.published_at ?? null }; + } + } catch { + /* 다음에 다시 */ + latest.at = Date.now() - 3300000; + } + return latest.v; + } + app.get('/site/admin/overview', async (req, reply) => { + const s = await requireSession(req, reply); + if (!s) return; + const r = appAuth.siteRole(s.user.id); + if (!r || r === 'user') return reply.code(403).send({ error: 'forbidden', message: '관리자만 볼 수 있습니다' }); + const dev = store.device(); + return { device: { ...hub.status(), guildId: dev?.guildId ?? null }, latest: await latestRelease(), role: r, serverVersion: cfg.version }; + }); + const nameLimit = new RateLimiter(10, 10 * 60000); + app.get('/site/profile', async (req, reply) => { + const s = await requireSession(req, reply); + if (!s) return; + return { user: s.user, customName: store.displayNames()[s.user.id] ?? null, role: appAuth.siteRole(s.user.id) }; + }); + app.put<{ Body: { name?: string | null } }>('/site/profile/name', async (req, reply) => { + const s = await requireSession(req, reply); + if (!s) return; + const origin = String(req.headers.origin || ''); + if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' }); + if (!nameLimit.hit(s.user.id)) return reply.code(429).send({ error: 'rate_limited', message: '이름을 너무 자주 바꿨습니다. 10분 뒤 다시 해 주세요' }); + const v = appAuth.checkName(req.body?.name, s.user.id); + if ('error' in v) return reply.code(400).send({ error: 'bad_name', message: v.error }); + store.setDisplayName(s.user.id, v.name); + if (!v.name) await restoreName(s.user.id); + req.log.info({ user: s.user.id, set: !!v.name }, '내 표시 이름 변경'); + pushNames(); + return { user: s.user, customName: v.name }; }); // ------------------------------------------------------------------ 상태 · 관리 diff --git a/site/server/src/config.ts b/site/server/src/config.ts index d3fc2ff..3419bed 100644 --- a/site/server/src/config.ts +++ b/site/server/src/config.ts @@ -20,6 +20,8 @@ export interface Config { /** 테스트용: 디스코드 API 주소 바꾸기 */ discordApi: string; assetUpstream: Record; + /** 최신 앱 릴리스 (Gitea API, 관리 화면에서 새 버전 안내) */ + releasesApi?: string; /** 범인찾기 (Claude API). apiKey 가 없으면 꺼진다 (없으면 CULPRIT_DEFAULTS) */ culprit?: { apiKey: string | null; @@ -59,6 +61,7 @@ export function loadConfig(env = process.env): Config { webDir: env.WEB_DIR || path.resolve('../web/dist'), version: env.GVR_VERSION || '1.0.0', discordApi: env.DISCORD_API || 'https://discord.com/api/v10', + releasesApi: env.RELEASES_API || 'https://git.tkrmagid.kr/api/v1/repos/tkrmagid/game_voice_recorder/releases/latest', assetUpstream: { valmedia: 'https://media.valorant-api.com/', ddragon: 'https://ddragon.leagueoflegends.com/', diff --git a/site/server/src/store.ts b/site/server/src/store.ts index f9debc0..b3ca6ee 100644 --- a/site/server/src/store.ts +++ b/site/server/src/store.ts @@ -212,6 +212,15 @@ export class ServerStore { } else delete this.d.displayNames[id]; this.save(true); } + /** 표시 이름을 지운 뒤 디스코드에서 다시 받은 이름으로 세션 · 앱 유저 이름을 되돌린다 (예전 표시 이름이 남지 않게) */ + restoreDiscordName(id: string, name: string): void { + if (this.d.displayNames[id]) return; + for (const s of this.d.sessions) if (s.user.id === id) s.user.name = name; + const u = this.appUser(id); + if (u) u.name = name; + if (this.d.appSeen[id]) this.d.appSeen[id].name = name; + this.save(true); + } // ---- 앱 유저 등록 · 앱 로그인 토큰 appUsers(): AppUser[] { diff --git a/site/server/test/profile-admin.test.ts b/site/server/test/profile-admin.test.ts new file mode 100644 index 0000000..73e3bec --- /dev/null +++ b/site/server/test/profile-admin.test.ts @@ -0,0 +1,132 @@ +// 사이트 "내 정보" (표시 이름) · 관리 화면 API (v1.6.0) +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 ADMIN = '111111111111111111'; +const MEMBER = '222222222222222222'; +const OTHER = '333333333333333333'; +const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-profile-')); +const NICK: Record = { [SUPER]: '사금향', [ADMIN]: '관리', [MEMBER]: '멤버닉', [OTHER]: '다른' }; + +async function fakeDiscord() { + const srv = http.createServer((req, res) => { + const u = new URL(req.url!, 'http://x'); + res.setHeader('content-type', 'application/json'); + const m = /^\/guilds\/111\/members\/(\d+)$/.exec(u.pathname); + if (m && NICK[m[1]!]) return res.end(JSON.stringify({ nick: NICK[m[1]!], avatar: null })); + const usr = /^\/users\/(\d+)$/.exec(u.pathname); + if (usr && NICK[usr[1]!]) return res.end(JSON.stringify({ id: usr[1], username: 'u' + usr[1], global_name: NICK[usr[1]!], avatar: null })); + if (u.pathname === '/releases/latest') return res.end(JSON.stringify({ tag_name: 'v1.6.0', html_url: 'https://git.example/releases/tag/v1.6.0', published_at: '2026-10-17T00:00:00Z' })); + res.statusCode = 404; + res.end('{}'); + }); + await new Promise((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 stack() { + const dc = await fakeDiscord(); + const cfg: Config = { + port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot', + allowedGuilds: ['111'], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent', + version: 'test', discordApi: dc.url, assetUpstream: {}, releasesApi: `${dc.url}/releases/latest`, + }; + const { app, store } = await buildServer(cfg); + store.upsertAppUser({ id: ADMIN, name: '관리', avatar: null, role: 'admin', addedBy: SUPER }); + await app.listen({ host: '127.0.0.1', port: 0 }); + const base = `http://127.0.0.1:${(app.server.address() as any).port}`; + const cookieOf = (id: string) => { + const s = store.createSession({ id, name: NICK[id]!, avatar: null }); + return `gvr_sid=${app.signCookie(s.token)}`; + }; + const as = (id: string) => { + const cookie = cookieOf(id); + const call = async (method: string, p: string, body?: unknown, origin = 'https://gvr.example') => { + const r = await fetch(base + p, { method, headers: { cookie, ...(body !== undefined ? { 'content-type': 'application/json', origin } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) }); + return { status: r.status, json: (await r.json().catch(() => null)) as any }; + }; + return { get: (p: string) => call('GET', p), put: (p: string, b: unknown, o?: string) => call('PUT', p, b, o), post: (p: string, b: unknown) => call('POST', p, b), patch: (p: string, b: unknown) => call('PATCH', p, b), del: (p: string) => call('DELETE', p, {}) }; + }; + return { store, as, close: async () => (await app.close(), dc.close()) }; +} + +test('내 정보: 누구나 자기 표시 이름을 바꾸고, 지우면 디스코드 별명으로 돌아간다', async () => { + const s = await stack(); + try { + const me = s.as(MEMBER); + assert.deepEqual((await me.get('/site/profile')).json, { user: { id: MEMBER, name: '멤버닉', avatar: null }, customName: null, role: null }); + const r = await me.put('/site/profile/name', { name: ' 하늘 별 ' }); + assert.equal(r.status, 200); + assert.equal(r.json.user.name, '하늘 별'); + assert.equal((await me.get('/auth/me')).json.user.name, '하늘 별'); + assert.equal(s.store.displayNames()[MEMBER], '하늘 별'); + // 지우기 → 디스코드 서버 별명 + const back = await me.put('/site/profile/name', { name: '' }); + assert.equal(back.status, 200); + assert.equal(back.json.customName, null); + assert.equal((await me.get('/auth/me')).json.user.name, '멤버닉'); + assert.equal(s.store.displayNames()[MEMBER], undefined); + } finally { + await s.close(); + } +}); + +test('내 정보: 다른 사람 이름 · 너무 긴 이름 · 보이지 않는 글자 · 다른 사이트에서 온 요청은 막는다', async () => { + const s = await stack(); + try { + assert.equal((await s.as(OTHER).put('/site/profile/name', { name: '하늘' })).status, 200); + const me = s.as(MEMBER); + const dup = await me.put('/site/profile/name', { name: '하늘' }); + assert.equal(dup.status, 400); + assert.match(dup.json.message, /이미 쓰는 이름/); + assert.equal((await me.put('/site/profile/name', { name: '가'.repeat(33) })).status, 400); + assert.equal((await me.put('/site/profile/name', { name: '하​늘' })).status, 400); + assert.equal((await me.put('/site/profile/name', { name: '별' }, 'https://evil.example')).status, 403); + assert.equal(s.store.displayNames()[MEMBER], undefined); + } finally { + await s.close(); + } +}); + +test('관리 화면: 관리자는 목록 · 남의 표시 이름, 등록 · 역할 · 해제는 최고 관리자만, 일반 멤버는 못 들어온다', async () => { + const s = await stack(); + try { + const member = s.as(MEMBER); + const admin = s.as(ADMIN); + const sup = s.as(SUPER); + assert.equal((await member.get('/site/admin/users')).status, 403); + assert.equal((await member.get('/site/admin/overview')).status, 403); + assert.equal((await member.put('/site/admin/names', { id: OTHER, name: 'x' })).status, 403); + + const list = await admin.get('/site/admin/users'); + assert.equal(list.status, 200); + assert.deepEqual(list.json.users.map((u: any) => [u.id, u.role]), [[SUPER, 'superadmin'], [ADMIN, 'admin']]); + const ov = await admin.get('/site/admin/overview'); + assert.equal(ov.json.role, 'admin'); + assert.equal(ov.json.latest.version, '1.6.0'); + assert.equal(ov.json.device.registered, false); + + const named = await admin.put('/site/admin/names', { id: MEMBER, name: '지호' }); + assert.equal(named.status, 200); + assert.equal(named.json.names[MEMBER], '지호'); + assert.equal((await member.get('/auth/me')).json.user.name, '지호', '로그인해 있는 세션 이름도 바뀐다'); + + assert.equal((await admin.post('/site/admin/users', { id: MEMBER, role: 'user' })).status, 403); + const added = await sup.post('/site/admin/users', { id: MEMBER, role: 'user' }); + assert.equal(added.status, 200); + assert.equal(added.json.users.find((u: any) => u.id === MEMBER).name, '지호', '등록할 때도 표시 이름으로'); + assert.equal((await sup.patch(`/site/admin/users/${MEMBER}`, { role: 'admin' })).json.users.find((u: any) => u.id === MEMBER).role, 'admin'); + assert.equal((await sup.patch(`/site/admin/users/${SUPER}`, { role: 'user' })).status, 400); + assert.equal((await sup.del(`/site/admin/users/${MEMBER}`)).status, 200); + assert.equal((await member.get('/site/admin/users')).status, 403); + } finally { + await s.close(); + } +}); diff --git a/site/web/mock/server.mjs b/site/web/mock/server.mjs index e8f67d8..5b412b8 100644 --- a/site/web/mock/server.mjs +++ b/site/web/mock/server.mjs @@ -21,7 +21,21 @@ const here = path.dirname(fileURLToPath(import.meta.url)); const ASSET_DIR = path.resolve(here, '../../../docs/report/mock/assets'); const ME = { id: '310482915522101248', name: '하늘', avatar: null }; +let m0; +/** 표시 이름: 목에서는 유저 목록 이름도 같이 바꾼다 (실제로는 게임 PC 앱이 받아서 바꿈) */ +function setName(id, n) { + const u = db.users.find((x) => x.id === id); + if (u) u._orig ??= u.name; + if (n) state.names[id] = n; + else delete state.names[id]; + if (u) u.name = n || u._orig; + broadcast({ type: 'users.updated', data: db.users }); +} const state = { + names: {}, + regs: [ + { id: ME.id, name: ME.name, avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: Date.now() - 3600000, lastVersion: '1.5.0' }, + ], device: { registered: true, online: process.env.MOCK_OFFLINE !== '1', name: '하늘의 게임 PC', lastSeen: Date.now(), version: '1.0.0' }, live: process.env.MOCK_LIVE !== '0', liveInterval: Number(process.env.MOCK_LIVE_INTERVAL ?? 15000), @@ -241,7 +255,35 @@ async function handle(req, res) { if (p === '/auth/me') { if (!sess) return json(res, 401, { error: 'unauthorized' }); if (sess === 'nm') return json(res, 403, { error: 'not_member' }); - return json(res, 200, { user: ME, isOwner: true, canViewLogs: true }); + return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, isOwner: true, canViewLogs: true, role: 'superadmin' }); + } + // 내 정보 · 관리 화면 (v1.6.0) + if (p === '/site/profile') return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, customName: state.names[ME.id] ?? null, role: 'superadmin' }); + if (p === '/site/profile/name' && req.method === 'PUT') { + const b = JSON.parse((await readBody(req)) || '{}'); + const n = String(b.name ?? '').trim(); + if (n && Object.entries(state.names).some(([id, x]) => id !== ME.id && x === n)) return json(res, 400, { error: 'bad_name', message: '다른 사람이 이미 쓰는 이름입니다' }); + setName(ME.id, n); + return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, customName: state.names[ME.id] ?? null }); + } + if (p === '/site/admin/overview') return json(res, 200, { device: { ...deviceStatus(), guildId: '1200000000000000000' }, latest: { version: '1.6.0', url: 'https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.6.0', publishedAt: null }, role: 'superadmin', serverVersion: '1.0.0' }); + if (p === '/site/admin/users' && req.method === 'GET') return json(res, 200, { users: state.regs, names: state.names }); + if (p === '/site/admin/names' && req.method === 'PUT') { + const b = JSON.parse((await readBody(req)) || '{}'); + setName(String(b.id), String(b.name ?? '').trim()); + return json(res, 200, { names: state.names }); + } + if (p === '/site/admin/users' && req.method === 'POST') { + const b = JSON.parse((await readBody(req)) || '{}'); + const u = db.users.find((x) => x.id === b.id); + state.regs.push({ id: b.id, name: u?.name ?? b.id, avatar: null, role: b.role, fixed: false, addedBy: ME.id, addedAt: Date.now(), lastSeenAt: null, lastVersion: null }); + return json(res, 200, { users: state.regs }); + } + if ((m0 = p.match(/^\/site\/admin\/users\/(\d+)$/))) { + const b = req.method === 'PATCH' ? JSON.parse((await readBody(req)) || '{}') : {}; + if (req.method === 'PATCH') state.regs = state.regs.map((r) => (r.id === m0[1] ? { ...r, role: b.role } : r)); + if (req.method === 'DELETE') state.regs = state.regs.filter((r) => r.id !== m0[1]); + return json(res, 200, { users: state.regs }); } if (p.startsWith('/api/')) { @@ -273,6 +315,16 @@ async function handle(req, res) { return json(res, 200, db.users); } let m; + if ((m = p.match(/^\/api\/users\/([^/]+)$/)) && req.method === 'PATCH') { + const u = db.users.find((x) => x.id === decodeURIComponent(m[1])); + if (!u) return json(res, 404, { error: 'not_found', message: '이 PC 기록에 없는 유저입니다' }); + const b = JSON.parse((await readBody(req)) || '{}'); + if (b.color) u.color = b.color; + if (b.excluded !== undefined) u.excluded = !!b.excluded; + if (b.riotIds) u.riot = b.riotIds.map((r) => ({ puuid: `riotid:${r}`, riotId: r })); + broadcast({ type: 'users.updated', data: db.users }); + return json(res, 200, { user: u, taken: [] }); + } if ((m = p.match(/^\/api\/users\/([^/]+)$/))) { const prof = userProfile(decodeURIComponent(m[1])); return prof ? json(res, 200, prof) : json(res, 404, { error: 'not_found' }); diff --git a/site/web/src/App.tsx b/site/web/src/App.tsx index ece0806..85ce3ea 100644 --- a/site/web/src/App.tsx +++ b/site/web/src/App.tsx @@ -18,6 +18,7 @@ import { CulpritPage } from './pages/CulpritPage'; import { MatchesPage, UserPage, UsersPage } from './pages/UserPages'; import { LogsPage } from './pages/LogsPage'; import { RecordsPage } from './pages/RecordsPage'; +import { AdminPage } from './pages/AdminPage'; import { installErrorReporting } from './lib/report'; import { useLocation } from 'react-router'; @@ -75,6 +76,7 @@ function Shell() { } /> } /> } /> + } /> } /> diff --git a/site/web/src/components/Header.tsx b/site/web/src/components/Header.tsx index 24e268a..12ac82a 100644 --- a/site/web/src/components/Header.tsx +++ b/site/web/src/components/Header.tsx @@ -6,7 +6,8 @@ import { settings, useSettings, type SfxKind } from '../store/settings'; import { sfx, SFX_LABEL } from '../lib/sfx'; import { resumeAudio } from '../lib/audio'; import { Avatar, Brand } from './common'; -import { IGear, ILogout, ISearch } from './Icons'; +import { IGear, ISearch } from './Icons'; +import { ProfilePopover } from './UserEdit'; import { GAME_NAME, liveGameLine, liveGameRows } from '@gvr/shared'; function SettingsPopover({ onClose }: { onClose: () => void }) { @@ -165,10 +166,11 @@ export function SearchBox() { } export function Header() { - const { auth, logout } = useAuth(); - const { overview } = useData(); + const { auth } = useAuth(); + const { overview, userById } = useData(); const { device, locked, conn } = useStatus(); const [open, setOpen] = useState(false); + const [profile, setProfile] = useState(false); const me = auth.status === 'ok' ? auth.me.user : null; const rec = overview?.recording; const nav = [ @@ -178,6 +180,7 @@ export function Header() { ['/users', '유저'], ['/dictionary', '단어사전'], ['/culprit', '🔍 범인찾기'], + ...(auth.status === 'ok' && auth.me.canViewLogs ? ([['/admin', '🛡️ 관리']] as const) : []), ] as const; return (
@@ -211,14 +214,13 @@ export function Header() { {open && setOpen(false)} />} {me && ( -
- + -
+ ▾ + )} + {profile && setProfile(false)} />}
); diff --git a/site/web/src/components/UserEdit.tsx b/site/web/src/components/UserEdit.tsx new file mode 100644 index 0000000..2879dd4 --- /dev/null +++ b/site/web/src/components/UserEdit.tsx @@ -0,0 +1,234 @@ +// 유저 설정 고치기 (v1.6.0): 머리글 "내 정보" 와 관리 화면이 같이 쓴다 +// - 표시 이름: 사이트 서버에 저장 (디스코드 이름 대신 보일 이름, 게임 PC 앱에 바로 전달) +// - 색 · 녹음 제외 · 라이엇 ID: 게임 PC 앱 기록에 저장 (앱 v1.6.0~) +import { useEffect, useRef, useState } from 'react'; +import { Link } from 'react-router'; +import { motion } from 'framer-motion'; +import type { User } from '@gvr/shared'; +import { api, ApiError } from '../lib/api'; +import { sfx } from '../lib/sfx'; +import { useAuth, useData } from '../store/app'; +import { Avatar } from './common'; +import { ILogout } from './Icons'; + +/** 타임라인에서 잘 보이는 색들 (어두운 배경) */ +export const USER_COLORS = ['#ff4655', '#ff8a3d', '#f2b23a', '#c8e04a', '#45d39a', '#14c1b7', '#3db8ff', '#5b8cff', '#9a7bff', '#d46bff', '#ff6fb1', '#c9d1dc']; + +/** 오류를 사람이 읽을 말로 */ +export function errText(e: unknown): string { + if (e instanceof ApiError) { + if (e.status === 404 && e.code === 'Not Found') return '게임 PC 앱이 아직 이 기능을 모릅니다. 앱을 v1.6.0 이상으로 업데이트해 주세요'; + if (e.status === 503 && e.code === 'device_offline') return '게임 PC 가 꺼져 있어 저장하지 못했습니다'; + if (e.status === 504) return '게임 PC 가 답하지 않습니다. 잠시 뒤 다시 해 주세요'; + if (e.detail) return e.detail; + if (e.status === 0) return '서버에 연결하지 못했습니다'; + return `저장하지 못했습니다 (${e.status} ${e.code})`; + } + return e instanceof Error ? e.message : String(e); +} + +/** 표시 이름 입력: 저장 · 디스코드 이름으로 되돌리기 */ +export function NameEditor({ value, custom, onSave, placeholder }: { value: string; custom: boolean; onSave: (name: string) => Promise; placeholder?: string }) { + const [v, setV] = useState(value); + const [busy, setBusy] = useState(false); + const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null); + useEffect(() => setV(value), [value]); + const save = async (name: string) => { + setBusy(true); + setMsg(null); + try { + await onSave(name); + setMsg({ ok: true, text: name ? '저장했습니다' : '디스코드 이름으로 되돌렸습니다' }); + sfx('click'); + } catch (e) { + setMsg({ ok: false, text: errText(e) }); + } finally { + setBusy(false); + } + }; + return ( +
+
{ + e.preventDefault(); + if (v.trim() && v.trim() !== value) void save(v.trim()); + }} + > + setV(e.target.value)} aria-label="표시 이름" /> + + {custom && ( + + )} +
+ {msg &&
{msg.text}
} +
+ ); +} + +/** 색 · 녹음 제외 · 라이엇 ID (게임 PC 앱에 저장) */ +export function AppUserEditor({ user, self }: { user: User; self: boolean }) { + const { reloadUsers } = useData(); + const [riot, setRiot] = useState(user.riot.map((r) => r.riotId).join(', ')); + const [busy, setBusy] = useState(false); + const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null); + const riotNow = user.riot.map((r) => r.riotId).join(', '); + useEffect(() => setRiot(riotNow), [riotNow]); + const colorRef = useRef(null); + const patch = async (p: { color?: string; excluded?: boolean; riotIds?: string[] }, okText: string) => { + setBusy(true); + setMsg(null); + try { + const r = await api.updateUser(user.id, p); + reloadUsers(); + setMsg(r.taken.length ? { ok: false, text: `다른 사람에게 연결된 라이엇 ID 는 빼고 저장했습니다: ${r.taken.join(', ')}` } : { ok: true, text: okText }); + sfx('click'); + } catch (e) { + setMsg({ ok: false, text: errText(e) }); + } finally { + setBusy(false); + } + }; + const riotIds = riot + .split(/[,\n]/) + .map((x) => x.trim()) + .filter(Boolean); + const riotBad = riotIds.filter((r) => !/^[^#]{1,32}#[^#]{1,8}$/.test(r)); + return ( +
+
색
+
+ {USER_COLORS.map((c) => ( + + void patch({ color: e.target.value }, '색을 바꿨습니다')} /> +
+ +
라이엇 ID
+
{ + e.preventDefault(); + if (!riotBad.length) void patch({ riotIds }, '라이엇 ID 를 저장했습니다'); + }} + > + setRiot(e.target.value)} aria-label="라이엇 ID" /> + +
+ {riotBad.length > 0 &&
이름#태그 형식이 아닙니다: {riotBad.join(', ')}
} +
경기 기록의 선수와 연결됩니다. 새로 넣은 ID 는 다음 경기에서 확인됩니다.
+ + + {msg &&
{msg.text}
} +
+ ); +} + +/** 머리글 오른쪽 위 내 이름을 누르면 나오는 "내 정보" */ +export function ProfilePopover({ onClose }: { onClose: () => void }) { + const { auth, logout, refreshMe } = useAuth(); + const { userById } = useData(); + const ref = useRef(null); + const [custom, setCustom] = useState(null); + useEffect(() => { + const down = (e: PointerEvent) => { + if (ref.current && !ref.current.contains(e.target as Node) && !(e.target as HTMLElement).closest('.me-btn')) onClose(); + }; + const key = (e: KeyboardEvent) => e.key === 'Escape' && onClose(); + document.addEventListener('pointerdown', down); + document.addEventListener('keydown', key); + return () => { + document.removeEventListener('pointerdown', down); + document.removeEventListener('keydown', key); + }; + }, [onClose]); + useEffect(() => { + let alive = true; + fetch('/site/profile', { credentials: 'include' }) + .then((r) => (r.ok ? r.json() : null)) + .then((p) => alive && p && setCustom(!!p.customName)) + .catch(() => undefined); + return () => { + alive = false; + }; + }, []); + if (auth.status !== 'ok') return null; + const me = auth.me.user; + const u = userById(me.id); + const admin = auth.me.canViewLogs; + const roleLabel = auth.me.role === 'superadmin' ? '최고 관리자' : auth.me.role === 'admin' ? '관리자' : auth.me.role === 'user' ? '앱 유저' : admin ? '관리자' : '서버 멤버'; + return ( + +
+ +
+ {me.name} +
+ {roleLabel} · {me.id} +
+
+
+
표시 이름
+ { + const r = await api.setMyName(name); + setCustom(!!r.customName); + await refreshMe(); + }} + /> +
사이트 · 게임 PC 기록 · 범인 분석에서 디스코드 이름 대신 보입니다.
+
녹음 기록 설정
+ {u ? :
아직 녹음된 적이 없습니다. 음성채널에서 한 번 녹음되면 색 · 라이엇 ID · 녹음 제외를 바꿀 수 있습니다.
} +
+ {u && ( + + 내 기록 보기 + + )} + {admin && ( + + 🛡️ 관리 페이지 + + )} + +
+
+ ); +} diff --git a/site/web/src/lib/api.ts b/site/web/src/lib/api.ts index 1537fa9..c47d27d 100644 --- a/site/web/src/lib/api.ts +++ b/site/web/src/lib/api.ts @@ -15,6 +15,8 @@ import type { BundleInfo, BundleImportResult, NoisePhrase, + AppRole, + AppUserRow, } from '@gvr/shared'; import { reportClient } from './report'; @@ -77,6 +79,16 @@ export interface Me { isOwner: boolean; /** 사이트 로그를 볼 수 있는지 (관리자 · 최고 관리자, v1.3.6~) */ canViewLogs?: boolean; + /** 앱 역할 (등록 안 된 멤버는 null, v1.6.0~) */ + role?: AppRole | null; +} + +/** 관리 화면 머리 (v1.6.0) */ +export interface AdminOverview { + device: DeviceStatus & { guildId: string | null }; + latest: { version: string; url: string; publishedAt: string | null } | null; + role: AppRole; + serverVersion: string; } export interface StatusResponse { device: DeviceStatus; @@ -119,6 +131,17 @@ export const api = { /** 관리자(OWNER_DISCORD_IDS) 전용: 게임 PC 1회용 등록 코드 (10분) */ registrationCode: () => request<{ code: string; expiresAt: number }>('/admin/registration-code', { method: 'POST' }), status: () => request('/api/status'), + // 내 정보 · 관리 화면 (v1.6.0) + setMyName: (name: string) => request<{ user: Me['user']; customName: string | null }>('/site/profile/name', { method: 'PUT', body: JSON.stringify({ name }) }), + /** 색 · 녹음 제외 · 라이엇 ID (게임 PC 앱 v1.6.0~, 본인 또는 관리자) */ + updateUser: (id: string, patch: { color?: string; excluded?: boolean; riotIds?: string[] }) => + request<{ user: User; taken: string[] }>(`/api/users/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(patch) }), + adminOverview: () => request('/site/admin/overview'), + adminUsers: () => request<{ users: AppUserRow[]; names: Record }>('/site/admin/users'), + adminSetName: (id: string, name: string) => request<{ names: Record }>('/site/admin/names', { method: 'PUT', body: JSON.stringify({ id, name }) }), + adminAddUser: (id: string, role: 'admin' | 'user') => request<{ users: AppUserRow[] }>('/site/admin/users', { method: 'POST', body: JSON.stringify({ id, role }) }), + adminSetRole: (id: string, role: 'admin' | 'user') => request<{ users: AppUserRow[] }>(`/site/admin/users/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ role }) }), + adminRemoveUser: (id: string) => request<{ users: AppUserRow[] }>(`/site/admin/users/${encodeURIComponent(id)}`, { method: 'DELETE' }), overview: () => request('/api/overview'), users: () => request('/api/users'), user: (id: string) => request(`/api/users/${encodeURIComponent(id)}`), diff --git a/site/web/src/pages/AdminPage.tsx b/site/web/src/pages/AdminPage.tsx new file mode 100644 index 0000000..619da96 --- /dev/null +++ b/site/web/src/pages/AdminPage.tsx @@ -0,0 +1,299 @@ +// 관리 페이지 (v1.6.0, 관리자 · 최고 관리자) +// - 게임 PC: 연결 · 앱 버전 · 새 버전 안내 +// - 유저: 표시 이름 · 색 · 녹음 제외 · 라이엇 ID (녹음된 사람), 앱 등록 · 역할 · 해제 (최고 관리자) +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { Link } from 'react-router'; +import type { AppUserRow, User } from '@gvr/shared'; +import { api, type AdminOverview } from '../lib/api'; +import { fmtDay } from '../lib/format'; +import { useAuth, useData } from '../store/app'; +import { Avatar, ErrorBox, Panel, Spinner } from '../components/common'; +import { AppUserEditor, errText, NameEditor } from '../components/UserEdit'; + +const ROLE: Record = { superadmin: '최고 관리자', admin: '관리자', user: '앱 유저' }; + +/** "1.4.1" < "1.5.0" */ +export function olderVersion(a: string | null | undefined, b: string | null | undefined): boolean { + if (!a || !b) return false; + const pa = a.split('.').map((x) => parseInt(x, 10) || 0); + const pb = b.split('.').map((x) => parseInt(x, 10) || 0); + for (let i = 0; i < Math.max(pa.length, pb.length); i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) < (pb[i] ?? 0); + return false; +} + +const when = (t: number | null) => (t ? `${fmtDay(t)} ${new Date(t).toLocaleTimeString('ko-KR', { hour12: false, hour: '2-digit', minute: '2-digit' })}` : '—'); + +interface Row { + id: string; + name: string; + avatar: string | null; + /** 녹음 기록에 있는 사람 (게임 PC 앱) */ + user: User | null; + /** 앱 등록 (사이트 서버) */ + reg: AppUserRow | null; +} + +export function AdminPage() { + const { auth } = useAuth(); + const { users } = useData(); + const [ov, setOv] = useState(null); + const [regs, setRegs] = useState(null); + const [names, setNames] = useState>({}); + const [err, setErr] = useState(null); + const [open, setOpen] = useState(null); + const [q, setQ] = useState(''); + const load = useCallback(() => { + setErr(null); + Promise.all([api.adminOverview(), api.adminUsers()]) + .then(([o, u]) => { + setOv(o); + setRegs(u.users); + setNames(u.names ?? {}); + }) + .catch(setErr); + }, []); + useEffect(load, [load]); + const sup = ov?.role === 'superadmin'; + + const rows = useMemo(() => { + const m = new Map(); + for (const u of users) m.set(u.id, { id: u.id, name: u.name, avatar: u.avatar, user: u, reg: null }); + for (const r of regs ?? []) { + const cur = m.get(r.id); + if (cur) cur.reg = r; + else m.set(r.id, { id: r.id, name: r.name, avatar: r.avatar, user: null, reg: r }); + } + const order = (r: Row) => (r.reg?.role === 'superadmin' ? 0 : r.reg?.role === 'admin' ? 1 : r.reg ? 2 : 3); + const k = q.trim().toLowerCase(); + return [...m.values()] + .filter((r) => !k || r.name.toLowerCase().includes(k) || r.id.includes(k) || r.user?.riot.some((x) => x.riotId.toLowerCase().includes(k))) + .sort((a, b) => order(a) - order(b) || a.name.localeCompare(b.name, 'ko')); + }, [users, regs, q]); + + if (auth.status !== 'ok' || !auth.me.canViewLogs) + return ( +
+

관리

+
관리자만 볼 수 있습니다.
+
+ ); + if (err) return
; + if (!ov || !regs) return
; + + const dev = ov.device; + const outdated = olderVersion(dev.version, ov.latest?.version); + return ( +
+
+

🛡️ 관리

+
+ + 📄 사이트 로그 + + +
+
+ + +
+
+ {dev.name ?? '등록된 PC 없음'} + · {dev.online ? '연결됨' : dev.lastSeen ? `마지막 연결 ${when(dev.lastSeen)}` : '연결 안 됨'} +
+
+ 앱 {dev.version ?? '?'} + {ov.latest && ( + + {' '} + · 최신 {ov.latest.version} + + )} + {outdated && ov.latest && ( + + 새 버전 v{ov.latest.version} 받기 → + + )} +
+ {outdated &&
게임 PC 앱이 최신이 아닙니다. 색 · 녹음 제외 · 라이엇 ID 바꾸기와 3D 리플레이는 최신 앱에서 됩니다.
} +
+
+ + setQ(e.target.value)} aria-label="유저 찾기" />} + > +
+ 표시 이름은 디스코드 이름 대신 사이트 · 게임 PC 기록 · 범인 분석에 보입니다 (관리자). 앱 등록 · 역할 바꾸기 · 등록 해제는 최고 관리자만 할 수 있습니다. +
+
+ {rows.map((r) => ( + setOpen((o) => (o === r.id ? null : r.id))} + onNames={setNames} + onRegs={setRegs} + /> + ))} +
+ {sup && } +
+
+ ); +} + +function AdminUserRow({ + r, + custom, + sup, + open, + onToggle, + onNames, + onRegs, +}: { + r: Row; + custom: boolean; + sup: boolean; + open: boolean; + onToggle: () => void; + onNames: (n: Record) => void; + onRegs: (u: AppUserRow[]) => void; +}) { + const { reloadUsers } = useData(); + const { auth, refreshMe } = useAuth(); + const [msg, setMsg] = useState(null); + const [busy, setBusy] = useState(false); + const act = async (fn: () => Promise<{ users: AppUserRow[] }>) => { + setBusy(true); + setMsg(null); + try { + onRegs((await fn()).users); + } catch (e) { + setMsg(errText(e)); + } finally { + setBusy(false); + } + }; + const role = r.reg?.role ?? null; + return ( +
+ + {open && ( +
+
표시 이름
+ { + const res = await api.adminSetName(r.id, name); + onNames(res.names); + // 게임 PC 앱이 이름을 받아 유저 목록을 다시 보낸다. 조금 기다렸다가 다시 받는다 + window.setTimeout(reloadUsers, 1500); + if (auth.status === 'ok' && auth.me.user.id === r.id) await refreshMe(); + const regs = await api.adminUsers().catch(() => null); + if (regs) onRegs(regs.users); + }} + /> + {r.user ? ( + + ) : ( +
이 PC 녹음 기록에 없는 사람입니다. 음성채널에서 한 번 녹음되면 색 · 라이엇 ID · 녹음 제외를 바꿀 수 있습니다.
+ )} + {r.user && ( + + 기록 보기 + + )} + {sup && role !== 'superadmin' && ( +
+
앱 사용 (게임 PC 앱 로그인)
+ {role ? ( + <> + + + + ) : ( + <> + + + + )} +
+ )} + {msg &&
{msg}
} +
+ )} +
+ ); +} + +function AddUser({ onRegs }: { onRegs: (u: AppUserRow[]) => void }) { + const [id, setId] = useState(''); + const [role, setRole] = useState<'user' | 'admin'>('user'); + const [busy, setBusy] = useState(false); + const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null); + const ok = /^\d{17,20}$/.test(id.trim()); + return ( +
{ + e.preventDefault(); + if (!ok) return; + setBusy(true); + setMsg(null); + api + .adminAddUser(id.trim(), role) + .then((r) => { + onRegs(r.users); + setMsg({ ok: true, text: '등록했습니다. 그 사람은 이제 겜녹이 앱에 로그인할 수 있습니다' }); + setId(''); + }) + .catch((e) => setMsg({ ok: false, text: errText(e) })) + .finally(() => setBusy(false)); + }} + > +
디스코드 아이디로 앱 유저 등록
+
+ setId(e.target.value)} aria-label="디스코드 아이디" /> + + +
+ {msg &&
{msg.text}
} +
+ ); +} diff --git a/site/web/src/store/app.tsx b/site/web/src/store/app.tsx index b99ca90..3d641af 100644 --- a/site/web/src/store/app.tsx +++ b/site/web/src/store/app.tsx @@ -6,7 +6,7 @@ import { makeUnknownUserCheck } from '../lib/unknown-users'; // ── 로그인 ─────────────────────────────────────────── type AuthState = { status: 'loading' } | { status: 'anon' } | { status: 'not_member' } | { status: 'ok'; me: Me }; -const AuthCtx = createContext<{ auth: AuthState; logout: () => void }>({ auth: { status: 'loading' }, logout: () => {} }); +const AuthCtx = createContext<{ auth: AuthState; logout: () => void; refreshMe: () => Promise }>({ auth: { status: 'loading' }, logout: () => {}, refreshMe: async () => {} }); export function AuthProvider({ children }: { children: ReactNode }) { const [auth, setAuth] = useState({ status: 'loading' }); @@ -28,7 +28,12 @@ export function AuthProvider({ children }: { children: ReactNode }) { const logout = useCallback(() => { void api.logout().finally(() => setAuth({ status: 'anon' })); }, []); - return {children}; + // 내 표시 이름을 바꾼 뒤 머리글 이름을 다시 받는다 + const refreshMe = useCallback(async () => { + const r = await api.me().catch(() => null); + if (r?.ok) setAuth({ status: 'ok', me: r.me }); + }, []); + return {children}; } export const useAuth = () => useContext(AuthCtx); @@ -123,8 +128,10 @@ interface DataValue { overview: Overview | null; users: User[]; userById: (id: string | undefined | null) => User | undefined; + /** 유저 목록 다시 받기 (유저 설정을 바꾼 뒤) */ + reloadUsers: () => void; } -const DataCtx = createContext({ overview: null, users: [], userById: () => undefined }); +const DataCtx = createContext({ overview: null, users: [], userById: () => undefined, reloadUsers: () => {} }); export function DataProvider({ children }: { children: ReactNode }) { const { epoch, locked } = useStatus(); @@ -163,6 +170,6 @@ export function DataProvider({ children }: { children: ReactNode }) { if (e.type === 'games.state') setOverview((o) => (o ? { ...o, live: e.data } : o)); }); const userById = useCallback((id: string | undefined | null) => (id ? map.get(id) : undefined), [map]); - return {children}; + return {children}; } export const useData = () => useContext(DataCtx); diff --git a/site/web/src/styles.css b/site/web/src/styles.css index f64618c..ec4d57d 100644 --- a/site/web/src/styles.css +++ b/site/web/src/styles.css @@ -4079,3 +4079,273 @@ button.match:hover { width: 90px; accent-color: var(--accent); } + +/* ── 내 정보 · 관리 페이지 (v1.6.0) ───────────────── */ +.me-btn { + padding: 4px 8px 4px 4px; + border-radius: 20px; + border: 1px solid transparent; + transition: border-color 0.15s, background 0.15s; +} +.me-btn:hover, +.me-btn[aria-expanded='true'] { + border-color: var(--line); + background: #15222f; +} +.me-caret { + font-size: 10px; + color: var(--dim); +} +.popover.profile-pop { + right: 0; + width: 360px; + max-height: calc(100vh - var(--header-h) - 24px); + overflow: auto; +} +.pp-head { + display: flex; + align-items: center; + gap: 10px; + padding-bottom: 10px; + border-bottom: 1px solid var(--line); + margin-bottom: 4px; +} +.pp-head b { + font-size: 15px; +} +.pp-links { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 14px; + padding-top: 10px; + border-top: 1px solid var(--line); +} +.ue-block { + display: flex; + flex-direction: column; + gap: 6px; +} +.ue-row { + display: flex; + gap: 6px; + align-items: center; +} +.ue-input { + flex: 1; + min-width: 0; + background: #0b141c; + border: 1px solid var(--line); + border-radius: 7px; + padding: 6px 9px; + font-size: 13px; + color: var(--ink); +} +.ue-input:focus { + outline: none; + border-color: #3a5670; +} +.ue-label { + font-size: 11.5px; + color: var(--muted); + margin-top: 6px; +} +.ue-hint { + font-size: 11.5px; + color: var(--dim); + line-height: 1.5; + display: block; +} +.ue-msg { + font-size: 12px; +} +.ue-msg.ok { + color: var(--good); +} +.ue-msg.bad { + color: #ff8a8a; +} +.ue-colors { + display: flex; + flex-wrap: wrap; + gap: 6px; +} +.ue-sw { + width: 22px; + height: 22px; + border-radius: 50%; + border: 2px solid transparent; + box-shadow: 0 0 0 1px #2c3f52; +} +.ue-sw.on { + border-color: #fff; +} +.ue-sw.custom { + background: var(--panel2); + color: var(--muted); + font-size: 13px; + line-height: 1; +} +.ue-hidden { + position: absolute; + width: 0; + height: 0; + opacity: 0; + pointer-events: none; +} +.ue-check { + display: flex; + gap: 8px; + align-items: flex-start; + font-size: 13px; + margin-top: 6px; + cursor: pointer; +} +.ue-check input { + margin-top: 3px; + accent-color: var(--accent); +} +.ue-check > span { + display: flex; + flex-direction: column; + gap: 2px; +} +.admin-page .panel { + margin-bottom: 16px; +} +.adm-dev { + display: flex; + flex-direction: column; + gap: 6px; + font-size: 13.5px; +} +.dot-st { + display: inline-block; + width: 8px; + height: 8px; + border-radius: 50%; + background: #4a5866; + vertical-align: middle; +} +.dot-st.on { + background: var(--good); +} +.adm-update { + margin-left: 10px; + color: var(--gold); + font-weight: 700; + font-size: 12.5px; +} +.adm-search { + max-width: 240px; +} +.adm-note { + margin-bottom: 10px; +} +.adm-list { + display: flex; + flex-direction: column; + gap: 4px; +} +.adm-row { + border: 1px solid var(--line); + border-radius: 10px; + background: #0f1923; +} +.adm-row.open { + border-color: #34506a; +} +.adm-sum { + width: 100%; + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + text-align: left; +} +.adm-nm { + flex: 1; + min-width: 0; + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} +.adm-role { + width: 96px; +} +.adm-seen { + width: 200px; + text-align: right; +} +.adm-caret { + color: var(--dim); + font-size: 11px; +} +.adm-body { + padding: 4px 14px 14px 52px; + display: flex; + flex-direction: column; + gap: 6px; + align-items: flex-start; +} +.adm-body > .ue-block { + width: min(520px, 100%); +} +.adm-acts { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: center; +} +.adm-acts .ue-label { + width: 100%; +} +.adm-add { + margin-top: 14px; + padding-top: 12px; + border-top: 1px solid var(--line); + max-width: 560px; +} +.adm-sel { + flex: none; + width: auto; +} +.b-name { + background: #13283a; + color: #8fc6ff; + border: 1px solid #23415c; +} +.b-role.superadmin { + background: #3a1820; + color: #ff8a95; +} +.b-role.admin { + background: #2b2412; + color: var(--gold); +} +.b-role.user { + background: #18303a; + color: var(--mint); +} +.btn.danger { + border-color: #5a2029; + color: #ff8a8a; +} +@media (max-width: 760px) { + .adm-seen, + .adm-role { + display: none; + } + .adm-body { + padding-left: 14px; + } + .popover.profile-pop { + position: fixed; + top: calc(var(--header-h) + 6px); + left: 8px; + right: 8px; + width: auto; + max-height: calc(100vh - var(--header-h) - 16px); + } +}