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:
64
apps/server/src/admin.test.ts
Normal file
64
apps/server/src/admin.test.ts
Normal file
@@ -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<typeof boot>;
|
||||
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);
|
||||
});
|
||||
});
|
||||
90
apps/server/src/admin/roles.ts
Normal file
90
apps/server/src/admin/roles.ts
Normal 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,
|
||||
}));
|
||||
}
|
||||
}
|
||||
41
apps/server/src/admin/settings.ts
Normal file
41
apps/server/src/admin/settings.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
108
apps/server/src/auth.test.ts
Normal file
108
apps/server/src/auth.test.ts
Normal file
@@ -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<typeof boot>;
|
||||
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: '<script>' }) })).res.status).toBe(400);
|
||||
s.settings.setSite({ ...s.settings.getSite(), bannedWords: ['금지어'] }, 'test');
|
||||
const r = await api(s.base, '/api/auth/guest', { method: 'POST', body: JSON.stringify({ nickname: '금 지 어' }) });
|
||||
expect(r.res.status).toBe(400);
|
||||
});
|
||||
|
||||
test('guest logout deletes the account', async () => {
|
||||
s = boot();
|
||||
const g = await guest(s.base, '게스트');
|
||||
expect((await api(s.base, '/api/auth/logout', { method: 'POST', body: '{}', cookie: g.cookie })).res.status).toBe(200);
|
||||
expect(s.users.get(g.id)).toBeNull();
|
||||
expect((await api(s.base, '/api/me', { cookie: g.cookie })).body.me).toBeNull();
|
||||
});
|
||||
|
||||
test('idle guests are purged after a day unless still connected', async () => {
|
||||
s = boot();
|
||||
const g = await guest(s.base, '오래된손님');
|
||||
s.purgeIdleGuests(Date.now() + 25 * 3600_000);
|
||||
expect(s.users.get(g.id)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('CSRF', () => {
|
||||
test('state-changing requests need our origin', async () => {
|
||||
s = boot();
|
||||
const noOrigin = await api(s.base, '/api/auth/guest', { method: 'POST', body: JSON.stringify({ nickname: '손님' }), origin: null });
|
||||
expect(noOrigin.res.status).toBe(403);
|
||||
const evil = await api(s.base, '/api/auth/guest', { method: 'POST', body: JSON.stringify({ nickname: '손님' }), origin: 'https://evil.example' });
|
||||
expect(evil.res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('discord login', () => {
|
||||
test('hidden when not configured', async () => {
|
||||
s = boot();
|
||||
expect((await api(s.base, '/api/config')).body.discord).toBe(false);
|
||||
expect((await api(s.base, '/api/auth/discord/start')).res.status).toBe(404);
|
||||
});
|
||||
|
||||
test('start redirects to the Discord consent screen for the 음악퀴즈 app with identify scope only', async () => {
|
||||
s = boot({ discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: '1561284577564037140', DISCORD_CLIENT_SECRET: 'x' });
|
||||
const r = await api(s.base, '/api/auth/discord/start?next=/r/123');
|
||||
expect(r.res.status).toBe(302);
|
||||
const loc = new URL(r.res.headers.get('location')!);
|
||||
expect(loc.origin + loc.pathname).toBe('https://discord.com/oauth2/authorize');
|
||||
expect(loc.searchParams.get('client_id')).toBe('1561284577564037140');
|
||||
expect(loc.searchParams.get('scope')).toBe('identify');
|
||||
expect(loc.searchParams.get('redirect_uri')).toBe('http://localhost:5173/api/auth/discord/callback');
|
||||
expect(loc.searchParams.get('state')!.length).toBeGreaterThan(20);
|
||||
expect(cookieOf(r.setCookie, 'oauth')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('callback with a wrong state fails, the right one logs in and returns to next', async () => {
|
||||
s = boot({ discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' });
|
||||
const start = await api(s.base, '/api/auth/discord/start?next=/admin');
|
||||
const oauth = cookieOf(start.setCookie, 'oauth')!;
|
||||
const bad = await api(s.base, '/api/auth/discord/callback?code=123456789012345678&state=wrong', { cookie: oauth });
|
||||
expect(bad.res.headers.get('location')).toBe('/?login=failed');
|
||||
const r = await discordLogin(s.base, '123456789012345679');
|
||||
expect(r.cb.res.headers.get('location')).toBe('/admin');
|
||||
const me = await api(s.base, '/api/me', { cookie: r.cookie });
|
||||
expect(me.body.me).toMatchObject({ nickname: '사금향', kind: 'member', avatar: 'https://cdn.discordapp.com/avatars/123456789012345679/abc.png?size=128' });
|
||||
});
|
||||
|
||||
test('a guest who logs in with Discord becomes that member (linked=1)', async () => {
|
||||
s = boot({ discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' });
|
||||
const g = await guest(s.base, '손님');
|
||||
const r = await discordLogin(s.base, '123456789012345671', g.cookie);
|
||||
expect(r.cb.res.headers.get('location')).toBe('/admin?linked=1');
|
||||
const me = await api(s.base, '/api/me', { cookie: r.cookie });
|
||||
expect(me.body.me).toMatchObject({ id: g.id, kind: 'member', nickname: '손님' });
|
||||
});
|
||||
|
||||
test('banned accounts cannot log in', async () => {
|
||||
s = boot({ discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' });
|
||||
const first = await discordLogin(s.base, '123456789012345672');
|
||||
const id = (await api(s.base, '/api/me', { cookie: first.cookie })).body.me.id;
|
||||
s.users.setBan(id, '테스트');
|
||||
const again = await discordLogin(s.base, '123456789012345672');
|
||||
expect(again.cb.res.headers.get('location')).toBe('/?login=banned');
|
||||
});
|
||||
|
||||
test('superadmin Discord IDs get the superadmin role', async () => {
|
||||
s = boot({ discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' });
|
||||
const r = await discordLogin(s.base, TEST_SUPERADMINS[0]);
|
||||
expect((await api(s.base, '/api/me', { cookie: r.cookie })).body.role).toBe('superadmin');
|
||||
});
|
||||
});
|
||||
59
apps/server/src/auth/discord.ts
Normal file
59
apps/server/src/auth/discord.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/** Discord OAuth2 (authorization code + state), docs/02, ported from joke-app. */
|
||||
export interface DiscordUser {
|
||||
id: string;
|
||||
username: string;
|
||||
global_name: string | null;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
const API = 'https://discord.com/api/v10';
|
||||
|
||||
export function authorizeUrl(clientId: string, redirectUri: string, state: string): string {
|
||||
const p = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
response_type: 'code',
|
||||
redirect_uri: redirectUri,
|
||||
scope: 'identify',
|
||||
state,
|
||||
prompt: 'none',
|
||||
});
|
||||
return `https://discord.com/oauth2/authorize?${p}`;
|
||||
}
|
||||
|
||||
export async function exchangeCode(
|
||||
cfg: { clientId: string; clientSecret: string },
|
||||
code: string,
|
||||
redirectUri: string,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<DiscordUser> {
|
||||
const tokenRes = await fetchImpl(`${API}/oauth2/token`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
client_id: cfg.clientId,
|
||||
client_secret: cfg.clientSecret,
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
redirect_uri: redirectUri,
|
||||
}),
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (!tokenRes.ok) throw new Error(`discord token exchange failed: ${tokenRes.status}`);
|
||||
const token = (await tokenRes.json()) as { access_token: string; token_type: string };
|
||||
const meRes = await fetchImpl(`${API}/users/@me`, {
|
||||
headers: { Authorization: `${token.token_type} ${token.access_token}` },
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (!meRes.ok) throw new Error(`discord /users/@me failed: ${meRes.status}`);
|
||||
return (await meRes.json()) as DiscordUser;
|
||||
}
|
||||
|
||||
export function avatarUrl(u: DiscordUser): string | null {
|
||||
return u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png?size=128` : null;
|
||||
}
|
||||
|
||||
/** Only same-site relative paths are allowed as post-login redirect targets. */
|
||||
export function safeNext(next: string | null | undefined): string {
|
||||
if (!next || !next.startsWith('/') || next.startsWith('//') || next.includes('\\')) return '/';
|
||||
return next;
|
||||
}
|
||||
90
apps/server/src/auth/sessions.ts
Normal file
90
apps/server/src/auth/sessions.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import type { Database } from 'bun:sqlite';
|
||||
|
||||
const DAY = 24 * 3600_000;
|
||||
export const SESSION_TTL = { guest: 365 * DAY, member: 90 * DAY } as const;
|
||||
export const SESSION_COOKIE = 'sid';
|
||||
/** users.last_seen_at is written at most this often per user. */
|
||||
const SEEN_EVERY = 60_000;
|
||||
|
||||
export function randomToken(bytes = 32): string {
|
||||
const buf = new Uint8Array(bytes);
|
||||
crypto.getRandomValues(buf);
|
||||
return Buffer.from(buf).toString('base64url');
|
||||
}
|
||||
|
||||
export function sha256Hex(input: string): string {
|
||||
return new Bun.CryptoHasher('sha256').update(input).digest('hex');
|
||||
}
|
||||
|
||||
export class Sessions {
|
||||
constructor(private db: Database) {}
|
||||
|
||||
create(userId: string, kind: 'guest' | 'member', userAgent: string | null, now = Date.now()): { token: string; expiresAt: number } {
|
||||
const token = randomToken();
|
||||
const expiresAt = now + SESSION_TTL[kind];
|
||||
this.db
|
||||
.query('INSERT INTO sessions (token_hash, user_id, created_at, expires_at, last_used_at, user_agent) VALUES (?, ?, ?, ?, ?, ?)')
|
||||
.run(sha256Hex(token), userId, now, expiresAt, now, userAgent?.slice(0, 200) ?? null);
|
||||
return { token, expiresAt };
|
||||
}
|
||||
|
||||
/** Resolves a token to a user id; slides expiry at most once per day. */
|
||||
resolve(token: string, now = Date.now()): string | null {
|
||||
const hash = sha256Hex(token);
|
||||
const row = this.db
|
||||
.query<{ user_id: string; expires_at: number; last_used_at: number; kind: 'guest' | 'member'; last_seen_at: number }, [string]>(
|
||||
`SELECT s.user_id, s.expires_at, s.last_used_at, u.kind, u.last_seen_at FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = ? AND u.deleted_at IS NULL AND u.banned_at IS NULL`,
|
||||
)
|
||||
.get(hash);
|
||||
if (!row) return null;
|
||||
if (row.expires_at <= now) {
|
||||
this.db.query('DELETE FROM sessions WHERE token_hash = ?').run(hash);
|
||||
return null;
|
||||
}
|
||||
if (now - row.last_used_at > DAY) {
|
||||
this.db
|
||||
.query('UPDATE sessions SET last_used_at = ?, expires_at = ? WHERE token_hash = ?')
|
||||
.run(now, now + SESSION_TTL[row.kind], hash);
|
||||
}
|
||||
// Idle guests are deleted after a day (docs/02), so remember when the user was last here.
|
||||
if (now - row.last_seen_at > SEEN_EVERY) this.db.query('UPDATE users SET last_seen_at = ? WHERE id = ?').run(now, row.user_id);
|
||||
return row.user_id;
|
||||
}
|
||||
|
||||
revoke(token: string): void {
|
||||
this.db.query('DELETE FROM sessions WHERE token_hash = ?').run(sha256Hex(token));
|
||||
}
|
||||
|
||||
revokeAll(userId: string): void {
|
||||
this.db.query('DELETE FROM sessions WHERE user_id = ?').run(userId);
|
||||
}
|
||||
|
||||
purgeExpired(now = Date.now()): number {
|
||||
return this.db.query('DELETE FROM sessions WHERE expires_at <= ?').run(now).changes;
|
||||
}
|
||||
}
|
||||
|
||||
/** Minimal HMAC-signed value for short-lived cookies (OAuth state + PKCE verifier). */
|
||||
export async function signValue(secret: string, value: string): Promise<string> {
|
||||
const mac = await hmac(secret, value);
|
||||
return `${Buffer.from(value).toString('base64url')}.${mac}`;
|
||||
}
|
||||
|
||||
export async function unsignValue(secret: string, signed: string): Promise<string | null> {
|
||||
const dot = signed.lastIndexOf('.');
|
||||
if (dot < 0) return null;
|
||||
const value = Buffer.from(signed.slice(0, dot), 'base64url').toString();
|
||||
const expected = await hmac(secret, value);
|
||||
const given = signed.slice(dot + 1);
|
||||
if (expected.length !== given.length) return null;
|
||||
let diff = 0;
|
||||
for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i);
|
||||
return diff === 0 ? value : null;
|
||||
}
|
||||
|
||||
async function hmac(secret: string, value: string): Promise<string> {
|
||||
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
||||
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value));
|
||||
return Buffer.from(sig).toString('base64url');
|
||||
}
|
||||
171
apps/server/src/auth/users.ts
Normal file
171
apps/server/src/auth/users.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
/** Accounts (docs/02). Ported from joke-app without the board-game stats tables. */
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { ulid } from 'ulid';
|
||||
import type { PublicUser } from '@mq/shared';
|
||||
|
||||
export interface UserRow {
|
||||
id: string;
|
||||
kind: 'guest' | 'member';
|
||||
nickname: string;
|
||||
avatar_url: string | null;
|
||||
use_avatar: number;
|
||||
settings_json: string;
|
||||
nick_changed_at: number | null;
|
||||
nick_change_count: number;
|
||||
created_at: number;
|
||||
last_seen_at: number;
|
||||
deleted_at: number | null;
|
||||
banned_at: number | null;
|
||||
banned_reason: string | null;
|
||||
}
|
||||
|
||||
export const NICK_CHANGES_PER_DAY = 10;
|
||||
|
||||
export class Users {
|
||||
constructor(private db: Database) {}
|
||||
|
||||
get(id: string): UserRow | null {
|
||||
return this.db.query<UserRow, [string]>('SELECT * FROM users WHERE id = ? AND deleted_at IS NULL').get(id);
|
||||
}
|
||||
|
||||
createGuest(nickname: string, now = Date.now()): UserRow {
|
||||
const id = ulid(now);
|
||||
this.db.query('INSERT INTO users (id, kind, nickname, created_at, last_seen_at) VALUES (?, ?, ?, ?, ?)').run(id, 'guest', nickname, now, now);
|
||||
return this.get(id)!;
|
||||
}
|
||||
|
||||
findByOauth(provider: string, providerUserId: string): UserRow | null {
|
||||
return this.db
|
||||
.query<UserRow, [string, string]>(
|
||||
`SELECT u.* FROM users u JOIN oauth_accounts o ON o.user_id = u.id
|
||||
WHERE o.provider = ? AND o.provider_user_id = ? AND u.deleted_at IS NULL`,
|
||||
)
|
||||
.get(provider, providerUserId);
|
||||
}
|
||||
|
||||
createMember(nickname: string, avatarUrl: string | null, now = Date.now()): UserRow {
|
||||
const id = ulid(now);
|
||||
this.db
|
||||
.query('INSERT INTO users (id, kind, nickname, avatar_url, created_at, last_seen_at) VALUES (?, ?, ?, ?, ?, ?)')
|
||||
.run(id, 'member', nickname, avatarUrl, now, now);
|
||||
return this.get(id)!;
|
||||
}
|
||||
|
||||
linkOauth(userId: string, provider: string, providerUserId: string, username: string | null, now = Date.now()): void {
|
||||
this.db
|
||||
.query('INSERT INTO oauth_accounts (provider, provider_user_id, user_id, username, created_at) VALUES (?, ?, ?, ?, ?)')
|
||||
.run(provider, providerUserId, userId, username, now);
|
||||
}
|
||||
|
||||
promoteToMember(userId: string, avatarUrl: string | null): void {
|
||||
this.db.query("UPDATE users SET kind = 'member', avatar_url = ? WHERE id = ?").run(avatarUrl, userId);
|
||||
}
|
||||
|
||||
setAvatar(userId: string, avatarUrl: string | null): void {
|
||||
this.db.query('UPDATE users SET avatar_url = ? WHERE id = ?').run(avatarUrl, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* A guest logs in with Discord that already has an account: the guest is folded into it.
|
||||
* (Saved quizzes and play records are added in later stages and move here too.)
|
||||
*/
|
||||
mergeGuestInto(guestId: string, memberId: string): void {
|
||||
void memberId;
|
||||
this.db.transaction(() => {
|
||||
this.db.query('DELETE FROM sessions WHERE user_id = ?').run(guestId);
|
||||
this.db.query('DELETE FROM users WHERE id = ?').run(guestId);
|
||||
})();
|
||||
}
|
||||
|
||||
/** Returns an error message or null. Enforces the daily change limit. */
|
||||
changeNickname(userId: string, nickname: string, now = Date.now()): string | null {
|
||||
const u = this.get(userId);
|
||||
if (!u) return '사용자를 찾을 수 없어요.';
|
||||
if (u.nickname === nickname) return null;
|
||||
const sameDay = u.nick_changed_at !== null && now - u.nick_changed_at < 24 * 3600_000;
|
||||
const count = sameDay ? u.nick_change_count : 0;
|
||||
if (count >= NICK_CHANGES_PER_DAY) return `닉네임은 하루에 ${NICK_CHANGES_PER_DAY}번까지 바꿀 수 있어요.`;
|
||||
this.db
|
||||
.query('UPDATE users SET nickname = ?, nick_changed_at = ?, nick_change_count = ? WHERE id = ?')
|
||||
.run(nickname, sameDay ? u.nick_changed_at : now, count + 1, userId);
|
||||
return null;
|
||||
}
|
||||
|
||||
updateSettings(userId: string, patch: { useAvatar?: boolean; settings?: Record<string, unknown> }): void {
|
||||
if (patch.useAvatar !== undefined) this.db.query('UPDATE users SET use_avatar = ? WHERE id = ?').run(patch.useAvatar ? 1 : 0, userId);
|
||||
if (patch.settings) this.db.query('UPDATE users SET settings_json = ? WHERE id = ?').run(JSON.stringify(patch.settings), userId);
|
||||
}
|
||||
|
||||
/** Admin rename: ignores the daily limit. */
|
||||
forceNickname(userId: string, nickname: string): void {
|
||||
this.db.query('UPDATE users SET nickname = ? WHERE id = ?').run(nickname, userId);
|
||||
}
|
||||
|
||||
setBan(userId: string, reason: string | null, now = Date.now()): void {
|
||||
if (reason === null) this.db.query('UPDATE users SET banned_at = NULL, banned_reason = NULL WHERE id = ?').run(userId);
|
||||
else this.db.query('UPDATE users SET banned_at = ?, banned_reason = ? WHERE id = ?').run(now, reason, userId);
|
||||
}
|
||||
|
||||
search(q: string, limit: number, offset: number) {
|
||||
const like = `%${q.replace(/[%_\\]/g, (m) => '\\' + m)}%`;
|
||||
const rows = this.db
|
||||
.query<UserRow & { discord_id: string | null; discord_name: string | null }, [string, string, string, string, number, number]>(
|
||||
`SELECT u.*, o.provider_user_id AS discord_id, o.username AS discord_name
|
||||
FROM users u
|
||||
LEFT JOIN oauth_accounts o ON o.user_id = u.id AND o.provider = 'discord'
|
||||
WHERE u.deleted_at IS NULL AND (? = '' OR u.nickname LIKE ? ESCAPE '\\' OR u.id = ? OR o.provider_user_id = ?)
|
||||
ORDER BY u.last_seen_at DESC LIMIT ? OFFSET ?`,
|
||||
)
|
||||
.all(q, like, q, q, limit, offset);
|
||||
const total = this.db.query<{ n: number }, []>('SELECT COUNT(*) AS n FROM users WHERE deleted_at IS NULL').get()!.n;
|
||||
return { rows, total };
|
||||
}
|
||||
|
||||
counts(): { total: number; guests: number; members: number; banned: number } {
|
||||
const r = this.db
|
||||
.query<{ total: number; guests: number | null; members: number | null; banned: number | null }, []>(
|
||||
`SELECT COUNT(*) AS total, SUM(kind = 'guest') AS guests, SUM(kind = 'member') AS members, SUM(banned_at IS NOT NULL) AS banned
|
||||
FROM users WHERE deleted_at IS NULL`,
|
||||
)
|
||||
.get()!;
|
||||
return { total: r.total, guests: r.guests ?? 0, members: r.members ?? 0, banned: r.banned ?? 0 };
|
||||
}
|
||||
|
||||
touch(userId: string, now = Date.now()): void {
|
||||
this.db.query('UPDATE users SET last_seen_at = ? WHERE id = ?').run(now, userId);
|
||||
}
|
||||
|
||||
/** Guests not seen since `before`, oldest first. */
|
||||
idleGuests(before: number, limit = 500): string[] {
|
||||
return this.db
|
||||
.query<{ id: string }, [number, number]>(
|
||||
"SELECT id FROM users WHERE kind = 'guest' AND deleted_at IS NULL AND last_seen_at < ? ORDER BY last_seen_at LIMIT ?",
|
||||
)
|
||||
.all(before, limit)
|
||||
.map((r) => r.id);
|
||||
}
|
||||
|
||||
/** Removes a guest account for good (logout, or idle for a day). Returns false for non-guests. */
|
||||
deleteGuest(userId: string): boolean {
|
||||
return this.db.transaction(() => {
|
||||
const row = this.db.query<{ kind: string }, [string]>('SELECT kind FROM users WHERE id = ?').get(userId);
|
||||
if (row?.kind !== 'guest') return false;
|
||||
this.db.query('DELETE FROM sessions WHERE user_id = ?').run(userId);
|
||||
this.db.query('DELETE FROM oauth_accounts WHERE user_id = ?').run(userId);
|
||||
this.db.query('DELETE FROM users WHERE id = ?').run(userId);
|
||||
return true;
|
||||
})();
|
||||
}
|
||||
|
||||
softDelete(userId: string, now = Date.now()): void {
|
||||
this.db.transaction(() => {
|
||||
this.db.query("UPDATE users SET deleted_at = ?, nickname = '탈퇴한 사용자', avatar_url = NULL WHERE id = ?").run(now, userId);
|
||||
this.db.query('DELETE FROM oauth_accounts WHERE user_id = ?').run(userId);
|
||||
this.db.query('DELETE FROM sessions WHERE user_id = ?').run(userId);
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
export function toPublicUser(u: UserRow): PublicUser {
|
||||
return { id: u.id, nickname: u.nickname, avatar: u.use_avatar && u.avatar_url ? u.avatar_url : null, kind: u.kind };
|
||||
}
|
||||
36
apps/server/src/config.ts
Normal file
36
apps/server/src/config.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
export interface Config {
|
||||
port: number;
|
||||
publicOrigin: string;
|
||||
/** Extra origins accepted for WS/CSRF checks (e.g. the Vite dev server). */
|
||||
allowedOrigins: string[];
|
||||
dbPath: string;
|
||||
discord: { clientId: string; clientSecret: string } | null;
|
||||
sessionSecret: string;
|
||||
secureCookies: boolean;
|
||||
/** Trust X-Forwarded-For (only behind our reverse proxy). */
|
||||
trustProxy: boolean;
|
||||
/** Superadmin Discord IDs (docs/02). Only in deploy/.env, never in the repo. */
|
||||
superadminDiscordIds: string[];
|
||||
}
|
||||
|
||||
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
|
||||
const publicOrigin = (env.PUBLIC_ORIGIN ?? 'http://localhost:5173').replace(/\/$/, '');
|
||||
const extra = (env.ALLOWED_ORIGINS ?? '').split(',').map((s) => s.trim()).filter(Boolean);
|
||||
const clientId = env.DISCORD_CLIENT_ID;
|
||||
const clientSecret = env.DISCORD_CLIENT_SECRET;
|
||||
const sessionSecret = env.SESSION_SECRET ?? '';
|
||||
if (publicOrigin.startsWith('https://') && sessionSecret.length < 32) {
|
||||
throw new Error('SESSION_SECRET must be at least 32 characters in production');
|
||||
}
|
||||
return {
|
||||
port: Number(env.PORT ?? 3000),
|
||||
publicOrigin,
|
||||
allowedOrigins: [publicOrigin, ...extra],
|
||||
dbPath: env.DB_PATH ?? './data/app.db',
|
||||
discord: clientId && clientSecret ? { clientId, clientSecret } : null,
|
||||
sessionSecret: sessionSecret || 'dev-only-insecure-session-secret-change-me',
|
||||
secureCookies: publicOrigin.startsWith('https://'),
|
||||
trustProxy: env.TRUST_PROXY === '1',
|
||||
superadminDiscordIds: (env.SUPERADMIN_DISCORD_IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
};
|
||||
}
|
||||
32
apps/server/src/db/index.ts
Normal file
32
apps/server/src/db/index.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Database } from 'bun:sqlite';
|
||||
import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const MIGRATIONS_DIR = join(import.meta.dir, 'migrations');
|
||||
|
||||
export function openDb(path: string): Database {
|
||||
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
|
||||
const db = new Database(path, { create: true, strict: true });
|
||||
db.exec('PRAGMA journal_mode = WAL;');
|
||||
db.exec('PRAGMA synchronous = NORMAL;');
|
||||
db.exec('PRAGMA foreign_keys = ON;');
|
||||
db.exec('PRAGMA busy_timeout = 5000;');
|
||||
migrate(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
export function migrate(db: Database): void {
|
||||
db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)');
|
||||
const applied = new Set(
|
||||
db.query<{ name: string }, []>('SELECT name FROM schema_migrations').all().map((r) => r.name),
|
||||
);
|
||||
const files = readdirSync(MIGRATIONS_DIR).filter((f) => f.endsWith('.sql')).sort();
|
||||
for (const file of files) {
|
||||
if (applied.has(file)) continue;
|
||||
const sql = readFileSync(join(MIGRATIONS_DIR, file), 'utf8');
|
||||
db.transaction(() => {
|
||||
db.exec(sql);
|
||||
db.query('INSERT INTO schema_migrations (name, applied_at) VALUES (?, ?)').run(file, Date.now());
|
||||
})();
|
||||
}
|
||||
}
|
||||
63
apps/server/src/db/migrations/001_init.sql
Normal file
63
apps/server/src/db/migrations/001_init.sql
Normal file
@@ -0,0 +1,63 @@
|
||||
-- Accounts, sessions, admins, settings, audit (docs/02). Same shape as joke-app 001~003 minus the board-game tables.
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL CHECK (kind IN ('guest','member')),
|
||||
nickname TEXT NOT NULL,
|
||||
avatar_url TEXT,
|
||||
use_avatar INTEGER NOT NULL DEFAULT 1,
|
||||
settings_json TEXT NOT NULL DEFAULT '{}',
|
||||
nick_changed_at INTEGER,
|
||||
nick_change_count INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
last_seen_at INTEGER NOT NULL,
|
||||
deleted_at INTEGER,
|
||||
banned_at INTEGER,
|
||||
banned_reason TEXT
|
||||
);
|
||||
-- Idle guests are deleted a day after their last visit.
|
||||
CREATE INDEX users_guest_seen ON users(kind, last_seen_at);
|
||||
|
||||
CREATE TABLE oauth_accounts (
|
||||
provider TEXT NOT NULL,
|
||||
provider_user_id TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
username TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (provider, provider_user_id)
|
||||
);
|
||||
CREATE INDEX oauth_accounts_user ON oauth_accounts(user_id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
last_used_at INTEGER NOT NULL,
|
||||
user_agent TEXT
|
||||
);
|
||||
CREATE INDEX sessions_user ON sessions(user_id);
|
||||
|
||||
CREATE TABLE admins (
|
||||
discord_id TEXT PRIMARY KEY,
|
||||
note TEXT,
|
||||
added_by TEXT,
|
||||
added_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE site_settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
json TEXT NOT NULL,
|
||||
updated_by TEXT,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE admin_audit (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
actor_id TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
target TEXT,
|
||||
before_json TEXT,
|
||||
after_json TEXT,
|
||||
at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX admin_audit_at ON admin_audit(at);
|
||||
158
apps/server/src/http/admin.ts
Normal file
158
apps/server/src/http/admin.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
/** 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';
|
||||
|
||||
export interface AdminDeps {
|
||||
users: Users;
|
||||
sessions: Sessions;
|
||||
roles: Roles;
|
||||
audit: Audit;
|
||||
settings: SettingsStore;
|
||||
disconnectUser: (userId: string) => void;
|
||||
stats: () => Record<string, unknown>;
|
||||
}
|
||||
|
||||
type Env = { Variables: { userId: string | null; role: Role } };
|
||||
|
||||
const DISCORD_ID = /^\d{17,20}$/;
|
||||
|
||||
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 });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 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;
|
||||
}
|
||||
203
apps/server/src/http/app.ts
Normal file
203
apps/server/src/http/app.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
/** HTTP API (docs/02). Login flow ported from joke-app. */
|
||||
import { Hono, type Context } from 'hono';
|
||||
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
||||
import { z } from 'zod';
|
||||
import { nicknameError, normalizeNickname } from '@mq/shared';
|
||||
import type { Config } from '../config';
|
||||
import { authorizeUrl, avatarUrl, exchangeCode, safeNext, type DiscordUser } from '../auth/discord';
|
||||
import { SESSION_COOKIE, SESSION_TTL, randomToken, signValue, unsignValue, type Sessions } from '../auth/sessions';
|
||||
import { toPublicUser, type Users } from '../auth/users';
|
||||
import { WindowLimiter } from '../ws/rate-limit';
|
||||
import { createAdminApp, type AdminDeps } from './admin';
|
||||
import type { Roles } from '../admin/roles';
|
||||
import type { SettingsStore } from '../admin/settings';
|
||||
|
||||
export interface HttpDeps {
|
||||
config: Config;
|
||||
users: Users;
|
||||
sessions: Sessions;
|
||||
roles: Roles;
|
||||
settings: SettingsStore;
|
||||
/** Injected for tests. */
|
||||
discordExchange?: (code: string, redirectUri: string) => Promise<DiscordUser>;
|
||||
ipOf: (req: Request) => string;
|
||||
health: () => { ok: boolean; [k: string]: unknown };
|
||||
admin: Omit<AdminDeps, 'users' | 'sessions' | 'roles' | 'settings'>;
|
||||
/** Deletes a guest account everywhere (sockets, DB). */
|
||||
removeGuest: (userId: string) => void;
|
||||
}
|
||||
|
||||
type Env = { Variables: { userId: string | null } };
|
||||
|
||||
const OAUTH_COOKIE = 'oauth';
|
||||
|
||||
export function createHttpApp(d: HttpDeps) {
|
||||
const app = new Hono<Env>();
|
||||
const guestLimiter = new WindowLimiter(20, 60_000);
|
||||
const redirectUri = `${d.config.publicOrigin}/api/auth/discord/callback`;
|
||||
|
||||
const cookieOpts = (maxAgeMs: number) => ({
|
||||
httpOnly: true,
|
||||
secure: d.config.secureCookies,
|
||||
sameSite: 'Lax' as const,
|
||||
path: '/',
|
||||
maxAge: Math.floor(maxAgeMs / 1000),
|
||||
});
|
||||
|
||||
// Session resolution.
|
||||
app.use('/api/*', async (c, next) => {
|
||||
const token = getCookie(c, SESSION_COOKIE);
|
||||
c.set('userId', token ? d.sessions.resolve(token) : null);
|
||||
await next();
|
||||
});
|
||||
|
||||
// CSRF: state-changing requests must come from our origin.
|
||||
app.use('/api/*', async (c, next) => {
|
||||
if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {
|
||||
const origin = c.req.header('origin');
|
||||
if (!origin || !d.config.allowedOrigins.includes(origin)) return c.json({ error: '잘못된 요청이에요.' }, 403);
|
||||
}
|
||||
await next();
|
||||
});
|
||||
|
||||
const userOf = (c: Context<Env>) => c.get('userId');
|
||||
|
||||
const startSession = (c: Context<Env>, userId: string, kind: 'guest' | 'member') => {
|
||||
const { token } = d.sessions.create(userId, kind, c.req.header('user-agent') ?? null);
|
||||
setCookie(c, SESSION_COOKIE, token, cookieOpts(SESSION_TTL[kind]));
|
||||
};
|
||||
|
||||
app.get('/healthz', (c) => {
|
||||
const h = d.health();
|
||||
return c.json(h, h.ok ? 200 : 503);
|
||||
});
|
||||
|
||||
app.get('/api/config', (c) => {
|
||||
const site = d.settings.getSite();
|
||||
return c.json({ discord: d.config.discord !== null, siteName: site.siteName, announcement: site.announcement, maintenance: site.maintenance });
|
||||
});
|
||||
|
||||
app.post('/api/auth/guest', async (c) => {
|
||||
if (!guestLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
|
||||
const body = z.object({ nickname: z.string().max(100) }).safeParse(await c.req.json().catch(() => null));
|
||||
if (!body.success) return c.json({ error: '닉네임을 입력해 주세요.' }, 400);
|
||||
const nick = normalizeNickname(body.data.nickname);
|
||||
const e = nicknameError(nick, d.settings.getSite().bannedWords);
|
||||
if (e) return c.json({ error: e }, 400);
|
||||
const current = userOf(c);
|
||||
if (current) {
|
||||
// Already signed in: a nickname change instead of another account.
|
||||
const err = d.users.changeNickname(current, nick);
|
||||
if (err) return c.json({ error: err }, 400);
|
||||
return c.json({ me: toPublicUser(d.users.get(current)!) });
|
||||
}
|
||||
const u = d.users.createGuest(nick);
|
||||
startSession(c, u.id, 'guest');
|
||||
return c.json({ me: toPublicUser(u) });
|
||||
});
|
||||
|
||||
app.get('/api/auth/discord/start', async (c) => {
|
||||
if (!d.config.discord) return c.text('디스코드 로그인이 설정되지 않았어요.', 404);
|
||||
const state = randomToken(24);
|
||||
const next = safeNext(c.req.query('next'));
|
||||
setCookie(c, OAUTH_COOKIE, await signValue(d.config.sessionSecret, JSON.stringify({ state, next, at: Date.now() })), {
|
||||
...cookieOpts(10 * 60_000),
|
||||
path: '/api/auth/discord',
|
||||
});
|
||||
return c.redirect(authorizeUrl(d.config.discord.clientId, redirectUri, state));
|
||||
});
|
||||
|
||||
app.get('/api/auth/discord/callback', async (c) => {
|
||||
const discord = d.config.discord;
|
||||
if (!discord) return c.text('디스코드 로그인이 설정되지 않았어요.', 404);
|
||||
const raw = getCookie(c, OAUTH_COOKIE);
|
||||
deleteCookie(c, OAUTH_COOKIE, { path: '/api/auth/discord' });
|
||||
const payload = raw ? await unsignValue(d.config.sessionSecret, raw) : null;
|
||||
const parsed = payload ? (JSON.parse(payload) as { state: string; next: string; at: number }) : null;
|
||||
const code = c.req.query('code');
|
||||
if (!parsed || !code || parsed.state !== c.req.query('state') || Date.now() - parsed.at > 10 * 60_000) {
|
||||
return c.redirect('/?login=failed');
|
||||
}
|
||||
let du: DiscordUser;
|
||||
try {
|
||||
du = d.discordExchange ? await d.discordExchange(code, redirectUri) : await exchangeCode(discord, code, redirectUri);
|
||||
} catch {
|
||||
return c.redirect('/?login=failed');
|
||||
}
|
||||
const avatar = avatarUrl(du);
|
||||
const existing = d.users.findByOauth('discord', du.id);
|
||||
if (existing?.banned_at) return c.redirect('/?login=banned');
|
||||
const currentId = userOf(c);
|
||||
const current = currentId ? d.users.get(currentId) : null;
|
||||
let userId: string;
|
||||
let linked = false;
|
||||
if (existing) {
|
||||
userId = existing.id;
|
||||
d.users.setAvatar(userId, avatar);
|
||||
if (current && current.kind === 'guest' && current.id !== existing.id) {
|
||||
d.users.mergeGuestInto(current.id, existing.id);
|
||||
linked = true;
|
||||
}
|
||||
} else if (current && current.kind === 'guest') {
|
||||
d.users.linkOauth(current.id, 'discord', du.id, du.username);
|
||||
d.users.promoteToMember(current.id, avatar);
|
||||
userId = current.id;
|
||||
linked = true;
|
||||
} else {
|
||||
const nick = normalizeNickname(du.global_name ?? du.username).slice(0, 12);
|
||||
const u = d.users.createMember(nicknameError(nick) ? '디스코드 사용자' : nick, avatar);
|
||||
d.users.linkOauth(u.id, 'discord', du.id, du.username);
|
||||
userId = u.id;
|
||||
}
|
||||
const old = getCookie(c, SESSION_COOKIE);
|
||||
if (old) d.sessions.revoke(old);
|
||||
startSession(c, userId, 'member');
|
||||
const next = safeNext(parsed.next);
|
||||
return c.redirect(linked ? `${next}${next.includes('?') ? '&' : '?'}linked=1` : next);
|
||||
});
|
||||
|
||||
app.post('/api/auth/logout', (c) => {
|
||||
const token = getCookie(c, SESSION_COOKIE);
|
||||
const u = userOf(c);
|
||||
// A guest has no way to log back in, so logging out deletes the account.
|
||||
if (u && d.users.get(u)?.kind === 'guest') d.removeGuest(u);
|
||||
else if (token) d.sessions.revoke(token);
|
||||
deleteCookie(c, SESSION_COOKIE, { path: '/' });
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get('/api/me', (c) => {
|
||||
const u = userOf(c);
|
||||
const row = u ? d.users.get(u) : null;
|
||||
if (!row) return c.json({ me: null });
|
||||
return c.json({ me: toPublicUser(row), settings: JSON.parse(row.settings_json), role: d.roles.roleOf(row.id) });
|
||||
});
|
||||
|
||||
app.patch('/api/me', async (c) => {
|
||||
const u = userOf(c);
|
||||
if (!u) return c.json({ error: '로그인이 필요해요.' }, 401);
|
||||
const body = z
|
||||
.object({
|
||||
nickname: z.string().max(100).optional(),
|
||||
useAvatar: z.boolean().optional(),
|
||||
settings: z
|
||||
.object({ fontScale: z.enum(['normal', 'large', 'xlarge']).optional(), theme: z.enum(['auto', 'light', 'dark']).optional() })
|
||||
.optional(),
|
||||
})
|
||||
.safeParse(await c.req.json().catch(() => null));
|
||||
if (!body.success) return c.json({ error: '잘못된 요청이에요.' }, 400);
|
||||
if (body.data.nickname !== undefined) {
|
||||
const nick = normalizeNickname(body.data.nickname);
|
||||
const e = nicknameError(nick, d.settings.getSite().bannedWords) ?? d.users.changeNickname(u, nick);
|
||||
if (e) return c.json({ error: e }, 400);
|
||||
}
|
||||
d.users.updateSettings(u, { useAvatar: body.data.useAvatar, settings: body.data.settings });
|
||||
return c.json({ me: toPublicUser(d.users.get(u)!) });
|
||||
});
|
||||
|
||||
app.route('/api/admin', createAdminApp({ ...d.admin, users: d.users, sessions: d.sessions, roles: d.roles, settings: d.settings }));
|
||||
|
||||
app.all('/api/*', (c) => c.json({ error: '없는 주소예요.' }, 404));
|
||||
|
||||
return app;
|
||||
}
|
||||
27
apps/server/src/index.ts
Normal file
27
apps/server/src/index.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { loadConfig } from './config';
|
||||
import { jsonLog, startServer } from './server';
|
||||
|
||||
const config = loadConfig();
|
||||
const app = startServer({ config });
|
||||
jsonLog('info', 'server started', { port: app.server.port, origin: config.publicOrigin, discord: config.discord !== null });
|
||||
|
||||
let stopping = false;
|
||||
const shutdown = async (signal: string) => {
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
jsonLog('info', 'shutting down', { signal });
|
||||
const force = setTimeout(() => process.exit(0), 10_000);
|
||||
await app.stop();
|
||||
clearTimeout(force);
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGTERM', () => void shutdown('SIGTERM'));
|
||||
process.on('SIGINT', () => void shutdown('SIGINT'));
|
||||
process.on('uncaughtException', (err) => {
|
||||
jsonLog('error', 'uncaughtException', { err: String(err), stack: err.stack });
|
||||
process.exit(1);
|
||||
});
|
||||
process.on('unhandledRejection', (err) => {
|
||||
jsonLog('error', 'unhandledRejection', { err: String(err) });
|
||||
process.exit(1);
|
||||
});
|
||||
144
apps/server/src/server.ts
Normal file
144
apps/server/src/server.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
/** Wires DB, auth, admin, HTTP and WebSocket into one Bun server (docs/01). Structure follows joke-app. */
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join, normalize } from 'node:path';
|
||||
import type { Server } from 'bun';
|
||||
import type { Config } from './config';
|
||||
import { openDb } from './db';
|
||||
import { SESSION_COOKIE, Sessions } from './auth/sessions';
|
||||
import { Users } from './auth/users';
|
||||
import { createHttpApp, type HttpDeps } from './http/app';
|
||||
import { Gateway, type WsData } from './ws/gateway';
|
||||
import { Audit, Roles } from './admin/roles';
|
||||
import { SettingsStore } from './admin/settings';
|
||||
|
||||
/** A guest who closed the site and stayed away this long is deleted (docs/02). */
|
||||
export const GUEST_IDLE_MS = 24 * 3600_000;
|
||||
|
||||
export type LogFn = (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
|
||||
|
||||
export const jsonLog: LogFn = (level, msg, extra) => {
|
||||
const line = JSON.stringify({ t: new Date().toISOString(), level, msg, ...extra });
|
||||
if (level === 'error') console.error(line);
|
||||
else console.log(line);
|
||||
};
|
||||
|
||||
export interface StartOptions {
|
||||
config: Config;
|
||||
log?: LogFn;
|
||||
staticDir?: string | null;
|
||||
discordExchange?: HttpDeps['discordExchange'];
|
||||
/** Upper bound for waiting on Bun's server.stop() (tests shorten it). */
|
||||
stopWaitMs?: number;
|
||||
}
|
||||
|
||||
export function startServer(opts: StartOptions) {
|
||||
const { config } = opts;
|
||||
const log = opts.log ?? jsonLog;
|
||||
const db = openDb(config.dbPath);
|
||||
const users = new Users(db);
|
||||
const sessions = new Sessions(db);
|
||||
const settings = new SettingsStore(db);
|
||||
const roles = new Roles(db, config.superadminDiscordIds);
|
||||
const audit = new Audit(db);
|
||||
const startedAt = Date.now();
|
||||
const gateway = new Gateway({ log, onClose: (id) => users.touch(id) });
|
||||
|
||||
const removeGuest = (id: string) => {
|
||||
gateway.disconnectUser(id);
|
||||
if (users.deleteGuest(id)) log('info', 'guest removed', { user: id });
|
||||
};
|
||||
/** Guests who closed the site and stayed away a day are deleted. */
|
||||
const purgeIdleGuests = (now = Date.now()) => {
|
||||
for (const id of users.idleGuests(now - GUEST_IDLE_MS)) if (!gateway.isOnline(id)) removeGuest(id);
|
||||
};
|
||||
let ready = true;
|
||||
|
||||
const ipOf = (req: Request) =>
|
||||
(config.trustProxy ? req.headers.get('x-forwarded-for')?.split(',').pop()?.trim() : undefined) || server?.requestIP(req)?.address || 'unknown';
|
||||
|
||||
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
|
||||
const serveStatic = !!staticDir && existsSync(staticDir);
|
||||
const app = createHttpApp({
|
||||
config,
|
||||
users,
|
||||
sessions,
|
||||
roles,
|
||||
settings,
|
||||
ipOf,
|
||||
discordExchange: opts.discordExchange,
|
||||
health: () => ({ ok: ready, connections: gateway.connectionCount }),
|
||||
removeGuest,
|
||||
admin: {
|
||||
audit,
|
||||
disconnectUser: (id) => gateway.disconnectUser(id),
|
||||
stats: () => ({
|
||||
connections: gateway.connectionCount,
|
||||
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
|
||||
memoryMb: Math.round(process.memoryUsage().rss / 1048576),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const server: Server<WsData> = Bun.serve<WsData>({
|
||||
port: config.port,
|
||||
async fetch(req, srv) {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === '/ws') {
|
||||
const origin = req.headers.get('origin');
|
||||
if (!origin || !config.allowedOrigins.includes(origin)) return new Response('forbidden origin', { status: 403 });
|
||||
const token = (req.headers.get('cookie') ?? '')
|
||||
.split(';')
|
||||
.map((s) => s.trim())
|
||||
.find((s) => s.startsWith(`${SESSION_COOKIE}=`))
|
||||
?.slice(SESSION_COOKIE.length + 1);
|
||||
const userId = token ? sessions.resolve(decodeURIComponent(token)) : null;
|
||||
if (!userId) return new Response('unauthorized', { status: 401 });
|
||||
return gateway.upgrade(req, srv, userId);
|
||||
}
|
||||
if (url.pathname.startsWith('/api/') || url.pathname === '/healthz') return app.fetch(req);
|
||||
if (serveStatic) return serveFile(staticDir!, url.pathname);
|
||||
return new Response('not found', { status: 404 });
|
||||
},
|
||||
websocket: {
|
||||
...gateway.handlers,
|
||||
idleTimeout: 40,
|
||||
sendPings: true,
|
||||
// Chat must never wait (docs/12): small JSON frames, so no compression step on the hot path.
|
||||
perMessageDeflate: false,
|
||||
maxPayloadLength: 64 * 1024,
|
||||
},
|
||||
});
|
||||
|
||||
const sweeper = setInterval(() => {
|
||||
try {
|
||||
sessions.purgeExpired();
|
||||
purgeIdleGuests();
|
||||
} catch (err) {
|
||||
log('error', 'sweep failed', { err: String(err) });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const stop = async () => {
|
||||
ready = false;
|
||||
clearInterval(sweeper);
|
||||
gateway.shutdown();
|
||||
await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]);
|
||||
db.close();
|
||||
};
|
||||
|
||||
return { server, stop, users, sessions, db, gateway, settings, roles, purgeIdleGuests };
|
||||
}
|
||||
|
||||
async function serveFile(root: string, pathname: string): Promise<Response> {
|
||||
const safe = normalize(decodeURIComponent(pathname)).replace(/^(\.\.[/\\])+/, '');
|
||||
const candidate = join(root, safe);
|
||||
if (candidate.startsWith(root) && !candidate.endsWith('/')) {
|
||||
const f = Bun.file(candidate);
|
||||
if (await f.exists()) {
|
||||
const immutable = safe.startsWith('/assets/');
|
||||
return new Response(f, { headers: { 'Cache-Control': immutable ? 'public, max-age=31536000, immutable' : 'no-cache' } });
|
||||
}
|
||||
}
|
||||
// SPA fallback.
|
||||
return new Response(Bun.file(join(root, 'index.html')), { headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'text/html; charset=utf-8' } });
|
||||
}
|
||||
120
apps/server/src/test-utils.ts
Normal file
120
apps/server/src/test-utils.ts
Normal file
@@ -0,0 +1,120 @@
|
||||
/** Helpers for integration tests: boot a real server, act as browser clients (from joke-app). */
|
||||
import { mkdtempSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import type { ServerMessage } from '@mq/shared';
|
||||
import { loadConfig } from './config';
|
||||
import { startServer, type StartOptions } from './server';
|
||||
|
||||
export const ORIGIN = 'http://localhost:5173';
|
||||
/** Made-up superadmin Discord IDs for tests (the real ones live only in deploy/.env). */
|
||||
export const TEST_SUPERADMINS = ['900000000000000001', '900000000000000002'] as const;
|
||||
|
||||
export function tempDbPath(): string {
|
||||
const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), 'mq-test-'));
|
||||
return join(dir, 'app.db');
|
||||
}
|
||||
|
||||
export function boot(extra: Partial<StartOptions> = {}, env: Record<string, string> = {}) {
|
||||
const config = loadConfig({ PORT: '0', DB_PATH: tempDbPath(), PUBLIC_ORIGIN: ORIGIN, SUPERADMIN_DISCORD_IDS: TEST_SUPERADMINS.join(','), ...env });
|
||||
const app = startServer({ config, log: () => {}, staticDir: null, stopWaitMs: 50, ...extra });
|
||||
const base = `http://localhost:${app.server.port}`;
|
||||
return { ...app, base, config };
|
||||
}
|
||||
|
||||
export async function api(base: string, path: string, init: RequestInit & { cookie?: string; origin?: string | null } = {}) {
|
||||
const headers = new Headers(init.headers);
|
||||
if (init.origin !== null) headers.set('origin', init.origin ?? ORIGIN);
|
||||
if (init.cookie) headers.set('cookie', init.cookie);
|
||||
if (init.body && !headers.has('content-type')) headers.set('content-type', 'application/json');
|
||||
const res = await fetch(base + path, { ...init, headers, redirect: 'manual' });
|
||||
const setCookie = res.headers.getSetCookie();
|
||||
let body: any = null;
|
||||
try {
|
||||
body = await res.clone().json();
|
||||
} catch {
|
||||
body = await res.text();
|
||||
}
|
||||
return { res, body, setCookie };
|
||||
}
|
||||
|
||||
/** `name=value` of a Set-Cookie list. */
|
||||
export function cookieOf(setCookie: string[], name: string): string | undefined {
|
||||
return setCookie.map((c) => c.split(';')[0]!).find((c) => c.startsWith(`${name}=`));
|
||||
}
|
||||
|
||||
export async function guest(base: string, nickname: string): Promise<{ cookie: string; id: string }> {
|
||||
const r = await api(base, '/api/auth/guest', { method: 'POST', body: JSON.stringify({ nickname }) });
|
||||
if (r.res.status !== 200) throw new Error(`guest failed: ${JSON.stringify(r.body)}`);
|
||||
return { cookie: cookieOf(r.setCookie, 'sid')!, id: r.body.me.id };
|
||||
}
|
||||
|
||||
/** Full Discord login through /start → (fake Discord) → /callback. `discordId` is passed as the code. */
|
||||
export async function discordLogin(base: string, discordId: string, cookie?: string) {
|
||||
const start = await api(base, '/api/auth/discord/start?next=/admin', { cookie });
|
||||
const loc = new URL(start.res.headers.get('location')!);
|
||||
const oauth = cookieOf(start.setCookie, 'oauth')!;
|
||||
const cb = await api(base, `/api/auth/discord/callback?code=${discordId}&state=${loc.searchParams.get('state')}`, {
|
||||
cookie: [cookie, oauth].filter(Boolean).join('; '),
|
||||
});
|
||||
return { start, loc, cb, cookie: cookieOf(cb.setCookie, 'sid') };
|
||||
}
|
||||
|
||||
export class Client {
|
||||
ws!: WebSocket;
|
||||
messages: ServerMessage[] = [];
|
||||
private waiters: { pred: (m: ServerMessage) => boolean; resolve: (m: ServerMessage) => void }[] = [];
|
||||
closed: { code: number; reason: string } | null = null;
|
||||
|
||||
constructor(
|
||||
private base: string,
|
||||
public cookie: string,
|
||||
) {}
|
||||
|
||||
async connect(): Promise<this> {
|
||||
const url = this.base.replace('http', 'ws') + '/ws';
|
||||
// Bun's WebSocket client accepts custom headers.
|
||||
this.ws = new WebSocket(url, { headers: { cookie: this.cookie, origin: ORIGIN } } as unknown as string[]);
|
||||
this.ws.onmessage = (e) => {
|
||||
const m = JSON.parse(String(e.data)) as ServerMessage;
|
||||
this.messages.push(m);
|
||||
for (const w of [...this.waiters]) {
|
||||
if (w.pred(m)) {
|
||||
this.waiters.splice(this.waiters.indexOf(w), 1);
|
||||
w.resolve(m);
|
||||
}
|
||||
}
|
||||
};
|
||||
this.ws.onclose = (e) => {
|
||||
this.closed = { code: e.code, reason: e.reason };
|
||||
};
|
||||
await this.waitFor((m) => m.t === 'welcome');
|
||||
return this;
|
||||
}
|
||||
|
||||
send(m: unknown): void {
|
||||
this.ws.send(JSON.stringify(m));
|
||||
}
|
||||
|
||||
waitFor(pred: (m: ServerMessage) => boolean, timeout = 3000): Promise<ServerMessage> {
|
||||
const existing = this.messages.find(pred);
|
||||
if (existing) return Promise.resolve(existing);
|
||||
return new Promise((resolve, reject) => {
|
||||
const w = { pred, resolve };
|
||||
this.waiters.push(w);
|
||||
setTimeout(() => {
|
||||
const i = this.waiters.indexOf(w);
|
||||
if (i >= 0) {
|
||||
this.waiters.splice(i, 1);
|
||||
reject(new Error(`timeout waiting; last: ${JSON.stringify(this.messages.slice(-3))}`));
|
||||
}
|
||||
}, timeout);
|
||||
});
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.ws.close();
|
||||
}
|
||||
}
|
||||
|
||||
export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
39
apps/server/src/ws.test.ts
Normal file
39
apps/server/src/ws.test.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { afterEach, expect, test } from 'bun:test';
|
||||
import { Client, ORIGIN, boot, guest } from './test-utils';
|
||||
|
||||
let s: ReturnType<typeof boot>;
|
||||
afterEach(async () => s && (await s.stop()));
|
||||
|
||||
test('websocket needs a session and our origin', async () => {
|
||||
s = boot();
|
||||
const ws = s.base.replace('http', 'ws') + '/ws';
|
||||
expect((await fetch(s.base + '/ws', { headers: { origin: ORIGIN, upgrade: 'websocket' } })).status).toBe(401);
|
||||
const g = await guest(s.base, '손님');
|
||||
expect((await fetch(s.base + '/ws', { headers: { origin: 'https://evil.example', cookie: g.cookie } })).status).toBe(403);
|
||||
void ws;
|
||||
});
|
||||
|
||||
test('welcome then clock-sync ping/pong answered immediately', async () => {
|
||||
s = boot();
|
||||
const g = await guest(s.base, '손님');
|
||||
const c = await new Client(s.base, g.cookie).connect();
|
||||
expect(c.messages[0]).toMatchObject({ t: 'welcome', userId: g.id });
|
||||
const sent = Date.now();
|
||||
c.send({ t: 'ping', c: sent });
|
||||
const pong = (await c.waitFor((m) => m.t === 'pong')) as { t: 'pong'; c: number; s: number };
|
||||
expect(pong.c).toBe(sent);
|
||||
expect(Math.abs(pong.s - Date.now())).toBeLessThan(1000);
|
||||
expect(s.gateway.isOnline(g.id)).toBe(true);
|
||||
c.send({ t: 'nope' });
|
||||
expect(await c.waitFor((m) => m.t === 'error')).toMatchObject({ t: 'error' });
|
||||
c.close();
|
||||
});
|
||||
|
||||
test('a banned user is disconnected', async () => {
|
||||
s = boot();
|
||||
const g = await guest(s.base, '손님');
|
||||
const c = await new Client(s.base, g.cookie).connect();
|
||||
s.gateway.disconnectUser(g.id);
|
||||
for (let i = 0; i < 50 && !c.closed; i++) await Bun.sleep(10);
|
||||
expect(c.closed?.code).toBe(4001);
|
||||
});
|
||||
86
apps/server/src/ws/gateway.ts
Normal file
86
apps/server/src/ws/gateway.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* WebSocket gateway (docs/01 실시간 메시지). Stage 1: authenticated connection, welcome, clock-sync ping.
|
||||
* Messages are handled synchronously on arrival: no queue and no batching (docs/12 채팅 "무조건 실시간").
|
||||
*/
|
||||
import type { Server, ServerWebSocket } from 'bun';
|
||||
import { ClientMessage, MAX_CLIENT_MESSAGE_BYTES, PROTOCOL, type ServerMessage } from '@mq/shared';
|
||||
import type { LogFn } from '../server';
|
||||
|
||||
export interface WsData {
|
||||
userId: string;
|
||||
connId: number;
|
||||
}
|
||||
|
||||
export interface GatewayDeps {
|
||||
log: LogFn;
|
||||
onClose?: (userId: string) => void;
|
||||
}
|
||||
|
||||
export class Gateway {
|
||||
private conns = new Map<string, Set<ServerWebSocket<WsData>>>();
|
||||
private nextId = 1;
|
||||
|
||||
constructor(private d: GatewayDeps) {}
|
||||
|
||||
get connectionCount(): number {
|
||||
let n = 0;
|
||||
for (const s of this.conns.values()) n += s.size;
|
||||
return n;
|
||||
}
|
||||
|
||||
isOnline(userId: string): boolean {
|
||||
return (this.conns.get(userId)?.size ?? 0) > 0;
|
||||
}
|
||||
|
||||
upgrade(req: Request, srv: Server<WsData>, userId: string): Response | undefined {
|
||||
if (srv.upgrade(req, { data: { userId, connId: this.nextId++ } })) return undefined;
|
||||
return new Response('upgrade failed', { status: 400 });
|
||||
}
|
||||
|
||||
/** Banned / force-logged-out users: drop every socket. */
|
||||
disconnectUser(userId: string): void {
|
||||
for (const ws of this.conns.get(userId) ?? []) ws.close(4001, 'logged out');
|
||||
}
|
||||
|
||||
shutdown(): void {
|
||||
for (const set of this.conns.values()) for (const ws of set) ws.close(1001, 'server restart');
|
||||
}
|
||||
|
||||
private send(ws: ServerWebSocket<WsData>, m: ServerMessage): void {
|
||||
ws.send(JSON.stringify(m));
|
||||
}
|
||||
|
||||
readonly handlers = {
|
||||
open: (ws: ServerWebSocket<WsData>) => {
|
||||
const set = this.conns.get(ws.data.userId) ?? new Set();
|
||||
set.add(ws);
|
||||
this.conns.set(ws.data.userId, set);
|
||||
this.send(ws, { t: 'welcome', protocol: PROTOCOL, userId: ws.data.userId, serverNow: Date.now() });
|
||||
},
|
||||
message: (ws: ServerWebSocket<WsData>, raw: string | Buffer) => {
|
||||
const text = typeof raw === 'string' ? raw : raw.toString();
|
||||
if (text.length > MAX_CLIENT_MESSAGE_BYTES) return this.send(ws, { t: 'error', message: '메시지가 너무 길어요.' });
|
||||
let json: unknown;
|
||||
try {
|
||||
json = JSON.parse(text);
|
||||
} catch {
|
||||
return this.send(ws, { t: 'error', message: '잘못된 메시지예요.' });
|
||||
}
|
||||
const parsed = ClientMessage.safeParse(json);
|
||||
if (!parsed.success) return this.send(ws, { t: 'error', message: '잘못된 메시지예요.' });
|
||||
const m = parsed.data;
|
||||
switch (m.t) {
|
||||
case 'ping':
|
||||
return this.send(ws, { t: 'pong', c: m.c, s: Date.now() });
|
||||
}
|
||||
},
|
||||
close: (ws: ServerWebSocket<WsData>) => {
|
||||
const set = this.conns.get(ws.data.userId);
|
||||
set?.delete(ws);
|
||||
if (set && set.size === 0) {
|
||||
this.conns.delete(ws.data.userId);
|
||||
this.d.onClose?.(ws.data.userId);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
45
apps/server/src/ws/rate-limit.ts
Normal file
45
apps/server/src/ws/rate-limit.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/** Token bucket: chat flood guard when the admin turns it on (docs/12 채팅). */
|
||||
export class TokenBucket {
|
||||
private tokens: number;
|
||||
private last: number;
|
||||
constructor(
|
||||
private ratePerSec: number,
|
||||
private burst: number,
|
||||
now = Date.now(),
|
||||
) {
|
||||
this.tokens = burst;
|
||||
this.last = now;
|
||||
}
|
||||
|
||||
take(now = Date.now()): boolean {
|
||||
this.tokens = Math.min(this.burst, this.tokens + ((now - this.last) / 1000) * this.ratePerSec);
|
||||
this.last = now;
|
||||
if (this.tokens < 1) return false;
|
||||
this.tokens -= 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Fixed-window counter per key (HTTP endpoints). */
|
||||
export class WindowLimiter {
|
||||
private hits = new Map<string, { start: number; n: number }>();
|
||||
constructor(
|
||||
private limit: number,
|
||||
private windowMs: number,
|
||||
) {}
|
||||
|
||||
allow(key: string, now = Date.now()): boolean {
|
||||
const h = this.hits.get(key);
|
||||
if (!h || now - h.start >= this.windowMs) {
|
||||
this.hits.set(key, { start: now, n: 1 });
|
||||
if (this.hits.size > 50_000) this.prune(now);
|
||||
return true;
|
||||
}
|
||||
h.n++;
|
||||
return h.n <= this.limit;
|
||||
}
|
||||
|
||||
private prune(now: number): void {
|
||||
for (const [k, v] of this.hits) if (now - v.start >= this.windowMs) this.hits.delete(k);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user