import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; import { createApp } from '../src/app.js'; import { bootstrapAdmin } from '../src/auth/bootstrap.js'; import { loadConfig } from '../src/config.js'; import { openAppDatabase } from '../src/db.js'; import { devEnv } from './env.js'; const NOW = '2026-10-14T18:00:00.000Z'; const ORIGIN = 'http://127.0.0.1:3000'; const dirs: string[] = []; const databases: { close: () => void }[] = []; afterEach(() => { for (const database of databases.splice(0)) database.close(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); describe('administrators', () => { it('asks a signed-out visitor to sign in', async () => { const { app } = await buildApp(); const page = await app.request('/admin/admins'); expect(page.status).toBe(303); expect(page.headers.get('location')).toBe('/login'); const posted = await app.request('/admin/admins', { method: 'POST', headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ name: 'Ada Lovelace', email: 'ada@example.invalid' }), }); expect(posted.status).toBe(303); expect(posted.headers.get('location')).toBe('/login'); }); it('lists the first administrator and adds another who can sign in', async () => { const { app, db } = await buildApp(); const cookie = await signIn(app, db, 'coordinator@example.invalid'); const home = await app.request('/admin', { headers: { cookie } }); expect(await home.text()).toContain('href="/admin/admins"'); const first = await app.request('/admin/admins', { headers: { cookie } }); const firstHtml = await first.text(); expect(first.status).toBe(200); expect(firstHtml).toContain('Administrator'); expect(firstHtml).toContain('coordinator@example.invalid'); expect(firstHtml).toContain('>You'); expect(firstHtml).toContain('This is the only administrator.'); expect(firstHtml).not.toContain('Remove this administrator'); const rejected = await postAdmin(app, cookie, { name: '', email: 'not-an-email' }); expect(rejected.status).toBe(400); const rejectedHtml = await rejected.text(); expect(rejectedHtml).toContain('Enter a name.'); expect(rejectedHtml).toContain('Enter an email address.'); expect(count(db, `SELECT COUNT(*) AS n FROM coordinators`)).toBe(1); const broken = await postAdmin(app, cookie, { name: 'Ada\nLovelace', email: 'ada@example.invalid' }); expect(broken.status).toBe(400); expect(await broken.text()).toContain('Enter a name without line breaks.'); const stale = await app.request('/admin/admins', { method: 'POST', headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie }, body: new URLSearchParams({ csrf: 'wrong', name: 'Ada Lovelace', email: 'ada@example.invalid' }), }); expect(stale.status).toBe(403); const saved = await postAdmin(app, cookie, { name: 'Ada