1단계 뼈대: joke-app에서 로그인(디스코드·게스트)·세션·권한·관리자·DB를 가져와 음악퀴즈용으로 정리, 새 디자인·아이콘, WS 연결·시계 맞추기, 테스트·e2e

- apps/server: Hono API(auth/me/config/admin), Bun WebSocket(welcome·ping/pong, 압축 끔), SQLite 마이그레이션
- 사이트 설정: 채팅 도배 방지 기본 꺼짐(관리자가 켬, 초당·순간 횟수)
- apps/web: 첫 화면·로그인·관리자(대시보드·사이트·사용자·관리자·기록), 라이트/다크, 휴대폰, noindex
- packages/shared: 닉네임 규칙, 프로토콜(zod), 시계 차이 계산
- 테스트 20개 + 브라우저 e2e 6단계 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 19:44:47 +09:00
parent 7ae34c49c1
commit 391bbe69e5
61 changed files with 3569 additions and 3 deletions

View File

@@ -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,
}));
}
}

View File

@@ -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<typeof SiteSettingsSchema>;
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;
}
}