256 lines
12 KiB
TypeScript
256 lines
12 KiB
TypeScript
/** Admin API (docs/02 관리자 페이지). Mounted under /api/admin. Ported from joke-app (rooms/games parts come later). */
|
|
import { Hono, type Context } from 'hono';
|
|
import { z } from 'zod';
|
|
import { nicknameError, normalizeNickname, type Role } from '@mq/shared';
|
|
import type { Audit, Roles } from '../admin/roles';
|
|
import { SiteSettingsSchema, type SettingsStore } from '../admin/settings';
|
|
import type { Sessions } from '../auth/sessions';
|
|
import { toPublicUser, type Users } from '../auth/users';
|
|
import type { Database } from 'bun:sqlite';
|
|
import { catalogStats, genreList, getSong, listSongs, updateSong } from '../songs/store';
|
|
import { checkEmbed, type EmbedState } from '../collector/oembed';
|
|
import { mountCatalogAdmin, songFilterFrom, type CollectControl } from './admin-catalog';
|
|
|
|
export interface AdminDeps {
|
|
users: Users;
|
|
sessions: Sessions;
|
|
roles: Roles;
|
|
audit: Audit;
|
|
settings: SettingsStore;
|
|
disconnectUser: (userId: string) => void;
|
|
stats: () => Record<string, unknown>;
|
|
db: Database;
|
|
/** Injected for tests. */
|
|
checkEmbed?: (videoId: string) => Promise<EmbedState>;
|
|
/** Lobby song counts depend on the catalog. */
|
|
onCatalogChange?: () => void;
|
|
/** Genre names shown on room cards. */
|
|
onGenresChange?: () => void;
|
|
rooms?: {
|
|
adminList(): unknown[];
|
|
adminClose(code: string): boolean;
|
|
};
|
|
collect?: CollectControl;
|
|
}
|
|
|
|
type Env = { Variables: { userId: string | null; role: Role } };
|
|
|
|
const DISCORD_ID = /^\d{17,20}$/;
|
|
const VIDEO_ID = /^[\w-]{11}$/;
|
|
|
|
/** Accepts https://youtu.be/ID, youtube.com/watch?v=ID, music.youtube.com/watch?v=ID or the bare ID. */
|
|
export function parseVideoId(s: string): string | null {
|
|
const t = s.trim();
|
|
if (VIDEO_ID.test(t)) return t;
|
|
try {
|
|
const u = new URL(t);
|
|
const id = u.hostname === 'youtu.be' ? u.pathname.slice(1) : u.searchParams.get('v');
|
|
return id && VIDEO_ID.test(id) ? id : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
const SongPatchSchema = z.object({
|
|
title: z.string().trim().min(1).max(200).optional(),
|
|
artist: z.string().trim().min(1).max(200).optional(),
|
|
year: z.number().int().min(1900).max(2100).nullable().optional(),
|
|
genres: z.array(z.string().max(30)).max(20).optional(),
|
|
level: z.number().int().min(1).max(10).nullable().optional(),
|
|
youtube: z.string().max(200).nullable().optional(),
|
|
highlightSec: z.number().min(0).max(3600).nullable().optional(),
|
|
hidden: z.boolean().optional(),
|
|
note: z.string().max(1000).nullable().optional(),
|
|
titleAliases: z.array(z.string().max(200)).max(30).optional(),
|
|
artistAliases: z.array(z.string().max(200)).max(30).optional(),
|
|
lyrics: z.string().max(20000).nullable().optional(),
|
|
});
|
|
|
|
export function createAdminApp(d: AdminDeps) {
|
|
const app = new Hono<Env>();
|
|
|
|
app.use('*', async (c, next) => {
|
|
const role = d.roles.roleOf(c.get('userId'));
|
|
if (role === 'user') return c.json({ error: '권한이 없어요.' }, c.get('userId') ? 403 : 401);
|
|
c.set('role', role);
|
|
await next();
|
|
});
|
|
|
|
const superOnly = async (c: Context<Env>, next: () => Promise<void>) => {
|
|
if (c.get('role') !== 'superadmin') return c.json({ error: '슈퍼어드민만 할 수 있어요.' }, 403);
|
|
await next();
|
|
};
|
|
const actor = (c: Context<Env>) => c.get('userId')!;
|
|
const body = async (c: Context<Env>) => c.req.json().catch(() => null);
|
|
|
|
app.get('/me', (c) => c.json({ role: c.get('role'), me: toPublicUser(d.users.get(actor(c))!) }));
|
|
|
|
app.get('/overview', (c) => c.json({ users: d.users.counts(), ...d.stats() }));
|
|
|
|
// ------------------------------------------------------------ site
|
|
app.get('/site', (c) => c.json({ site: d.settings.getSite() }));
|
|
app.put('/site', async (c) => {
|
|
const parsed = SiteSettingsSchema.safeParse(await body(c));
|
|
if (!parsed.success) return c.json({ error: `입력 값이 올바르지 않아요: ${parsed.error.issues.map((i) => i.path.join('.')).join(', ')}` }, 400);
|
|
const before = d.settings.getSite();
|
|
d.settings.setSite(parsed.data, actor(c));
|
|
d.audit.log(actor(c), 'site.update', null, before, parsed.data);
|
|
return c.json({ site: parsed.data });
|
|
});
|
|
|
|
// ------------------------------------------------------------ songs (docs/02 노래 관리)
|
|
app.get('/catalog', (c) => c.json(catalogStats(d.db)));
|
|
app.get('/genres', (c) => c.json({ genres: genreList(d.db) }));
|
|
// Static paths (/songs/export, /songs/bulk …) before /songs/:id.
|
|
mountCatalogAdmin(app, d, {
|
|
actor,
|
|
body,
|
|
videoOf: async (url) => {
|
|
const id = parseVideoId(url);
|
|
if (!id) return '유튜브 주소를 알아볼 수 없어요. https://youtu.be/… 형식으로 넣어 주세요.';
|
|
const e = await (d.checkEmbed ?? checkEmbed)(id);
|
|
if (e.state === 'noembed') return '이 영상은 다른 사이트에서 재생할 수 없게 막혀 있어요(퍼가기 금지). 다른 영상을 골라 주세요.';
|
|
if (e.state === 'dead') return '없는 영상이에요.';
|
|
if (e.state === 'error') return '유튜브 확인에 실패했어요. 잠시 후 다시 시도해 주세요.';
|
|
return { id, author: e.author, title: e.title };
|
|
},
|
|
});
|
|
app.get('/songs', (c) => c.json(listSongs(d.db, songFilterFrom(c))));
|
|
app.get('/songs/:id', (c) => {
|
|
const r = getSong(d.db, Number(c.req.param('id')));
|
|
return r ? c.json(r) : c.json({ error: '노래를 찾을 수 없어요.' }, 404);
|
|
});
|
|
app.patch('/songs/:id', async (c) => {
|
|
const id = Number(c.req.param('id'));
|
|
const before = getSong(d.db, id);
|
|
if (!before) return c.json({ error: '노래를 찾을 수 없어요.' }, 404);
|
|
const parsed = SongPatchSchema.safeParse(await body(c));
|
|
if (!parsed.success) return c.json({ error: `입력 값이 올바르지 않아요: ${parsed.error.issues.map((i) => i.path.join('.')).join(', ')}` }, 400);
|
|
const { youtube, ...rest } = parsed.data;
|
|
let youtubeId: string | null | undefined;
|
|
let embed: { author: string; title: string } | undefined;
|
|
if (youtube !== undefined) {
|
|
if (youtube === null || youtube.trim() === '') youtubeId = null;
|
|
else {
|
|
youtubeId = parseVideoId(youtube);
|
|
if (!youtubeId) return c.json({ error: '유튜브 주소를 알아볼 수 없어요. https://youtu.be/… 형식으로 넣어 주세요.' }, 400);
|
|
const e = await (d.checkEmbed ?? checkEmbed)(youtubeId);
|
|
if (e.state === 'noembed') return c.json({ error: '이 영상은 다른 사이트에서 재생할 수 없게 막혀 있어요(퍼가기 금지). 다른 영상을 골라 주세요.' }, 400);
|
|
if (e.state === 'dead') return c.json({ error: '없는 영상이에요.' }, 400);
|
|
if (e.state === 'error') return c.json({ error: '유튜브 확인에 실패했어요. 잠시 후 다시 시도해 주세요.' }, 502);
|
|
embed = { author: e.author, title: e.title };
|
|
}
|
|
}
|
|
const genres = new Set(genreList(d.db).map((g) => g.id));
|
|
if (rest.genres?.some((g) => !genres.has(g))) return c.json({ error: '없는 장르가 있어요.' }, 400);
|
|
updateSong(d.db, id, { ...rest, youtubeId }, embed);
|
|
d.onCatalogChange?.();
|
|
const after = getSong(d.db, id)!;
|
|
d.audit.log(actor(c), 'song.update', String(id), { title: before.song.title, artist: before.song.artist }, parsed.data);
|
|
return c.json(after);
|
|
});
|
|
|
|
// ------------------------------------------------------------ audit
|
|
app.get('/audit', (c) => {
|
|
const page = Math.max(0, Number(c.req.query('page') ?? 0) || 0);
|
|
return c.json({ entries: d.audit.list(50, page * 50) });
|
|
});
|
|
|
|
// ------------------------------------------------------------ users (superadmin)
|
|
app.use('/users/*', superOnly);
|
|
app.use('/users', superOnly);
|
|
app.get('/users', (c) => {
|
|
const q = (c.req.query('q') ?? '').trim().slice(0, 60);
|
|
const page = Math.max(0, Number(c.req.query('page') ?? 0) || 0);
|
|
const { rows, total } = d.users.search(q, 30, page * 30);
|
|
return c.json({
|
|
total,
|
|
users: rows.map((u) => ({
|
|
id: u.id,
|
|
nickname: u.nickname,
|
|
kind: u.kind,
|
|
discordId: u.discord_id,
|
|
discordName: u.discord_name,
|
|
role: d.roles.roleOfDiscord(u.discord_id),
|
|
banned: u.banned_at ? { at: u.banned_at, reason: u.banned_reason } : null,
|
|
createdAt: u.created_at,
|
|
lastSeenAt: u.last_seen_at,
|
|
})),
|
|
});
|
|
});
|
|
|
|
app.patch('/users/:id', async (c) => {
|
|
const id = c.req.param('id');
|
|
const u = d.users.get(id);
|
|
if (!u) return c.json({ error: '사용자를 찾을 수 없어요.' }, 404);
|
|
const parsed = z
|
|
.object({ nickname: z.string().max(100).optional(), ban: z.object({ reason: z.string().trim().min(1).max(200) }).nullable().optional() })
|
|
.safeParse(await body(c));
|
|
if (!parsed.success) return c.json({ error: '입력 값이 올바르지 않아요.' }, 400);
|
|
const discordId = d.roles.discordIdOf(id);
|
|
if (parsed.data.ban && discordId && d.roles.isSuperadminDiscord(discordId)) return c.json({ error: '슈퍼어드민은 제한할 수 없어요.' }, 400);
|
|
if (parsed.data.nickname !== undefined) {
|
|
const nick = normalizeNickname(parsed.data.nickname);
|
|
const e = nicknameError(nick, d.settings.getSite().bannedWords);
|
|
if (e) return c.json({ error: e }, 400);
|
|
d.users.forceNickname(id, nick);
|
|
d.audit.log(actor(c), 'user.rename', id, u.nickname, nick);
|
|
}
|
|
if (parsed.data.ban !== undefined) {
|
|
if (parsed.data.ban) {
|
|
d.users.setBan(id, parsed.data.ban.reason);
|
|
d.sessions.revokeAll(id);
|
|
d.disconnectUser(id);
|
|
d.audit.log(actor(c), 'user.ban', id, null, parsed.data.ban);
|
|
} else {
|
|
d.users.setBan(id, null);
|
|
d.audit.log(actor(c), 'user.unban', id, { reason: u.banned_reason }, null);
|
|
}
|
|
}
|
|
return c.json({ ok: true });
|
|
});
|
|
|
|
app.post('/users/:id/logout', (c) => {
|
|
const id = c.req.param('id');
|
|
if (!d.users.get(id)) return c.json({ error: '사용자를 찾을 수 없어요.' }, 404);
|
|
d.sessions.revokeAll(id);
|
|
d.disconnectUser(id);
|
|
d.audit.log(actor(c), 'user.logout', id, null, null);
|
|
return c.json({ ok: true });
|
|
});
|
|
|
|
app.delete('/users/:id', (c) => {
|
|
const id = c.req.param('id');
|
|
const u = d.users.get(id);
|
|
if (!u) return c.json({ error: '사용자를 찾을 수 없어요.' }, 404);
|
|
const discordId = d.roles.discordIdOf(id);
|
|
if (discordId && d.roles.isSuperadminDiscord(discordId)) return c.json({ error: '슈퍼어드민은 삭제할 수 없어요.' }, 400);
|
|
d.disconnectUser(id);
|
|
d.users.softDelete(id);
|
|
d.audit.log(actor(c), 'user.delete', id, { nickname: u.nickname, discordId }, null);
|
|
return c.json({ ok: true });
|
|
});
|
|
|
|
// ------------------------------------------------------------ admins (superadmin)
|
|
app.use('/admins/*', superOnly);
|
|
app.use('/admins', superOnly);
|
|
app.get('/admins', (c) => c.json({ admins: d.roles.listAdmins() }));
|
|
app.post('/admins', async (c) => {
|
|
const parsed = z.object({ discordId: z.string().trim(), note: z.string().trim().max(100).optional() }).safeParse(await body(c));
|
|
if (!parsed.success || !DISCORD_ID.test(parsed.data.discordId)) return c.json({ error: '디스코드 ID는 숫자 17~20자리예요.' }, 400);
|
|
if (d.roles.isSuperadminDiscord(parsed.data.discordId)) return c.json({ error: '이미 슈퍼어드민이에요.' }, 400);
|
|
if (!d.roles.addAdmin(parsed.data.discordId, parsed.data.note ?? null, actor(c))) return c.json({ error: '이미 등록된 관리자예요.' }, 400);
|
|
d.audit.log(actor(c), 'admin.add', parsed.data.discordId, null, { note: parsed.data.note ?? null });
|
|
return c.json({ admins: d.roles.listAdmins() });
|
|
});
|
|
app.delete('/admins/:discordId', (c) => {
|
|
const id = c.req.param('discordId');
|
|
if (d.roles.isSuperadminDiscord(id)) return c.json({ error: '설정 파일의 슈퍼어드민은 지울 수 없어요.' }, 400);
|
|
if (!d.roles.removeAdmin(id)) return c.json({ error: '등록되지 않은 디스코드 ID예요.' }, 404);
|
|
d.audit.log(actor(c), 'admin.remove', id, null, null);
|
|
return c.json({ admins: d.roles.listAdmins() });
|
|
});
|
|
|
|
return app;
|
|
}
|