import { test, expect, type Page } from '@playwright/test'; const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001'; const confirmation = 'If this email belongs to an eligible account, a sign-in link has been sent.'; const invalidLink = 'This sign-in link is invalid or expired. Please request a new link.'; function mockSession(email: string) { const user = { id: '11111111-1111-4111-8111-111111111111', aud: 'authenticated', role: 'authenticated', email, app_metadata: {}, user_metadata: {}, created_at: '2026-01-01T00:00:00Z', }; const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url'); return { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test-signature`, refresh_token: 'mock-refresh-token', token_type: 'bearer', expires_in: 3600 }; } async function mockApi(page: Page, email = 'admin@appe.at', isAdmin = false, password = 'personal-password') { const session = mockSession(email); const calls = { users: 0, exchanges: 0, logouts: 0, passwords: 0 }; await page.route('**/auth/v1/**', async (route) => { const url = new URL(route.request().url()); if (url.pathname.endsWith('/user')) { calls.users++; await route.fulfill({ json: session.user }); } else if (url.pathname.endsWith('/token')) { if (url.searchParams.get('grant_type') === 'pkce') calls.exchanges++; if (url.searchParams.get('grant_type') === 'password') calls.passwords++; await route.fulfill({ json: session }); } else if (url.pathname.endsWith('/logout')) { calls.logouts++; await route.fulfill({ status: 204 }); } else { await route.fulfill({ json: {} }); } }); await page.route('**/rest/v1/**', async (route) => { const url = new URL(route.request().url()); await route.fulfill({ json: url.pathname.endsWith('/contacts') ? { email, full_name: 'Test Admin', is_admin: isAdmin, password } : [] }); }); return { session, calls }; } test.describe('Admin magic links', () => { test('pending send locks the recipient and failed resend clears stale confirmation', async ({ page }) => { await mockApi(page); await page.clock.install(); let requestCount = 0; let releaseSend!: () => void; const pendingSend = new Promise((resolve) => { releaseSend = resolve; }); await page.route('**/auth/v1/otp**', async (route) => { requestCount++; if (requestCount === 1) { await pendingSend; await route.fulfill({ json: {} }); } else { await route.fulfill({ status: 500, json: { msg: 'SMTP unavailable' } }); } }); await page.goto(adminUrl); await page.getByLabel('Email', { exact: true }).fill('admin@appe.at'); await page.getByRole('button', { name: 'Send magic link', exact: true }).click(); await expect(page.getByLabel('Email', { exact: true })).toBeDisabled(); await expect(page.getByRole('button', { name: 'Sending...', exact: true })).toBeDisabled(); releaseSend(); await expect(page.locator('.login-form [role="status"]')).toHaveText(confirmation); await expect(page.getByLabel('Email', { exact: true })).toBeEnabled(); await page.clock.runFor(60_000); await page.getByRole('button', { name: 'Resend magic link', exact: true }).click(); await expect(page.getByRole('alert')).toHaveText('Unable to send a sign-in link right now. Please try again later.'); await expect(page.locator('.login-form [role="status"]')).toHaveCount(0); await expect(page.getByRole('button', { name: 'Send magic link', exact: true })).toBeEnabled(); await expect(page.getByText('SMTP unavailable')).toHaveCount(0); expect(requestCount).toBe(2); }); test('email-only sending, private confirmation, cooldown and resend', async ({ page }) => { await mockApi(page); await page.clock.install(); let requestCount = 0; await page.route('**/auth/v1/otp**', async (route) => { requestCount++; expect(route.request().postDataJSON()).toMatchObject({ email: 'admin@appe.at', create_user: false }); expect(new URL(route.request().url()).searchParams.get('redirect_to')).toBe(`${adminUrl}/auth/callback`); await route.fulfill({ json: {} }); }); await page.goto(adminUrl); await expect(page.getByLabel('Password', { exact: true })).toHaveCount(0); await page.getByLabel('Email', { exact: true }).fill('admin@appe.at'); await page.getByRole('button', { name: 'Send magic link', exact: true }).click(); await expect(page.locator('.login-form [role="status"]')).toHaveText(confirmation); await expect(page.getByRole('button', { name: 'Resend in 60s' })).toBeDisabled(); await page.clock.runFor(60_000); await page.getByRole('button', { name: 'Resend magic link', exact: true }).click(); await expect(page.getByRole('button', { name: 'Resend in 60s' })).toBeDisabled(); expect(requestCount).toBe(2); }); for (const status of [400, 422, 429, 500]) { test(`OTP status ${status} does not reveal account existence`, async ({ page }) => { await mockApi(page); await page.route('**/auth/v1/otp**', (route) => route.fulfill({ status, json: { msg: 'User not found', code: 'test_error' } })); await page.goto(adminUrl); await page.getByLabel('Email', { exact: true }).fill('unknown@example.org'); await page.getByRole('button', { name: 'Send magic link', exact: true }).click(); if (status < 429) await expect(page.locator('.login-form [role="status"]')).toHaveText(confirmation); else await expect(page.getByRole('alert')).toHaveText('Unable to send a sign-in link right now. Please try again later.'); await expect(page.getByText('User not found')).toHaveCount(0); }); } for (const account of [ { email: 'admin@appe.at', isAdmin: false, admitted: true }, { email: 'admin@example.org', isAdmin: true, admitted: true }, { email: 'attendee@example.org', isAdmin: false, admitted: false }, ]) { test(`implicit callback applies admin gate for ${account.email}`, async ({ page }) => { const { session, calls } = await mockApi(page, account.email, account.isAdmin); await page.goto(`${adminUrl}/auth/callback?next=https://example.org#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`); await expect(page).toHaveURL(`${adminUrl}/`); if (account.admitted) { await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible(); await page.getByRole('button', { name: 'Sign out', exact: true }).click(); await expect(page.getByRole('heading', { name: 'APPE Admin' })).toBeVisible(); } else { await expect(page.getByRole('alert')).toHaveText('This account is not an admin.'); await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toHaveCount(0); expect(calls.logouts).toBe(1); expect(await page.evaluate(() => Object.keys(localStorage).filter((key) => key.endsWith('-auth-token')))).toEqual([]); } expect(calls.users).toBe(1); }); } test('code callback is exchanged once under StrictMode', async ({ page }) => { const { calls } = await mockApi(page); await page.goto(`${adminUrl}/auth/callback?code=mock-code&redirect_to=https://example.org`); await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible(); await expect(page).toHaveURL(`${adminUrl}/`); expect(calls.exchanges).toBe(1); }); for (const suffix of [ '#error=access_denied&error_code=otp_expired&error_description=Sensitive+server+detail', '?error=access_denied&error_code=otp_expired', '#access_token=incomplete', '', ]) { test(`invalid callback is scrubbed and recoverable: ${suffix || 'empty'}`, async ({ page }) => { const { calls } = await mockApi(page); await page.goto(`${adminUrl}/auth/callback${suffix}`); await expect(page).toHaveURL(`${adminUrl}/`); await expect(page.getByRole('alert')).toHaveText(invalidLink); await expect(page.getByRole('button', { name: 'Send magic link', exact: true })).toBeVisible(); expect(calls.users).toBe(0); expect(calls.exchanges).toBe(0); await expect(page.getByText('Sensitive server detail')).toHaveCount(0); }); } test('login has no password field or sign-in method selector', async ({ page }) => { const { calls } = await mockApi(page); await page.goto(adminUrl); await expect(page.getByLabel('Email', { exact: true })).toBeVisible(); await expect(page.locator('input[type="password"]')).toHaveCount(0); await expect(page.getByRole('group', { name: 'Sign-in method' })).toHaveCount(0); await expect(page.getByRole('button', { name: 'Password', exact: true })).toHaveCount(0); await expect(page.getByRole('button', { name: 'Sign in', exact: true })).toHaveCount(0); await expect(page.getByRole('button', { name: 'Send magic link', exact: true })).toBeVisible(); expect(calls.passwords).toBe(0); }); test('expired callback can recover by requesting a new magic link', async ({ page }) => { const { calls } = await mockApi(page); let requestCount = 0; await page.route('**/auth/v1/otp**', async (route) => { requestCount++; expect(route.request().postDataJSON()).toMatchObject({ email: 'admin@appe.at', create_user: false }); await route.fulfill({ json: {} }); }); await page.goto(`${adminUrl}/auth/callback#error=access_denied&error_code=otp_expired`); await expect(page.getByRole('alert')).toHaveText(invalidLink); await page.getByLabel('Email', { exact: true }).fill('admin@appe.at'); await page.getByRole('button', { name: 'Send magic link', exact: true }).click(); await expect(page.getByRole('alert')).toHaveCount(0); await expect(page.locator('.login-form [role="status"]')).toHaveText(confirmation); await expect(page.getByRole('button', { name: 'Resend in 60s' })).toBeDisabled(); expect(requestCount).toBe(1); expect(calls.passwords).toBe(0); await expect(page).toHaveURL(`${adminUrl}/`); }); test('default-password contact has no change-password prompt on callback or session restore', async ({ page }) => { const { session, calls } = await mockApi(page, 'admin@appe.at', false, 'appe-admin-2026'); await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`); await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible(); await expect(page.getByRole('dialog')).toHaveCount(0); await expect(page.getByText('Change your password', { exact: true })).toHaveCount(0); await expect(page.locator('input[type="password"]')).toHaveCount(0); await page.reload(); await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible(); await expect(page.getByRole('dialog')).toHaveCount(0); await expect(page.getByText('Change your password', { exact: true })).toHaveCount(0); await expect(page.locator('input[type="password"]')).toHaveCount(0); expect(calls.passwords).toBe(0); }); test('rejected code exchange clears a previously stored local session', async ({ page }) => { const { session } = await mockApi(page); await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`); await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible(); await page.route('**/auth/v1/token**', (route) => route.fulfill({ status: 400, json: { error: 'invalid_grant', error_description: 'Sensitive exchange detail' }, })); await page.goto(`${adminUrl}/auth/callback?code=expired-code`); await expect(page.getByRole('alert')).toHaveText(invalidLink); await expect(page).toHaveURL(`${adminUrl}/`); await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toHaveCount(0); expect(await page.evaluate(() => Object.keys(localStorage).filter((key) => key.endsWith('-auth-token')))).toEqual([]); await expect(page.getByText('Sensitive exchange detail')).toHaveCount(0); }); });