diff --git a/.gitignore b/.gitignore index 2f641f6..1ae8f1a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,6 @@ -tools/report/report.html node_modules/ +tools/report/report.html +apps/web/dist/ +data/*.db* +test-results/ +deploy/.env diff --git a/README.md b/README.md index a64aa10..19ed9c4 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,16 @@ -# music_quiz +# music_quiz (음악퀴즈) +친구들끼리 방을 만들어 노래를 듣고 채팅으로 제목·가수를 맞히는 실시간 음악퀴즈. https://mquiz.tkrmagid.kr + +- 설계 문서: `docs/` (확정 사항은 `docs/12-decisions.md`, 작업 순서는 `docs/10-roadmap.md`) +- 구조: Bun workspaces — `apps/server`(Hono + WebSocket + SQLite), `apps/web`(React + Vite), `packages/shared` + +## 개발 +```sh +bun install +bun run dev # 서버 :3000 + 웹 :5173 +bun run typecheck +bun test # 단위·통합 테스트 +bun run e2e # 웹 빌드 후 브라우저 e2e (/usr/bin/google-chrome 필요) +``` +디스코드 로그인을 로컬에서 쓰려면 `DISCORD_CLIENT_ID`, `DISCORD_CLIENT_SECRET`, `SUPERADMIN_DISCORD_IDS`를 환경변수로 넣는다(리포에 커밋 금지). diff --git a/apps/server/package.json b/apps/server/package.json new file mode 100644 index 0000000..108f093 --- /dev/null +++ b/apps/server/package.json @@ -0,0 +1,16 @@ +{ + "name": "@mq/server", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "bun --watch src/index.ts", + "start": "bun src/index.ts" + }, + "dependencies": { + "@mq/shared": "workspace:*", + "hono": "4.13.12", + "ulid": "3.0.2", + "zod": "4.6.5" + } +} diff --git a/apps/server/src/admin.test.ts b/apps/server/src/admin.test.ts new file mode 100644 index 0000000..89344a2 --- /dev/null +++ b/apps/server/src/admin.test.ts @@ -0,0 +1,64 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { TEST_SUPERADMINS, api, boot, discordLogin, guest } from './test-utils'; + +const fakeDiscord = async (code: string) => ({ id: code, username: 'u', global_name: `관리${code.slice(-2)}`, avatar: null }); +const DISCORD = { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' }; + +let s: ReturnType; +afterEach(async () => s && (await s.stop())); + +describe('admin access', () => { + test('anonymous 401, plain user 403, both superadmins 200', async () => { + s = boot({ discordExchange: fakeDiscord }, DISCORD); + expect((await api(s.base, '/api/admin/me')).res.status).toBe(401); + const g = await guest(s.base, '손님'); + expect((await api(s.base, '/api/admin/me', { cookie: g.cookie })).res.status).toBe(403); + const plain = await discordLogin(s.base, '111111111111111111'); + expect((await api(s.base, '/api/admin/me', { cookie: plain.cookie })).res.status).toBe(403); + for (const id of TEST_SUPERADMINS) { + const sa = await discordLogin(s.base, id); + const r = await api(s.base, '/api/admin/me', { cookie: sa.cookie }); + expect(r.res.status).toBe(200); + expect(r.body.role).toBe('superadmin'); + } + }); + + test('superadmin adds an admin by Discord ID (before that person ever logs in); admin cannot manage admins', async () => { + s = boot({ discordExchange: fakeDiscord }, DISCORD); + const sa = await discordLogin(s.base, TEST_SUPERADMINS[0]); + const add = await api(s.base, '/api/admin/admins', { method: 'POST', cookie: sa.cookie, body: JSON.stringify({ discordId: '222222222222222222', note: '친구' }) }); + expect(add.res.status).toBe(200); + expect(add.body.admins.filter((a: any) => a.fixed).length).toBe(2); + const adm = await discordLogin(s.base, '222222222222222222'); + expect((await api(s.base, '/api/admin/me', { cookie: adm.cookie })).body.role).toBe('admin'); + expect((await api(s.base, '/api/admin/admins', { cookie: adm.cookie })).res.status).toBe(403); + expect((await api(s.base, '/api/admin/users', { cookie: adm.cookie })).res.status).toBe(403); + expect((await api(s.base, `/api/admin/admins/${TEST_SUPERADMINS[1]}`, { method: 'DELETE', cookie: sa.cookie })).res.status).toBe(400); + const audit = await api(s.base, '/api/admin/audit', { cookie: sa.cookie }); + expect(audit.body.entries[0]).toMatchObject({ action: 'admin.add', target: '222222222222222222' }); + }); + + test('site settings: chat flood guard is off by default and can be turned on', async () => { + s = boot({ discordExchange: fakeDiscord }, DISCORD); + const sa = await discordLogin(s.base, TEST_SUPERADMINS[0]); + const site = (await api(s.base, '/api/admin/site', { cookie: sa.cookie })).body.site; + expect(site).toMatchObject({ siteName: '음악퀴즈', chatFloodGuard: false, chatRatePerSec: 6, chatBurst: 12 }); + const put = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sa.cookie, body: JSON.stringify({ ...site, chatFloodGuard: true, announcement: '공지' }) }); + expect(put.res.status).toBe(200); + expect(s.settings.getSite().chatFloodGuard).toBe(true); + expect((await api(s.base, '/api/config')).body.announcement).toBe('공지'); + }); + + test('superadmin can ban a user (sessions revoked) but not another superadmin', async () => { + s = boot({ discordExchange: fakeDiscord }, DISCORD); + const sa = await discordLogin(s.base, TEST_SUPERADMINS[0]); + const g = await guest(s.base, '말썽쟁이'); + const ban = await api(s.base, `/api/admin/users/${g.id}`, { method: 'PATCH', cookie: sa.cookie, body: JSON.stringify({ ban: { reason: '도배' } }) }); + expect(ban.res.status).toBe(200); + expect((await api(s.base, '/api/me', { cookie: g.cookie })).body.me).toBeNull(); + const sa2 = await discordLogin(s.base, TEST_SUPERADMINS[1]); + const sa2Id = (await api(s.base, '/api/me', { cookie: sa2.cookie })).body.me.id; + const r = await api(s.base, `/api/admin/users/${sa2Id}`, { method: 'PATCH', cookie: sa.cookie, body: JSON.stringify({ ban: { reason: 'x' } }) }); + expect(r.res.status).toBe(400); + }); +}); diff --git a/apps/server/src/admin/roles.ts b/apps/server/src/admin/roles.ts new file mode 100644 index 0000000..2755bde --- /dev/null +++ b/apps/server/src/admin/roles.ts @@ -0,0 +1,90 @@ +/** Role resolution by linked Discord ID (docs/02, ported from joke-app). Computed per request. */ +import type { Database } from 'bun:sqlite'; + +export type Role = 'user' | 'admin' | 'superadmin'; + +export class Roles { + constructor( + private db: Database, + private superadminDiscordIds: string[], + ) {} + + discordIdOf(userId: string): string | null { + return ( + this.db + .query<{ provider_user_id: string }, [string]>("SELECT provider_user_id FROM oauth_accounts WHERE user_id = ? AND provider = 'discord'") + .get(userId)?.provider_user_id ?? null + ); + } + + roleOfDiscord(discordId: string | null): Role { + if (!discordId) return 'user'; + if (this.superadminDiscordIds.includes(discordId)) return 'superadmin'; + const row = this.db.query<{ n: number }, [string]>('SELECT COUNT(*) AS n FROM admins WHERE discord_id = ?').get(discordId); + return (row?.n ?? 0) > 0 ? 'admin' : 'user'; + } + + roleOf(userId: string | null): Role { + return userId ? this.roleOfDiscord(this.discordIdOf(userId)) : 'user'; + } + + isSuperadminDiscord(discordId: string): boolean { + return this.superadminDiscordIds.includes(discordId); + } + + listAdmins(): { discordId: string; note: string | null; addedBy: string | null; addedAt: number; userId: string | null; nickname: string | null; fixed: boolean }[] { + const rows = this.db + .query<{ discord_id: string; note: string | null; added_by: string | null; added_at: number; user_id: string | null; nickname: string | null }, []>( + `SELECT a.discord_id, a.note, a.added_by, a.added_at, o.user_id, u.nickname FROM admins a + LEFT JOIN oauth_accounts o ON o.provider = 'discord' AND o.provider_user_id = a.discord_id + LEFT JOIN users u ON u.id = o.user_id ORDER BY a.added_at`, + ) + .all() + .map((r) => ({ discordId: r.discord_id, note: r.note, addedBy: r.added_by, addedAt: r.added_at, userId: r.user_id, nickname: r.nickname, fixed: false })); + const fixed = this.superadminDiscordIds.map((d) => { + const u = this.db + .query<{ user_id: string; nickname: string }, [string]>( + "SELECT o.user_id, u.nickname FROM oauth_accounts o JOIN users u ON u.id = o.user_id WHERE o.provider = 'discord' AND o.provider_user_id = ?", + ) + .get(d); + return { discordId: d, note: '슈퍼어드민(설정 고정)', addedBy: null, addedAt: 0, userId: u?.user_id ?? null, nickname: u?.nickname ?? null, fixed: true }; + }); + return [...fixed, ...rows]; + } + + addAdmin(discordId: string, note: string | null, by: string, now = Date.now()): boolean { + return this.db.query('INSERT OR IGNORE INTO admins (discord_id, note, added_by, added_at) VALUES (?, ?, ?, ?)').run(discordId, note, by, now).changes > 0; + } + + removeAdmin(discordId: string): boolean { + return this.db.query('DELETE FROM admins WHERE discord_id = ?').run(discordId).changes > 0; + } +} + +export class Audit { + constructor(private db: Database) {} + + log(actorId: string, action: string, target: string | null, before: unknown, after: unknown, now = Date.now()): void { + this.db + .query('INSERT INTO admin_audit (actor_id, action, target, before_json, after_json, at) VALUES (?, ?, ?, ?, ?, ?)') + .run(actorId, action, target, before === undefined ? null : JSON.stringify(before), after === undefined ? null : JSON.stringify(after), now); + } + + list(limit: number, offset: number) { + return this.db + .query<{ id: number; actor_id: string; nickname: string | null; action: string; target: string | null; before_json: string | null; after_json: string | null; at: number }, [number, number]>( + 'SELECT a.*, u.nickname FROM admin_audit a LEFT JOIN users u ON u.id = a.actor_id ORDER BY a.id DESC LIMIT ? OFFSET ?', + ) + .all(limit, offset) + .map((r) => ({ + id: r.id, + actorId: r.actor_id, + actor: r.nickname, + action: r.action, + target: r.target, + before: r.before_json ? JSON.parse(r.before_json) : null, + after: r.after_json ? JSON.parse(r.after_json) : null, + at: r.at, + })); + } +} diff --git a/apps/server/src/admin/settings.ts b/apps/server/src/admin/settings.ts new file mode 100644 index 0000000..7c7179e --- /dev/null +++ b/apps/server/src/admin/settings.ts @@ -0,0 +1,41 @@ +/** + * Admin-editable site settings with an in-memory cache (docs/02 관리자 → 사이트, docs/12 채팅). + * Room defaults (모드·장르·정답인식 …) join here in stage 4. + */ +import type { Database } from 'bun:sqlite'; +import { z } from 'zod'; + +export const SiteSettingsSchema = z.object({ + siteName: z.string().trim().min(1).max(40).default('음악퀴즈'), + announcement: z.string().trim().max(300).default(''), + maintenance: z.boolean().default(false), + bannedWords: z.array(z.string().trim().min(1).max(30)).max(500).default([]), + /** Chat flood guard (docs/12 채팅): off by default; when on, a token bucket per connection. */ + chatFloodGuard: z.boolean().default(false), + chatRatePerSec: z.number().int().min(1).max(50).default(6), + chatBurst: z.number().int().min(1).max(100).default(12), +}); +export type SiteSettings = z.infer; + +export class SettingsStore { + private site: SiteSettings; + + constructor(private db: Database) { + const row = db.query<{ json: string }, [string]>('SELECT json FROM site_settings WHERE key = ?').get('site'); + const parsed = SiteSettingsSchema.safeParse(row ? JSON.parse(row.json) : {}); + this.site = parsed.success ? parsed.data : SiteSettingsSchema.parse({}); + } + + getSite(): SiteSettings { + return this.site; + } + + setSite(next: SiteSettings, by: string, now = Date.now()): void { + this.db + .query( + 'INSERT INTO site_settings (key, json, updated_by, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET json = excluded.json, updated_by = excluded.updated_by, updated_at = excluded.updated_at', + ) + .run('site', JSON.stringify(next), by, now); + this.site = next; + } +} diff --git a/apps/server/src/auth.test.ts b/apps/server/src/auth.test.ts new file mode 100644 index 0000000..0963f8c --- /dev/null +++ b/apps/server/src/auth.test.ts @@ -0,0 +1,108 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { TEST_SUPERADMINS, api, boot, cookieOf, discordLogin, guest } from './test-utils'; + +const fakeDiscord = async (code: string) => ({ id: code, username: `user${code.slice(-3)}`, global_name: '사금향', avatar: code.endsWith('9') ? 'abc' : null }); + +let s: ReturnType; +afterEach(async () => s && (await s.stop())); + +describe('guest login', () => { + test('creates a guest with a valid nickname and returns it from /api/me', async () => { + s = boot(); + const g = await guest(s.base, '신나는 레코드'); + const me = await api(s.base, '/api/me', { cookie: g.cookie }); + expect(me.body.me).toMatchObject({ id: g.id, nickname: '신나는 레코드', kind: 'guest' }); + expect(me.body.role).toBe('user'); + }); + + test('rejects bad nicknames and admin banned words', async () => { + s = boot(); + expect((await api(s.base, '/api/auth/guest', { method: 'POST', body: JSON.stringify({ nickname: 'a' }) })).res.status).toBe(400); + expect((await api(s.base, '/api/auth/guest', { method: 'POST', body: JSON.stringify({ nickname: ' + + diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..6251bd1 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,25 @@ +{ + "name": "@mq/web", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "@mq/shared": "workspace:*", + "pretendard": "1.3.9", + "react": "19.3.0", + "react-dom": "19.3.0", + "react-router": "8.4.0", + "zustand": "5.0.15" + }, + "devDependencies": { + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "@vitejs/plugin-react": "6.1.1", + "vite": "8.3.2" + } +} diff --git a/apps/web/public/favicon.ico b/apps/web/public/favicon.ico new file mode 100644 index 0000000..c66be48 Binary files /dev/null and b/apps/web/public/favicon.ico differ diff --git a/apps/web/public/favicon.svg b/apps/web/public/favicon.svg new file mode 100644 index 0000000..bf58c5a --- /dev/null +++ b/apps/web/public/favicon.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/apps/web/public/icons/apple-touch-icon.png b/apps/web/public/icons/apple-touch-icon.png new file mode 100644 index 0000000..d993c2c Binary files /dev/null and b/apps/web/public/icons/apple-touch-icon.png differ diff --git a/apps/web/public/icons/icon-192.png b/apps/web/public/icons/icon-192.png new file mode 100644 index 0000000..7709534 Binary files /dev/null and b/apps/web/public/icons/icon-192.png differ diff --git a/apps/web/public/icons/icon-512.png b/apps/web/public/icons/icon-512.png new file mode 100644 index 0000000..1587f41 Binary files /dev/null and b/apps/web/public/icons/icon-512.png differ diff --git a/apps/web/public/logo.svg b/apps/web/public/logo.svg new file mode 100644 index 0000000..bb7deec --- /dev/null +++ b/apps/web/public/logo.svg @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/public/manifest.webmanifest b/apps/web/public/manifest.webmanifest new file mode 100644 index 0000000..c14e3ce --- /dev/null +++ b/apps/web/public/manifest.webmanifest @@ -0,0 +1,13 @@ +{ + "name": "음악퀴즈", + "short_name": "음악퀴즈", + "start_url": "/", + "display": "standalone", + "background_color": "#F5EFE3", + "theme_color": "#F5EFE3", + "lang": "ko", + "icons": [ + { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" } + ] +} diff --git a/apps/web/public/robots.txt b/apps/web/public/robots.txt new file mode 100644 index 0000000..1f53798 --- /dev/null +++ b/apps/web/public/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Disallow: / diff --git a/apps/web/src/components/LoginBox.tsx b/apps/web/src/components/LoginBox.tsx new file mode 100644 index 0000000..d08d84b --- /dev/null +++ b/apps/web/src/components/LoginBox.tsx @@ -0,0 +1,26 @@ +/** 시작하기: Discord login (big) + guest nickname (docs/03 첫 화면 오른쪽). */ +import { DiscordMark } from './ui'; +import { GuestWarning, NicknameForm } from './NicknameForm'; +import { discordLoginUrl } from '../net/api'; +import { useSession } from '../store/session'; + +export function LoginBox({ next, onDone }: { next: string; onDone?: () => void }) { + const discord = useSession((s) => s.discordEnabled); + return ( +
+

시작하기

+

디스코드로 로그인하면 기록이 남고, 게스트도 바로 놀 수 있어요.

+ {discord && ( + <> + + + 디스코드로 로그인 + +
또는
+ + )} + + +
+ ); +} diff --git a/apps/web/src/components/NicknameForm.tsx b/apps/web/src/components/NicknameForm.tsx new file mode 100644 index 0000000..aef6b2c --- /dev/null +++ b/apps/web/src/components/NicknameForm.tsx @@ -0,0 +1,65 @@ +/** Guest start: nickname (pre-filled suggestion) + start button (joke-app NicknameForm). */ +import { useState } from 'react'; +import { nicknameError, normalizeNickname, suggestNickname } from '@mq/shared/lite'; +import { api } from '../net/api'; +import { useSession } from '../store/session'; + +export function NicknameForm({ onDone }: { onDone?: () => void }) { + const [nick, setNick] = useState(() => suggestNickname()); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (e: React.FormEvent) => { + e.preventDefault(); + const n = normalizeNickname(nick); + const err = nicknameError(n); + if (err) return setError(err); + setBusy(true); + try { + await api.guest(n); + await useSession.getState().refresh(); + onDone?.(); + } catch (ex) { + setError((ex as Error).message); + } finally { + setBusy(false); + } + }; + + return ( +
+ + {error && ( +

+ {error} +

+ )} + +
+ ); +} + +/** Guests are deleted a day after they leave the site (docs/02). */ +export function GuestWarning() { + return ( +

+ 게스트는 사이트에 들어오지 않은 채 하루가 지나면 계정이 지워져요. 퀴즈 저장은 디스코드 로그인 계정만 할 수 있어요. +

+ ); +} diff --git a/apps/web/src/components/SiteHeader.tsx b/apps/web/src/components/SiteHeader.tsx new file mode 100644 index 0000000..a0ce1d1 --- /dev/null +++ b/apps/web/src/components/SiteHeader.tsx @@ -0,0 +1,114 @@ +/** Top bar: logo, menu, theme toggle, login / account menu (joke-app SiteHeader, music-quiz menu). */ +import { useEffect, useRef, useState } from 'react'; +import { Link, NavLink, useNavigate } from 'react-router'; +import { api } from '../net/api'; +import { useSession } from '../store/session'; +import { Avatar, ConfirmSheet } from './ui'; + +export function SiteHeader() { + const { me, siteName, role } = useSession(); + return ( +
+
+ + + {siteName} + + +
+ + {me ? ( + + ) : ( + + 로그인 + + )} +
+
+ ); +} + +function ThemeToggle() { + const theme = useSession((s) => s.settings.theme); + const updateSettings = useSession((s) => s.updateSettings); + const [systemDark, setSystemDark] = useState(() => matchMedia('(prefers-color-scheme: dark)').matches); + useEffect(() => { + const q = matchMedia('(prefers-color-scheme: dark)'); + const on = () => setSystemDark(q.matches); + q.addEventListener('change', on); + return () => q.removeEventListener('change', on); + }, []); + const dark = theme === 'dark' || (theme === 'auto' && systemDark); + const label = dark ? '밝은 화면으로 바꾸기' : '어두운 화면으로 바꾸기'; + return ( + + ); +} + +function AccountMenu() { + const me = useSession((s) => s.me)!; + const role = useSession((s) => s.role); + const nav = useNavigate(); + const [open, setOpen] = useState(false); + const [confirm, setConfirm] = useState(false); + const ref = useRef(null); + + useEffect(() => { + if (!open) return; + const onDown = (e: PointerEvent) => !ref.current?.contains(e.target as Node) && setOpen(false); + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false); + document.addEventListener('pointerdown', onDown); + document.addEventListener('keydown', onKey); + return () => { + document.removeEventListener('pointerdown', onDown); + document.removeEventListener('keydown', onKey); + }; + }, [open]); + + return ( +
+ + {open && ( +
+ {role !== 'user' && ( + + )} + +
+ )} + {confirm && ( + { + await api.logout(); + nav('/'); + await useSession.getState().refresh(); + }} + onClose={() => setConfirm(false)} + /> + )} +
+ ); +} diff --git a/apps/web/src/components/ui.tsx b/apps/web/src/components/ui.tsx new file mode 100644 index 0000000..c48b97a --- /dev/null +++ b/apps/web/src/components/ui.tsx @@ -0,0 +1,101 @@ +/** Shared UI primitives (joke-app pattern, new look). */ +import { useEffect, useRef, type ReactNode } from 'react'; +import type { PublicUser } from '@mq/shared/lite'; +import { useToasts } from '../store/toast'; + +/** Per-user fixed colour; skips the 60°~160° green band so names never look like the 정답 green (docs/03). */ +export function userHue(id: string): number { + let h = 0; + for (const ch of id) h = (h * 31 + ch.charCodeAt(0)) >>> 0; + const hue = h % 260; + return hue < 60 ? hue : hue + 100; +} + +export function Avatar({ user, size = 36 }: { user: Pick; size?: number }) { + return ( + + {user.avatar ? : [...user.nickname][0]} + + ); +} + +export function Sheet({ onClose, children, label }: { onClose: () => void; children: ReactNode; label: string }) { + const ref = useRef(null); + const close = useRef(onClose); + close.current = onClose; + useEffect(() => { + const prev = document.activeElement as HTMLElement | null; + ref.current?.focus(); + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && close.current(); + window.addEventListener('keydown', onKey); + return () => { + window.removeEventListener('keydown', onKey); + prev?.focus?.(); + }; + }, []); + return ( +
e.target === e.currentTarget && onClose()}> +
+ {children} +
+
+ ); +} + +export function ConfirmSheet({ + title, + body, + confirm, + danger, + onConfirm, + onClose, +}: { + title: string; + body?: ReactNode; + confirm: string; + danger?: boolean; + onConfirm: () => void; + onClose: () => void; +}) { + return ( + +

{title}

+ {body &&
{body}
} +
+ + +
+
+ ); +} + +export function Toasts() { + const toasts = useToasts((s) => s.toasts); + return ( +
+ {toasts.map((t) => ( +
+ {t.text} +
+ ))} +
+ ); +} + +export function DiscordMark() { + return ( + + + + ); +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx new file mode 100644 index 0000000..b2919b5 --- /dev/null +++ b/apps/web/src/main.tsx @@ -0,0 +1,70 @@ +import { StrictMode, Suspense, lazy, useEffect } from 'react'; +import { createRoot } from 'react-dom/client'; +import { BrowserRouter, Route, Routes, useLocation, useNavigate } from 'react-router'; +import 'pretendard/dist/web/variable/pretendardvariable-dynamic-subset.css'; +import './styles/global.css'; +import { Toasts } from './components/ui'; +import { SiteHeader } from './components/SiteHeader'; +import { useSession } from './store/session'; +import { toast } from './store/toast'; +import { Home } from './pages/Home'; + +const LoginPage = lazy(() => import('./pages/LoginPage')); +const NotFound = lazy(() => import('./pages/NotFound')); +const AdminApp = lazy(() => import('./pages/admin/AdminApp')); + +function Announcement() { + const text = useSession((s) => s.announcement); + const maintenance = useSession((s) => s.maintenance); + if (!text && !maintenance) return null; + return ( +
+ {maintenance && '🛠 점검 중 · '} + {text || '새 방을 잠시 만들 수 없어요.'} +
+ ); +} + +function Shell() { + const loaded = useSession((s) => s.loaded); + const nav = useNavigate(); + const loc = useLocation(); + useEffect(() => { + void useSession.getState().refresh(); + }, []); + useEffect(() => { + const q = new URLSearchParams(loc.search); + if (q.get('linked') === '1') toast('디스코드 계정과 연결했어요.'); + if (q.get('login') === 'failed') toast('디스코드 로그인에 실패했어요. 다시 시도해 주세요.', 'error'); + if (q.get('login') === 'banned') toast('이용이 제한된 계정이에요.', 'error', 6000); + if (q.has('linked') || q.has('login')) { + q.delete('linked'); + q.delete('login'); + nav({ pathname: loc.pathname, search: q.toString() }, { replace: true }); + } + }, [loc.search]); // eslint-disable-line react-hooks/exhaustive-deps + if (!loaded) return
불러오는 중…
; + return ( + <> + + + + 불러오는 중…}> + + } /> + } /> + } /> + } /> + + + + ); +} + +createRoot(document.getElementById('root')!).render( + + + + + , +); diff --git a/apps/web/src/net/api.ts b/apps/web/src/net/api.ts new file mode 100644 index 0000000..24567fd --- /dev/null +++ b/apps/web/src/net/api.ts @@ -0,0 +1,48 @@ +import type { PublicUser, Role } from '@mq/shared/lite'; + +export class ApiError extends Error { + constructor( + message: string, + readonly status: number, + ) { + super(message); + } +} + +export async function apiCall(method: string, path: string, body?: unknown): Promise { + let res: Response; + try { + res = await fetch(path, { + method, + credentials: 'same-origin', + headers: body !== undefined ? { 'Content-Type': 'application/json' } : undefined, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + } catch { + throw new ApiError('인터넷 연결을 확인해 주세요.', 0); + } + const data = (await res.json().catch(() => ({}))) as { error?: string } & T; + if (!res.ok) throw new ApiError(data.error ?? '잠시 후 다시 시도해 주세요.', res.status); + return data; +} + +export interface Settings { + fontScale?: 'normal' | 'large' | 'xlarge'; + theme?: 'auto' | 'light' | 'dark'; +} + +export interface MeResponse { + me: PublicUser | null; + role?: Role; + settings?: Settings; +} + +export const api = { + config: () => apiCall<{ discord: boolean; siteName: string; announcement: string; maintenance: boolean }>('GET', '/api/config'), + me: () => apiCall('GET', '/api/me'), + guest: (nickname: string) => apiCall<{ me: PublicUser }>('POST', '/api/auth/guest', { nickname }), + updateMe: (patch: { nickname?: string; settings?: Settings }) => apiCall<{ me: PublicUser }>('PATCH', '/api/me', patch), + logout: () => apiCall<{ ok: true }>('POST', '/api/auth/logout', {}), +}; + +export const discordLoginUrl = (next: string) => `/api/auth/discord/start?next=${encodeURIComponent(next)}`; diff --git a/apps/web/src/pages/Home.tsx b/apps/web/src/pages/Home.tsx new file mode 100644 index 0000000..7e8cd99 --- /dev/null +++ b/apps/web/src/pages/Home.tsx @@ -0,0 +1,50 @@ +/** 첫 화면 (docs/03): 소개 + 방 만들기/코드로 참여, 시작하기, 열린 방 목록. Rooms arrive in stage 4. */ +import { useSession } from '../store/session'; +import { LoginBox } from '../components/LoginBox'; +import { Avatar } from '../components/ui'; + +export function Home() { + const me = useSession((s) => s.me); + return ( +
+
+
+
+

+ 전주 1초, 채팅 한 줄. +
+ 누가 먼저 맞히나. +

+

방 만들고 링크 하나 보내면 끝. 인원 제한 없이 같이 듣고, 채팅으로 제목을 먼저 치는 사람이 점수를 가져가요.

+
+ + +
+

방 만들기는 곧 열려요. 지금은 로그인만 먼저 해 볼 수 있어요.

+
+ {me ? ( +
+

반가워요!

+
+ +
+
{me.nickname}
+
{me.kind === 'member' ? '디스코드 계정으로 로그인했어요' : '게스트로 참여 중이에요'}
+
+
+
+ ) : ( + + )} +
+
+

열린 방 0

+
+
아직 열린 방이 없어요.
+
+ ); +} diff --git a/apps/web/src/pages/LoginPage.tsx b/apps/web/src/pages/LoginPage.tsx new file mode 100644 index 0000000..41b1100 --- /dev/null +++ b/apps/web/src/pages/LoginPage.tsx @@ -0,0 +1,19 @@ +import { Navigate, useNavigate, useSearchParams } from 'react-router'; +import { LoginBox } from '../components/LoginBox'; +import { useSession } from '../store/session'; + +/** Only same-site paths, so ?next= can't send people to another site. */ +const safeNext = (v: string | null) => (v && v.startsWith('/') && !v.startsWith('//') ? v : '/'); + +export default function LoginPage() { + const nav = useNavigate(); + const me = useSession((s) => s.me); + const [params] = useSearchParams(); + const next = safeNext(params.get('next')); + if (me) return ; + return ( +
+ nav(next, { replace: true })} /> +
+ ); +} diff --git a/apps/web/src/pages/NotFound.tsx b/apps/web/src/pages/NotFound.tsx new file mode 100644 index 0000000..2338054 --- /dev/null +++ b/apps/web/src/pages/NotFound.tsx @@ -0,0 +1,12 @@ +import { Link } from 'react-router'; + +export default function NotFound() { + return ( +
+

페이지를 찾을 수 없어요

+ + 홈으로 + +
+ ); +} diff --git a/apps/web/src/pages/admin/AdminApp.tsx b/apps/web/src/pages/admin/AdminApp.tsx new file mode 100644 index 0000000..fff9fb4 --- /dev/null +++ b/apps/web/src/pages/admin/AdminApp.tsx @@ -0,0 +1,434 @@ +/** + * 관리자 페이지 (docs/02): side menu + content. Stage 1 has 대시보드 · 사이트 · 사용자 · 관리자 · 기록; + * 노래 · 가수 · 장르 · 수집 · 통계 · 방 are listed and open in later stages. + */ +import { useCallback, useEffect, useState, type FormEvent } from 'react'; +import { Link, NavLink, Navigate, Route, Routes } from 'react-router'; +import type { Role } from '@mq/shared/lite'; +import { ApiError, apiCall, discordLoginUrl } from '../../net/api'; +import { useSession } from '../../store/session'; +import { toast } from '../../store/toast'; +import { ConfirmSheet } from '../../components/ui'; + +const fmt = (ms: number | null | undefined) => (ms ? new Date(ms).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' }) : '-'); + +function useLoad(path: string | null) { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const reload = useCallback(() => { + if (!path) return; + apiCall('GET', path) + .then((d) => (setData(d), setError(null))) + .catch((e: Error) => setError(e.message)); + }, [path]); + useEffect(reload, [reload]); + return { data, error, reload, setData }; +} + +const SOON = ['노래', '가수', '장르', '수집', '통계', '방']; + +export default function AdminApp() { + const me = useSession((s) => s.me); + const role = useSession((s) => s.role); + if (!me || me.kind === 'guest') { + return ( +
+

관리자 페이지

+

관리자는 디스코드로 로그인해야 들어올 수 있어요.

+ + 디스코드로 로그인 + +
+ ); + } + if (role === 'user') { + return ( +
+

권한이 없어요

+

관리자로 등록된 디스코드 계정만 들어올 수 있어요.

+ + 홈으로 + +
+ ); + } + const isSuper = role === 'superadmin'; + return ( +
+ +
+ + } /> + } /> + {isSuper && } />} + {isSuper && } />} + } /> + } /> + +
+
+ ); +} + +function Dashboard({ role }: { role: Role }) { + const { data, error } = useLoad<{ users: { total: number; guests: number; members: number; banned: number }; connections: number; uptimeSec: number; memoryMb: number }>( + '/api/admin/overview', + ); + return ( + <> +

대시보드

+

+ 내 권한: {role === 'superadmin' ? '슈퍼어드민' : '관리자'} +

+ {error &&

{error}

} + {data && ( +
+
+ {data.connections} + 지금 접속 +
+
+ {data.users.members} + 디스코드 회원 +
+
+ {data.users.guests} + 게스트 +
+
+ {data.users.banned} + 이용 제한 +
+
+ {Math.floor(data.uptimeSec / 3600)}시간 + 서버 켜진 시간 +
+
+ {data.memoryMb}MB + 서버 메모리 +
+
+ )} +
+

다음에 생기는 것

+

노래 수, 유튜브 매칭률, 가사 보유율, 진행 중인 방, 오늘 플레이 수는 노래 DB와 방 기능이 들어오면 여기에 보여요.

+
+ + ); +} + +interface Site { + siteName: string; + announcement: string; + maintenance: boolean; + bannedWords: string[]; + chatFloodGuard: boolean; + chatRatePerSec: number; + chatBurst: number; +} + +function SiteSettings() { + const { data, error } = useLoad<{ site: Site }>('/api/admin/site'); + const [s, setS] = useState(null); + const [words, setWords] = useState(''); + useEffect(() => { + if (data) { + setS(data.site); + setWords(data.site.bannedWords.join(', ')); + } + }, [data]); + if (error) return

{error}

; + if (!s) return

불러오는 중…

; + const save = async (e: FormEvent) => { + e.preventDefault(); + const next = { ...s, bannedWords: words.split(',').map((w) => w.trim()).filter(Boolean) }; + try { + const r = await apiCall<{ site: Site }>('PUT', '/api/admin/site', next); + setS(r.site); + toast('저장했어요.'); + void useSession.getState().refresh(); + } catch (ex) { + toast((ex as ApiError).message, 'error'); + } + }; + return ( +
+

사이트 설정

+
+ + +
+ +