Files
music_quiz/e2e/login.e2e.ts
EJClaw 391bbe69e5 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>
2026-10-18 19:44:47 +09:00

185 lines
10 KiB
TypeScript

/**
* Stage 1 E2E (docs/10 1단계): guest start, Discord login (real /start → consent URL checked → mocked callback),
* both superadmins reach /admin, a plain member is refused, admin edits site settings and adds an admin.
* Run: bun run e2e (builds apps/web/dist, needs /usr/bin/google-chrome)
*/
import { chromium, type BrowserContext } from 'playwright-core';
import { mkdirSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
const PORT = Number(process.env.E2E_PORT ?? 4618);
const ORIGIN = `http://localhost:${PORT}`;
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
mkdirSync(SHOTS, { recursive: true });
/** Made-up IDs; the real superadmin IDs live only in deploy/.env. */
const SUPERS = ['900000000000000001', '900000000000000002'];
const PLAIN = '900000000000000555';
const CLIENT_ID = '1561284577564037140';
const config = loadConfig({
PORT: String(PORT),
DB_PATH: join(mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'mq-e2e-')), 'app.db'),
PUBLIC_ORIGIN: ORIGIN,
SUPERADMIN_DISCORD_IDS: SUPERS.join(','),
DISCORD_CLIENT_ID: CLIENT_ID,
DISCORD_CLIENT_SECRET: 'e2e',
});
const app = startServer({
config,
log: () => {},
staticDir: join(import.meta.dir, '../apps/web/dist'),
discordExchange: async (code) => ({ id: code, username: `u${code.slice(-3)}`, global_name: code === SUPERS[0] ? '사금향' : `친구${code.slice(-3)}`, avatar: null }),
});
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
const step = async (name: string, fn: () => Promise<void>) => {
const t0 = performance.now();
try {
await fn();
console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`);
} catch (e) {
console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`);
throw e;
}
};
const expect = (ok: unknown, msg: string) => {
if (!ok) throw new Error(msg);
};
/** Fake Discord: let our real /start run (state cookie + consent URL), check the URL, bounce to our callback. */
async function fakeDiscord(ctx: BrowserContext, discordId: string, seen: { consent?: URL }) {
await ctx.route(`${ORIGIN}/api/auth/discord/start*`, async (route) => {
const res = await fetch(route.request().url(), { redirect: 'manual', headers: { cookie: (await route.request().headerValue('cookie')) ?? '' } });
const consent = new URL(res.headers.get('location')!);
seen.consent = consent;
const back = `${ORIGIN}/api/auth/discord/callback?code=${discordId}&state=${consent.searchParams.get('state')}`;
await route.fulfill({
status: 200,
headers: { 'content-type': 'text/html', 'set-cookie': res.headers.get('set-cookie') ?? '' },
body: `<script>location.replace(${JSON.stringify(back)})</script>`,
});
});
}
let failed = false;
try {
await step('첫 화면: 로고·소개·디스코드 로그인·게스트 시작, 검색엔진 차단', async () => {
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR', colorScheme: 'light' });
const p = await ctx.newPage();
const errors: string[] = [];
p.on('pageerror', (e) => errors.push(e.message));
await p.goto(ORIGIN + '/');
await p.getByRole('heading', { name: /누가 먼저 맞히나/ }).waitFor();
expect(await p.locator('.site-logo img').evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth > 0), '로고 이미지가 안 보여요');
expect(await p.getByRole('link', { name: '디스코드로 로그인' }).isVisible(), '디스코드 버튼 없음');
expect(await p.getByRole('button', { name: '게스트로 시작' }).isVisible(), '게스트 버튼 없음');
expect((await p.locator('meta[name=robots]').getAttribute('content'))?.includes('noindex'), 'noindex 없음');
expect((await (await fetch(ORIGIN + '/robots.txt')).text()).includes('Disallow: /'), 'robots.txt');
expect((await fetch(ORIGIN + '/favicon.ico')).ok, 'favicon');
await p.screenshot({ path: join(SHOTS, 'stage1-home.png') });
await ctx.close();
expect(errors.length === 0, errors.join(', '));
});
await step('게스트로 시작 → 헤더에 닉네임·게스트, 관리자 페이지는 디스코드 로그인 안내', async () => {
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, locale: 'ko-KR' });
const p = await ctx.newPage();
await p.goto(ORIGIN + '/');
await p.getByLabel('게스트 닉네임 (2~12자)').fill('흥 많은 기타');
await p.getByRole('button', { name: '게스트로 시작' }).click();
await p.getByRole('button', { name: '내 계정: 흥 많은 기타' }).waitFor();
expect(await p.getByText('게스트', { exact: true }).first().isVisible(), '게스트 표시');
await p.goto(ORIGIN + '/admin');
await p.getByText('관리자는 디스코드로 로그인해야').waitFor();
// 로그아웃하면 게스트 계정은 지워짐
await p.goto(ORIGIN + '/');
await p.getByRole('button', { name: '내 계정: 흥 많은 기타' }).click();
await p.getByRole('menuitem', { name: /로그아웃/ }).click();
await p.getByRole('dialog').getByRole('button', { name: '로그아웃' }).click();
await p.getByRole('button', { name: '게스트로 시작' }).waitFor();
await ctx.close();
});
for (const [i, id] of SUPERS.entries()) {
await step(`슈퍼어드민 ${i + 1}: 디스코드 로그인(음악퀴즈 앱 동의 화면 주소 확인) → 관리자 페이지`, async () => {
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' });
const seen: { consent?: URL } = {};
await fakeDiscord(ctx, id, seen);
const p = await ctx.newPage();
await p.goto(ORIGIN + '/');
await p.getByRole('link', { name: '디스코드로 로그인' }).click();
await p.getByRole('button', { name: /내 계정:/ }).waitFor();
const c = seen.consent!;
expect(c.origin + c.pathname === 'https://discord.com/oauth2/authorize', `consent ${c}`);
expect(c.searchParams.get('client_id') === CLIENT_ID, 'client_id');
expect(c.searchParams.get('scope') === 'identify', 'scope');
expect(c.searchParams.get('redirect_uri') === `${ORIGIN}/api/auth/discord/callback`, 'redirect_uri');
await p.getByRole('link', { name: '관리자' }).click();
await p.getByRole('heading', { name: '대시보드' }).waitFor();
await p.getByText('슈퍼어드민', { exact: true }).first().waitFor();
if (i === 0) {
const side = p.getByRole('navigation', { name: '관리자 메뉴' });
// 사이트 설정: 도배 방지 기본 꺼짐 → 켜고 저장
await side.getByRole('link', { name: /사이트/ }).click();
const guard = p.getByLabel('도배 방지 켜기 (기본: 꺼짐)');
expect(!(await guard.isChecked()), '도배 방지 기본값이 꺼짐이 아님');
await guard.check();
await p.getByLabel('공지 (첫 화면 위에 보여요)').fill('1단계 시험 중');
await p.getByRole('button', { name: '저장' }).click();
await p.getByText('저장했어요.').waitFor();
expect(app.settings.getSite().chatFloodGuard === true, '저장 안 됨');
await p.getByRole('note').getByText('1단계 시험 중').waitFor();
// 관리자 추가 (아직 로그인 안 한 사람)
await side.getByRole('link', { name: /관리자$/ }).click();
await p.getByPlaceholder('디스코드 ID (숫자 17~20자리)').fill('900000000000000777');
await p.getByRole('button', { name: '추가' }).click();
await p.getByText('관리자를 추가했어요.').waitFor();
await p.getByText('아직 로그인 안 함').first().waitFor();
await side.getByRole('link', { name: /사용자/ }).click();
await p.getByRole('cell', { name: '사금향' }).waitFor();
await side.getByRole('link', { name: /기록/ }).click();
await p.getByRole('cell', { name: 'admin.add' }).waitFor();
await side.getByRole('link', { name: /대시보드/ }).click();
await p.getByRole('heading', { name: '대시보드' }).waitFor();
await p.screenshot({ path: join(SHOTS, 'stage1-admin.png') });
}
await ctx.close();
});
}
await step('일반 디스코드 회원: 관리자 메뉴 없음, /admin 은 권한 없음', async () => {
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, locale: 'ko-KR', colorScheme: 'dark' });
await fakeDiscord(ctx, PLAIN, {});
const p = await ctx.newPage();
await p.goto(ORIGIN + '/login');
await p.getByRole('link', { name: '디스코드로 로그인' }).click();
await p.getByRole('button', { name: /내 계정: 친구555/ }).waitFor();
expect((await p.getByRole('link', { name: '관리자' }).count()) === 0, '관리자 메뉴가 보임');
await p.screenshot({ path: join(SHOTS, 'stage1-home-dark-member.png') });
await p.goto(ORIGIN + '/admin');
await p.getByRole('heading', { name: '권한이 없어요' }).waitFor();
expect((await p.evaluate(() => fetch('/api/admin/me').then((r) => r.status))) === 403, 'API 403 아님');
await ctx.close();
});
await step('휴대폰 화면(390px): 첫 화면이 가로로 넘치지 않음', async () => {
const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, locale: 'ko-KR', isMobile: true, hasTouch: true });
const p = await ctx.newPage();
await p.goto(ORIGIN + '/');
await p.getByRole('button', { name: '게스트로 시작' }).waitFor();
const overflow = await p.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
expect(overflow <= 0, `가로 넘침 ${overflow}px`);
await p.screenshot({ path: join(SHOTS, 'stage1-mobile.png'), fullPage: true });
await ctx.close();
});
} catch {
failed = true;
} finally {
await browser.close();
await app.stop();
}
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
process.exit(failed ? 1 : 0);