import { test, expect } from '@playwright/test'; import { randomUUID } from 'node:crypto'; import { APP_URL, SUPABASE_URL, ANON_KEY, SERVICE_ROLE_KEY } from '../src/helpers/config'; import { psql, sqlQuote } from '../src/helpers/db'; import { login } from '../src/helpers/auth'; test('real leaderboard updates scores and ranks without rewarding staff or admins', async ({ page }) => { test.skip(new URL(APP_URL).hostname !== 'localhost' && new URL(APP_URL).hostname !== '127.0.0.1', 'Disposable fixtures are local-only'); const suffix = randomUUID(); const emails = ['player', 'peer', 'third', 'fourth', 'staff', 'admin'].map(role => `board-${role}-${suffix}@example.test`); const password = randomUUID(); const userIds: string[] = []; const eventId = psql('select id from public.events where is_active limit 1;'); expect(eventId).toMatch(/^[0-9a-f-]{36}$/); const initialPoints = Number(psql('select coalesce(max(points),0) from public.leaderboard;')) + 100; let subscribed = false; let updates = 0; const transportMessages: string[] = []; page.on('websocket', socket => { if (!socket.url().includes('/realtime/')) return; socket.on('framereceived', frame => { try { const decoded = JSON.parse(String(frame.payload)); const message = Array.isArray(decoded) ? { event: decoded[3], payload: decoded[4] } : decoded; transportMessages.push(JSON.stringify({ event: message.event, status: message.payload?.status, response: message.payload?.response, extension: message.payload?.extension, message: message.payload?.message })); if (message.event === 'phx_reply' && message.payload?.status === 'ok' && message.payload?.response?.postgres_changes?.length) subscribed = true; if (message.event === 'postgres_changes') updates++; } catch { /* Ignore non-JSON transport frames. */ } }); }); try { const created = await fetch(`${SUPABASE_URL}/auth/v1/admin/users`, { method: 'POST', headers: { apikey: SERVICE_ROLE_KEY, Authorization: `Bearer ${SERVICE_ROLE_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ email: emails[0], password, email_confirm: true }), }); expect(created.ok, 'Create disposable local Auth user').toBe(true); const user = await created.json(); userIds.push(user.id); psql(`begin; insert into public.contacts(email,full_name,is_admin) values ${emails.map((email, index) => `(${sqlQuote(email)},${sqlQuote(['Board Player','Board Peer','Board Third','Board Fourth','Board Staff','Board Admin'][index])},${index === 5})`).join(',')}; insert into public.registrations(event_id,contact_email,type,checked_in,points,qr_token) values ${emails.map((email, index) => `(${sqlQuote(eventId)},${sqlQuote(email)},${sqlQuote(index >= 4 ? 'staff' : 'attendee')},true,${initialPoints + (4 - index) * 10},${sqlQuote(index === 0 ? password : randomUUID())})`).join(',')}; commit;`); await login(page, APP_URL, { email: emails[0], qrToken: password, type: 'attendee', label: 'Disposable leaderboard player' }); await page.getByText('Leaderboard', { exact: true }).click(); await expect(page.locator('.podium .pname')).toHaveText(['Board', 'Board', 'Board']); await expect(page.getByText('Board Fourth', { exact: true })).toBeVisible(); await expect(page.getByText(/You.re ranked/)).toContainText('#1'); await expect.poll(() => subscribed, { timeout: 20_000, message: 'Realtime subscription acknowledged' }).toBe(true) .catch(error => { throw new Error(`${error.message}\n${transportMessages.join('\n')}`); }); psql(`begin; select set_config('request.jwt.claims', ${sqlQuote(JSON.stringify({ email: emails[5], role: 'authenticated' }))}, true); set local role authenticated; select public.adjust_points(${sqlQuote(emails[1])},100,'Leaderboard regression'); select public.adjust_points(${sqlQuote(emails[4])},9999,'Excluded staff regression'); select public.adjust_points(${sqlQuote(emails[5])},9999,'Excluded admin regression'); commit;`); await expect(page.locator('.podium .bar.b1')).toHaveText(String(initialPoints + 130)); await expect(page.getByText(/You.re ranked/)).toContainText('#2'); expect(updates).toBeGreaterThan(0); expect(psql(`select bool_and(points=0) from public.registrations where contact_email in (${emails.slice(4).map(sqlQuote).join(',')});`)).toBe('t'); expect(psql(`select count(*) from public.leaderboard where contact_email in (${emails.slice(4).map(sqlQuote).join(',')});`)).toBe('0'); expect(psql(`select count(*) from public.points_log where contact_email in (${emails.slice(4).map(sqlQuote).join(',')});`)).toBe('0'); const forbidden = await fetch(`${SUPABASE_URL}/rest/v1/rpc/_award_points`, { method: 'POST', headers: { apikey: ANON_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ p_event_id: eventId, p_contact_email: emails[0], p_delta: 9999, p_category: 'admin' }), }); expect(forbidden.ok, 'Anonymous API must not forge points').toBe(false); } finally { await page.close(); psql(`delete from public.contacts where email in (${emails.map(sqlQuote).join(',')});`); for (const userId of userIds) { const deleted = await fetch(`${SUPABASE_URL}/auth/v1/admin/users/${userId}`, { method: 'DELETE', headers: { apikey: SERVICE_ROLE_KEY, Authorization: `Bearer ${SERVICE_ROLE_KEY}` }, }); expect(deleted.ok, 'Delete disposable Auth user').toBe(true); } expect(psql(`select count(*) from public.contacts where email in (${emails.map(sqlQuote).join(',')});`)).toBe('0'); } });