feat: add volunteer shift signup app

Initial source, tests, migrations, and local Docker setup for the Hope Food Pantry volunteer scheduler.
This commit is contained in:
blake committed 2026-10-16 09:33:39 -05:00
commit f1a46e2ba7
129 files changed
+25290

No files matched your search

+982
View File
@@ -0,0 +1,982 @@
import { createHash } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { ACCEPTED } from '../src/admin-pages.js';
import { createApp } from '../src/app.js';
import { bootstrapAdmin } from '../src/auth/bootstrap.js';
import { recoverCoordinator } from '../src/auth/recover.js';
import { sessionClearCookie, sessionSetCookie } from '../src/auth/session.js';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { deliverDueMail } from '../src/mail/deliver.js';
import { renderMagicLink } from '../src/mail/templates.js';
import type { Mailer, OutboundMail } from '../src/mail/types.js';
import { LOGIN_IP_LIMIT } from '../src/rate-limit.js';
import { readManageSignup, reserveSignup } from '../src/signup.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const ORIGIN = 'http://127.0.0.1:3000';
const MAIL = {
baseUrl: ORIGIN,
basePath: '',
from: 'Hope Food Pantry <volunteer@example.invalid>',
replyTo: 'volunteer@example.invalid',
};
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('coordinator sign-in', () => {
it('uses the same response for an active coordinator and anyone else', async () => {
const active = await buildApp();
const inactive = await buildApp();
inactive.db.prepare('UPDATE coordinators SET active = 0').run();
const known = await postLogin(active.app, 'coordinator@example.invalid');
const stranger = await postLogin(active.app, 'missing@example.invalid');
const closed = await postLogin(inactive.app, 'coordinator@example.invalid');
const knownHtml = await known.text();
const strangerHtml = await stranger.text();
const closedHtml = await closed.text();
expect(known.status).toBe(200);
expect(stranger.status).toBe(200);
expect(closed.status).toBe(200);
expect(knownHtml).toBe(strangerHtml);
expect(knownHtml).toBe(closedHtml);
expect(knownHtml).toContain(ACCEPTED);
expect(knownHtml).not.toContain('not found');
expect(knownHtml).not.toContain('/login/link/');
expect(known.headers.get('set-cookie')).toBeNull();
expect(count(active.db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'magic_link'")).toBe(1);
expect(count(inactive.db, "SELECT COUNT(*) AS n FROM outbox")).toBe(0);
});
it('does not sign in when the link is only opened', async () => {
const { app, db } = await buildApp();
await postLogin(app, 'coordinator@example.invalid');
const token = magicToken(db);
const opened = await app.request(`/login/link/${token}`);
const html = await opened.text();
expect(opened.status).toBe(200);
expect(html).toContain('The link works once');
expect(html).not.toContain(LINK_GONE);
expect(opened.headers.get('set-cookie')).toBeNull();
expect(usedAt(db, token)).toBeNull();
expect(count(db, 'SELECT COUNT(*) AS n FROM sessions')).toBe(0);
const ignored = await postLink(app, token, 'not-the-proof-value-000000000000');
expect(ignored.status).toBe(404);
expect(usedAt(db, token)).toBeNull();
const proof = field(html, 'proof');
const signedIn = await postLink(app, token, proof);
expect(signedIn.status).toBe(303);
expect(signedIn.headers.get('location')).toBe('/admin');
const setCookie = signedIn.headers.get('set-cookie') ?? '';
expect(setCookie).toContain('HttpOnly');
expect(setCookie).toContain('SameSite=Lax');
expect(setCookie).not.toContain('Secure');
expect(setCookie).not.toContain('@');
expect(usedAt(db, token)).toBe(NOW);
expect(count(db, 'SELECT COUNT(*) AS n FROM sessions')).toBe(1);
const again = await postLink(app, token, proof);
expect(again.status).toBe(404);
expect(count(db, 'SELECT COUNT(*) AS n FROM sessions')).toBe(1);
const home = await app.request('/admin', { headers: { cookie: cookieHeader(signedIn) } });
expect(home.status).toBe(200);
const homeHtml = await home.text();
expect(homeHtml).toContain('Signed in as <strong>Administrator</strong>');
expect(homeHtml).toContain('No database backup has been saved yet.');
expect(homeHtml).not.toContain('coordinator@example.invalid');
});
it('still accepts a valid link after other guesses from the same network', async () => {
const { app, db } = await buildApp();
await postLogin(app, 'coordinator@example.invalid');
const token = magicToken(db);
for (let index = 0; index < 20; index += 1) {
const guess = await postLink(app, `not-a-real-token-value-${index}xxxx`, 'also-not-a-real-proof-value-0001');
expect(guess.status).toBe(404);
}
const page = await app.request(`/login/link/${token}`);
const signedIn = await postLink(app, token, field(await page.text(), 'proof'));
expect(signedIn.status).toBe(303);
const blocked = await postLink(app, 'not-a-real-token-value-finalxxx', 'also-not-a-real-proof-value-0001');
expect(blocked.status).toBe(429);
expect(blocked.headers.get('retry-after')).toBeTruthy();
});
it('limits sign-in requests for one address', async () => {
const { app } = await buildApp();
for (let index = 0; index < 3; index += 1) {
const response = await postLogin(app, 'coordinator@example.invalid');
expect(response.status).toBe(200);
}
const limited = await postLogin(app, 'coordinator@example.invalid');
expect(limited.status).toBe(429);
expect(await limited.text()).toContain('Too many sign-in attempts');
expect(limited.headers.get('retry-after')).toBeTruthy();
});
it('does not let a cross-site sign-in post use up the network allowance', async () => {
const { app } = await buildApp();
for (let index = 0; index < LOGIN_IP_LIMIT; index += 1) {
const rejected = await app.request('/login', {
method: 'POST',
headers: { origin: 'https://evil.example', 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ email: 'coordinator@example.invalid', 'cf-turnstile-response': 'token' }),
});
expect(rejected.status).toBe(403);
}
const allowed = await postLogin(app, 'coordinator@example.invalid');
expect(allowed.status).toBe(200);
expect(await allowed.text()).toContain(ACCEPTED);
});
it('creates the first administrator once and does not replace that account', async () => {
const { db, created } = await buildApp();
expect(created).toEqual({ created: true });
expect(bootstrapAdmin(db, 'other@example.invalid', NOW)).toEqual({ created: false });
expect(db.prepare('SELECT email, name, role, password_hash, active FROM coordinators').get()).toEqual({
email: 'coordinator@example.invalid',
name: 'Administrator',
role: 'admin',
password_hash: null,
active: 1,
});
});
it('revokes sessions from the host recovery command and can replace the address', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
expect((await app.request('/admin', { headers: { cookie } })).status).toBe(200);
const result = recoverCoordinator(db, {
email: 'coordinator@example.invalid',
replaceWith: 'next@example.invalid',
now: NOW,
});
expect(result).toEqual({ coordinatorId: 1 });
expect((await app.request('/admin', { headers: { cookie } })).status).toBe(303);
await postLogin(app, 'coordinator@example.invalid');
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'magic_link' AND status = 'pending' AND to_email = 'coordinator@example.invalid'")).toBe(0);
await postLogin(app, 'next@example.invalid');
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'magic_link' AND status = 'pending' AND to_email = 'next@example.invalid'")).toBe(1);
expect(auditJson(db)).not.toContain('@');
});
it('sends a sign-in link without using it, and drops an expired one', async () => {
const sent: OutboundMail[] = [];
const mailer: Mailer = { send: async (message) => { sent.push(message); return { result: 'sent', providerId: 'local' }; } };
const fresh = await buildApp();
await postLogin(fresh.app, 'coordinator@example.invalid');
const token = magicToken(fresh.db);
expect(await deliverDueMail(fresh.db, mailer, NOW, () => 0.5)).toBe(1);
expect(sent[0]?.text).toContain(`/login/link/${token}`);
expect(sent[0]?.text).toContain('expires in 15 minutes');
expect(sent[0]?.text).toContain('Opening the link does not sign you in');
expect(usedAt(fresh.db, token)).toBeNull();
const stale = await buildApp();
await postLogin(stale.app, 'coordinator@example.invalid');
stale.db.prepare('UPDATE login_tokens SET expires_at = ?').run(NOW);
const calls: OutboundMail[] = [];
expect(await deliverDueMail(stale.db, { send: async (message) => { calls.push(message); return { result: 'sent', providerId: null }; } }, NOW, () => 0.5)).toBe(0);
expect(calls).toHaveLength(0);
expect(stale.db.prepare("SELECT status AS status FROM outbox WHERE kind = 'magic_link'").get()).toEqual({ status: 'cancelled' });
});
it('escapes the sign-in letter', () => {
const rendered = renderMagicLink({ signInUrl: 'http://127.0.0.1:3000/login/link/abc', replyTo: 'a<b@example.invalid' });
expect(rendered.html).toContain('a&lt;b@example.invalid');
expect(rendered.html).not.toContain('a<b@example.invalid');
expect(rendered.subject).not.toContain('\n');
});
it('sets the session cookie for https and for a mounted path', () => {
const secure = sessionSetCookie({ basePath: '/volunteer', secureCookies: true }, 'abc');
expect(secure).toContain('Path=/volunteer');
expect(secure).toContain('Secure');
expect(secure).toContain('HttpOnly');
expect(secure).toContain('SameSite=Lax');
expect(sessionSetCookie({ basePath: '', secureCookies: false }, 'abc')).not.toContain('Secure');
expect(sessionClearCookie({ basePath: '', secureCookies: false })).toContain('Max-Age=0');
});
});
describe('coordinator screens', () => {
it('keeps unpublished events and the roster off the public site', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
expect((await app.request('/admin')).status).toBe(303);
const created = await postForm(app, '/admin/events', cookie, {
title: 'Soup Night',
slug: '',
description: 'Bring a spoon.',
location: 'Sioux Center, Iowa',
tz: 'America/Chicago',
}, { origin: 'null', 'sec-fetch-site': 'same-origin' });
expect(created.status).toBe(303);
const eventId = Number(/\/admin\/events\/(\d+)/.exec(created.headers.get('location') ?? '')?.[1]);
expect((await app.request('/e/soup-night')).status).toBe(404);
expect(await (await app.request('/')).text()).not.toContain('Soup Night');
const published = await postForm(app, `/admin/events/${eventId}`, cookie, {
title: 'Soup Night',
slug: 'soup-night',
description: 'Bring a spoon.',
location: 'Sioux Center, Iowa',
tz: 'America/Chicago',
published: 'yes',
});
expect(published.status).toBe(303);
expect((await app.request('/e/soup-night')).status).toBe(200);
const shift = await postForm(app, `/admin/events/${eventId}/shifts`, cookie, {
role: 'Ladle',
date: '2026-10-15',
start: '09:00',
end: '12:00',
capacity: '2',
});
expect(shift.status).toBe(303);
const shiftId = Number(/\/admin\/shifts\/(\d+)/.exec(shift.headers.get('location') ?? '')?.[1]);
const backwards = await postForm(app, `/admin/events/${eventId}/shifts`, cookie, {
role: 'Overnight',
date: '2026-10-15',
start: '12:00',
end: '09:00',
capacity: '1',
});
expect(backwards.status).toBe(400);
expect(await backwards.text()).toContain('same day');
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(1);
const pat = reserve(db, shiftId, 'Pat Example', 'pat@example.invalid', 'pat-operation');
const sam = reserve(db, shiftId, 'Sam Example', 'sam@example.invalid', 'sam-operation');
expect(pat.manageToken).toBeTruthy();
const roster = await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } });
const rosterHtml = await roster.text();
expect(rosterHtml).toContain('pat@example.invalid');
expect(rosterHtml).toContain('Sam Example');
const publicShift = await (await app.request(`/s/${shiftId}`)).text();
expect(publicShift).not.toContain('pat@example.invalid');
expect(publicShift).not.toContain('Sam Example');
expect(await (await app.request('/')).text()).not.toContain('pat@example.invalid');
const tooSmall = await postForm(app, `/admin/shifts/${shiftId}`, cookie, {
role: 'Ladle',
date: '2026-10-15',
start: '09:00',
end: '12:00',
capacity: '1',
});
expect(tooSmall.status).toBe(400);
expect(await tooSmall.text()).toContain('cannot be lower');
expect(db.prepare('SELECT capacity AS capacity FROM shifts WHERE id = ?').get(shiftId)).toEqual({ capacity: 2 });
const moved = await postForm(app, `/admin/shifts/${shiftId}`, cookie, {
role: 'Ladle',
date: '2026-10-15',
start: '10:00',
end: '12:00',
capacity: '2',
});
expect(moved.status).toBe(303);
expect(readManageSignup(db, pat.manageToken ?? '', NOW)).toBeNull();
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'changed' AND status = 'pending'")).toBe(2);
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND status = 'pending'")).toBe(0);
const changed = db.prepare("SELECT body_text AS body_text FROM outbox WHERE kind = 'changed' AND to_email = 'pat@example.invalid'").get() as { body_text: string };
const nextToken = /\/m\/([A-Za-z0-9_-]+)/.exec(changed.body_text)?.[1] ?? '';
expect(readManageSignup(db, nextToken, NOW)?.status).toBe('confirmed');
expect(await (await app.request(`/s/${shiftId}`)).text()).toContain('10:00 AM');
const patId = db.prepare("SELECT id AS id FROM signups WHERE email_norm = 'pat@example.invalid'").get() as { id: number };
const cancelled = await postForm(app, `/admin/signups/${patId.id}/cancel`, cookie, {});
expect(cancelled.status).toBe(303);
expect(cancelled.headers.get('location')).toContain('signup-cancelled');
expect(db.prepare("SELECT status AS status FROM signups WHERE id = ?").get(patId.id)).toEqual({ status: 'cancelled' });
expect(await (await app.request(`/s/${shiftId}`)).text()).not.toContain('pat@example.invalid');
expect(await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text()).toContain('Pat Example');
const closed = await postForm(app, `/admin/shifts/${shiftId}/cancel`, cookie, {});
expect(closed.status).toBe(303);
expect(db.prepare('SELECT cancelled AS cancelled FROM shifts WHERE id = ?').get(shiftId)).toEqual({ cancelled: 1 });
expect(db.prepare("SELECT status AS status FROM signups WHERE email_norm = 'sam@example.invalid'").get()).toEqual({ status: 'cancelled' });
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(2);
expect(await (await app.request('/')).text()).not.toContain('Ladle');
const closedPage = await (await app.request(`/s/${shiftId}`)).text();
expect(closedPage).toContain('This shift is closed');
expect(closedPage).not.toContain('<form');
expect(closedPage).not.toContain('sam@example.invalid');
expect(auditJson(db)).not.toContain('@');
expect(sam.manageToken).not.toBe(nextToken);
});
it('adds a walk-in without putting their name on the public list', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const shiftId = await openShift(app, cookie, { published: false, capacity: '2', role: 'Bagging', date: '2026-10-21' });
const page = await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } });
const html = await page.text();
expect(html).toContain('Add a walk-in');
expect(html).toContain('src="/js/enhance.js"');
expect(html).toContain('data-under-18');
expect(html).toContain('data-guardian');
expect(html).not.toMatch(/id="walkin-under-18"[^>]*\schecked/);
expect(html).not.toContain('cf-turnstile');
const body = walkInBody(html, {
name: 'Dee Example',
email: 'Dee@Example.invalid',
phone: '712-555-0199',
notes: 'Arrived at the door',
});
const added = await postBody(app, `/admin/shifts/${shiftId}/walk-in`, cookie, body);
const replay = await postBody(app, `/admin/shifts/${shiftId}/walk-in`, cookie, body);
expect(added.status).toBe(303);
expect(added.headers.get('location')).toContain('notice=walk-in');
expect(replay.status).toBe(303);
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'dee@example.invalid' AND status = 'confirmed' AND group_size = 1")).toBe(1);
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND status = 'pending' AND to_email = 'dee@example.invalid'")).toBe(1);
expect(db.prepare("SELECT action AS action FROM audit WHERE action = 'signup.walkin'").get()).toEqual({ action: 'signup.walkin' });
expect(auditJson(db)).not.toContain('@');
const roster = await (await app.request(added.headers.get('location') ?? '', { headers: { cookie } })).text();
expect(roster).toContain('They are on this shift');
expect(roster).toContain('Dee Example');
expect(await (await app.request('/')).text()).not.toContain('Dee Example');
expect(await (await app.request('/')).text()).not.toContain('dee@example.invalid');
expect((await app.request(`/s/${shiftId}`)).status).toBe(404);
const again = await postWalkIn(app, cookie, shiftId, { name: 'Dee Example', email: 'dee@example.invalid' });
expect(again.status).toBe(400);
expect(await again.text()).toContain('already signed up');
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(1);
const other = await postWalkIn(app, cookie, shiftId, { name: 'Sam Example', email: 'dee@example.invalid' });
expect(other.status).toBe(303);
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'dee@example.invalid' AND status = 'confirmed'")).toBe(2);
});
it('keeps a walk-in off a full, closed, or ended shift and asks for a guardian', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const shiftId = await openShift(app, cookie, { published: true, capacity: '1', role: 'Sorting', date: '2026-10-21' });
const minor = await postWalkIn(app, cookie, shiftId, { name: 'Kim Example', email: 'kim@example.invalid', under18: 'yes' });
expect(minor.status).toBe(400);
const minorHtml = await minor.text();
expect(minorHtml).toContain('Enter the guardian name.');
expect(minorHtml).toMatch(/id="walkin-under-18"[^>]*\schecked/);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
const added = await postWalkIn(app, cookie, shiftId, {
name: 'Kim Example',
email: 'kim@example.invalid',
under18: 'yes',
guardianName: 'Pat Example',
guardianEmail: 'pat@example.invalid',
});
expect(added.status).toBe(303);
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND status = 'pending'")).toBe(2);
const full = await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text();
expect(full).toContain('This shift is full.');
expect(full).not.toContain('Add a walk-in');
expect(await (await app.request(`/s/${shiftId}`)).text()).not.toContain('kim@example.invalid');
const overflow = await postWalkIn(app, cookie, shiftId, { name: 'More Example', email: 'more@example.invalid' });
expect(overflow.status).toBe(400);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(1);
const endedId = await openShift(app, cookie, { published: true, capacity: '2', role: 'Morning', date: '2026-10-14', start: '09:00', end: '12:00' });
const ended = await (await app.request(`/admin/shifts/${endedId}`, { headers: { cookie } })).text();
expect(ended).toContain('This shift has ended.');
expect(ended).not.toContain('Add a walk-in');
await postForm(app, `/admin/shifts/${shiftId}/cancel`, cookie, {});
const closed = await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text();
expect(closed).not.toContain('Add a walk-in');
const rejected = await app.request(`/admin/shifts/${shiftId}/walk-in`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ name: 'Late Example', email: 'late@example.invalid' }),
});
expect(rejected.status).toBe(403);
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'late@example.invalid'")).toBe(0);
});
it('marks attendance without emailing or showing it publicly', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const shiftId = await openShift(app, cookie, { published: true, capacity: '2', role: 'Greeting', date: '2026-10-22' });
const added = await postWalkIn(app, cookie, shiftId, { name: 'Ria Example', email: 'ria.fake@example.invalid' });
expect(added.status).toBe(303);
const signupId = (db.prepare("SELECT id AS id FROM signups WHERE email_norm = 'ria.fake@example.invalid'").get() as { id: number }).id;
const mailBefore = count(db, 'SELECT COUNT(*) AS n FROM outbox');
const attended = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'attended' });
expect(attended.status).toBe(303);
expect(attended.headers.get('location')).toContain('notice=attended');
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: 1 });
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(mailBefore);
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.attend'")).toBe(1);
const repeat = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'attended' });
expect(repeat.status).toBe(303);
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.attend'")).toBe(1);
const roster = await (await app.request(attended.headers.get('location') ?? '', { headers: { cookie } })).text();
expect(roster).toContain('Marked attended.');
expect(roster).toContain('Attended.');
expect(roster).toContain('aria-pressed="true"');
const missed = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'no-show' });
expect(missed.status).toBe(303);
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: 0 });
const missedPage = await (await app.request(missed.headers.get('location') ?? '', { headers: { cookie } })).text();
expect(missedPage).toContain('No-show.');
const cleared = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'clear' });
expect(cleared.status).toBe(303);
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: null });
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.attend.clear'")).toBe(1);
const marked = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'attended' });
expect(marked.status).toBe(303);
const publicShift = await (await app.request(`/s/${shiftId}`)).text();
expect(publicShift).not.toContain('ria.fake@example.invalid');
expect(publicShift).not.toContain('No-show');
expect(publicShift).not.toContain('Attended.');
expect(await (await app.request('/')).text()).not.toContain('ria.fake@example.invalid');
db.prepare("UPDATE shifts SET starts_at_utc = '2026-10-14T14:00:00.000Z', ends_at_utc = '2026-10-14T17:00:00.000Z' WHERE id = ?").run(shiftId);
const afterEnd = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'no-show' });
expect(afterEnd.status).toBe(303);
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: 0 });
await postForm(app, `/admin/signups/${signupId}/cancel`, cookie, {});
const blocked = await postForm(app, `/admin/signups/${signupId}/attendance`, cookie, { mark: 'attended' });
expect(blocked.status).toBe(400);
expect(await blocked.text()).toContain('That signup is cancelled.');
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: 0 });
const closedRoster = await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text();
expect(closedRoster).not.toContain(`/admin/signups/${signupId}/attendance`);
expect(auditJson(db)).not.toContain('@');
const bare = await app.request(`/admin/signups/${signupId}/attendance`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ mark: 'attended' }),
});
expect(bare.status).toBe(403);
expect(db.prepare('SELECT attended AS attended FROM signups WHERE id = ?').get(signupId)).toEqual({ attended: 0 });
});
it('rejects a coordinator form without its matching token', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const rejected = await app.request('/admin/events', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ title: 'Nope', slug: 'nope', tz: 'America/Chicago' }),
});
expect(rejected.status).toBe(403);
expect(count(db, 'SELECT COUNT(*) AS n FROM events')).toBe(0);
const home = await app.request('/admin', { headers: { cookie } });
const logout = await app.request('/logout', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ csrf: field(await home.text(), 'csrf') }),
});
expect(logout.status).toBe(303);
expect(logout.headers.get('set-cookie')).toContain('Max-Age=0');
expect((await app.request('/admin', { headers: { cookie } })).status).toBe(303);
});
it('moves a confirmed signup onto another shift in the same event', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const eventId = await createEvent(app, cookie, 'Pantry', true);
const sourceId = await addShift(app, cookie, eventId, { role: 'Sorting', date: '2026-10-22', capacity: '2' });
const destinationId = await addShift(app, cookie, eventId, { role: 'Distribution', date: '2026-10-23', capacity: '2' });
const added = await postWalkIn(app, cookie, sourceId, {
name: 'Kim Example',
email: 'kim@example.invalid',
under18: 'yes',
guardianName: 'Pat Example',
guardianEmail: 'pat@example.invalid',
});
expect(added.status).toBe(303);
const signupId = signupIdFor(db, 'kim@example.invalid');
db.prepare('UPDATE signups SET phone = ?, notes = ?, reminders_off = 1, attended = 1 WHERE id = ?').run('712-555-0199', 'Blue shirt', signupId);
const oldToken = manageToken(db, signupId, 'confirmation');
db.prepare(
`INSERT INTO outbox (
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
headers_json, send_after, attempts, status, created_at
) VALUES (?, ?, ?, 'reminder', ?, 'Reminder', 'Soon', '<p>Soon</p>', '{}', ?, 0, 'pending', ?)`,
).run(`reminder:${signupId}`, signupId, sourceId, 'kim@example.invalid', NOW, NOW);
const versions = shiftVersions(db);
const page = await app.request(`/admin/shifts/${sourceId}`, { headers: { cookie } });
const html = await page.text();
expect(optionValues(html, 'destination')).toEqual([String(destinationId)]);
const moved = await postMove(app, cookie, signupId, html, String(destinationId));
expect(moved.status).toBe(303);
expect(moved.headers.get('location')).toBe(`/admin/shifts/${destinationId}?notice=moved`);
const source = db.prepare('SELECT status, attended, shift_id FROM signups WHERE id = ?').get(signupId) as {
status: string;
attended: number;
shift_id: number;
};
expect(source).toEqual({ status: 'cancelled', attended: 1, shift_id: sourceId });
expect(readManageSignup(db, oldToken, NOW)).toBeNull();
const created = db.prepare(
`SELECT id, status, attended, phone, notes, reminders_off, is_minor, guardian_name, guardian_email, shift_id
FROM signups WHERE shift_id = ? AND status = 'confirmed'`,
).get(destinationId) as {
id: number;
status: string;
attended: number | null;
phone: string;
notes: string;
reminders_off: number;
is_minor: number;
guardian_name: string;
guardian_email: string;
shift_id: number;
};
expect(created).toMatchObject({
status: 'confirmed',
attended: null,
phone: '712-555-0199',
notes: 'Blue shirt',
reminders_off: 1,
is_minor: 1,
guardian_name: 'Pat Example',
guardian_email: 'pat@example.invalid',
shift_id: destinationId,
});
expect(shiftVersions(db)).toEqual(versions);
expect(counted(db, signupId, 'confirmation', 'cancelled')).toBe(2);
expect(db.prepare("SELECT status AS status FROM outbox WHERE kind = 'reminder'").get()).toEqual({ status: 'cancelled' });
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'changed' AND status = 'pending'")).toBe(2);
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled'")).toBe(0);
const letter = db.prepare("SELECT subject, body_text FROM outbox WHERE kind = 'changed' AND to_email = 'kim@example.invalid'").get() as {
subject: string;
body_text: string;
};
expect(letter.subject).toBe('Your signup was moved to Distribution');
expect(letter.body_text).toContain('A coordinator moved your signup to a different shift.');
expect(letter.body_text).not.toContain(oldToken);
const nextToken = manageToken(db, created.id, 'changed');
expect(readManageSignup(db, nextToken, NOW)?.role).toBe('Distribution');
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.move'")).toBe(1);
const again = await postMove(app, cookie, signupId, html, String(destinationId));
expect(again.status).toBe(303);
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE status = 'confirmed'")).toBe(1);
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.move'")).toBe(1);
const roster = await (await app.request(moved.headers.get('location') ?? '', { headers: { cookie } })).text();
expect(roster).toContain('They are on this shift. A change email is queued.');
expect(roster).toContain('Kim Example');
expect(roster).toContain('Attendance is not marked.');
const sourceRoster = await (await app.request(`/admin/shifts/${sourceId}`, { headers: { cookie } })).text();
expect(sourceRoster).not.toContain(`/admin/signups/${signupId}/move`);
expect(sourceRoster).toContain('0/2 spots filled');
expect(sourceRoster).toContain('event-pill is-open');
const home = await (await app.request('/')).text();
const shiftPage = await (await app.request(`/s/${destinationId}`)).text();
expect(home).not.toContain('kim@example.invalid');
expect(home).not.toContain('Kim Example');
expect(shiftPage).not.toContain('kim@example.invalid');
expect(shiftPage).not.toContain('Attended.');
expect(auditJson(db)).not.toContain('@');
});
it('keeps the original signup when the move cannot be saved', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const eventId = await createEvent(app, cookie, 'Pantry', true);
const sourceId = await addShift(app, cookie, eventId, { role: 'Sorting', date: '2026-10-22', capacity: '2' });
const fullId = await addShift(app, cookie, eventId, { role: 'Full shift', date: '2026-10-23', capacity: '1' });
const openId = await addShift(app, cookie, eventId, { role: 'Distribution', date: '2026-10-24', capacity: '2' });
const endedId = await addShift(app, cookie, eventId, { role: 'Morning', date: '2026-10-14', capacity: '2', start: '09:00', end: '12:00' });
const otherEvent = await createEvent(app, cookie, 'Other', true);
const otherShift = await addShift(app, cookie, otherEvent, { role: 'Elsewhere', date: '2026-10-25', capacity: '2' });
await postWalkIn(app, cookie, sourceId, { name: 'Ria Example', email: 'ria@example.invalid' });
await postWalkIn(app, cookie, fullId, { name: 'Dee Example', email: 'dee@example.invalid' });
const signupId = signupIdFor(db, 'ria@example.invalid');
const page = await (await app.request(`/admin/shifts/${sourceId}`, { headers: { cookie } })).text();
expect(optionValues(page, 'destination')).toEqual([String(openId)]);
expect(page).not.toContain('Full shift,');
expect(page).not.toContain('Morning,');
const mailBefore = count(db, 'SELECT COUNT(*) AS n FROM outbox');
const full = await postMove(app, cookie, signupId, page, String(fullId));
expect(full.status).toBe(400);
expect(await full.text()).toContain('That shift is full.');
const ended = await postMove(app, cookie, signupId, page, String(endedId));
expect(ended.status).toBe(400);
expect(await ended.text()).toContain('That shift is closed.');
const elsewhere = await postMove(app, cookie, signupId, page, String(otherShift));
expect(elsewhere.status).toBe(400);
expect(await elsewhere.text()).toContain('Choose a shift in this event.');
await postWalkIn(app, cookie, openId, { name: 'Ria Example', email: 'ria@example.invalid' });
const duplicate = await postMove(app, cookie, signupId, page, String(openId));
expect(duplicate.status).toBe(400);
expect(await duplicate.text()).toContain('That person is already signed up for this shift.');
expect(db.prepare('SELECT status, shift_id FROM signups WHERE id = ?').get(signupId)).toEqual({ status: 'confirmed', shift_id: sourceId });
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.move'")).toBe(0);
expect(counted(db, signupId, 'confirmation', 'pending')).toBe(1);
const bare = await app.request(`/admin/signups/${signupId}/move`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ destination: String(openId) }),
});
expect(bare.status).toBe(403);
expect(db.prepare('SELECT status FROM signups WHERE id = ?').get(signupId)).toEqual({ status: 'confirmed' });
const stale = await postMove(app, cookie, signupId, page.replace(/name="move_token" value="[^"]*"/, 'name="move_token" value="nope"'), String(openId));
expect(stale.status).toBe(400);
expect(await stale.text()).toContain('This form is out of date');
await postForm(app, `/admin/signups/${signupId}/cancel`, cookie, {});
const cancelled = await postMove(app, cookie, signupId, page, String(openId));
expect(cancelled.status).toBe(400);
expect(await cancelled.text()).toContain('That signup is cancelled.');
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ria@example.invalid' AND status = 'confirmed'")).toBe(1);
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBeGreaterThan(mailBefore);
expect(auditJson(db)).not.toContain('@');
});
it('moves someone onto a shift that already has their email for a different person', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const eventId = await createEvent(app, cookie, 'Pantry', true);
const sourceId = await addShift(app, cookie, eventId, { role: 'Sorting', date: '2026-10-22', capacity: '2' });
const openId = await addShift(app, cookie, eventId, { role: 'Distribution', date: '2026-10-24', capacity: '2' });
await postWalkIn(app, cookie, sourceId, { name: 'Ria Example', email: 'ria@example.invalid' });
await postWalkIn(app, cookie, openId, { name: 'Sam Example', email: 'ria@example.invalid' });
const signupId = signupIdFor(db, 'ria@example.invalid');
const page = await (await app.request(`/admin/shifts/${sourceId}`, { headers: { cookie } })).text();
const moved = await postMove(app, cookie, signupId, page, String(openId));
expect(moved.status).toBe(303);
expect(count(db, `SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ria@example.invalid' AND shift_id = ${openId} AND status = 'confirmed'`)).toBe(2);
expect(db.prepare('SELECT status, shift_id FROM signups WHERE id = ?').get(signupId)).toEqual({ status: 'cancelled', shift_id: sourceId });
});
it('keeps the next two weeks of shifts in view and tucks later ones under see more', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const eventId = await createEvent(app, cookie, 'Pantry', true);
await addShift(app, cookie, eventId, { role: 'Morning', date: '2026-10-13', capacity: '2' });
await addShift(app, cookie, eventId, { role: 'Sorting', date: '2026-10-15', capacity: '2' });
await addShift(app, cookie, eventId, { role: 'Distribution', date: '2026-10-28', capacity: '2' });
await addShift(app, cookie, eventId, { role: 'Intake', date: '2026-11-04', capacity: '2' });
await addShift(app, cookie, eventId, { role: 'Packing', date: '2026-11-11', capacity: '2' });
const eveningId = await addShift(app, cookie, eventId, { role: 'Evening', date: '2026-11-18', capacity: '2' });
expect((await postForm(app, `/admin/shifts/${eveningId}/cancel`, cookie, {})).status).toBe(303);
const html = await (await app.request(`/admin/events/${eventId}`, { headers: { cookie } })).text();
const moreAt = html.indexOf('See 2 more shifts');
expect(moreAt).toBeGreaterThan(0);
const before = html.slice(0, moreAt);
const after = html.slice(moreAt);
expect(before).toContain('Morning');
expect(before).toContain('Sorting');
expect(before).toContain('Distribution');
expect(before).not.toContain('Intake');
expect(before).not.toContain('Packing');
expect(before).not.toContain('Evening');
expect(after.indexOf('Intake')).toBeGreaterThan(-1);
expect(after.indexOf('Packing')).toBeGreaterThan(after.indexOf('Intake'));
expect(after.indexOf('Evening')).toBeGreaterThan(after.indexOf('Packing'));
expect(after).toContain('Show fewer');
expect(html).not.toContain('<details class="shift-more" open');
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(6);
const soon = await createEvent(app, cookie, 'Soup', true);
await addShift(app, cookie, soon, { role: 'Ladle', date: '2026-10-16', capacity: '2' });
const short = await (await app.request(`/admin/events/${soon}`, { headers: { cookie } })).text();
expect(short).toContain('Ladle');
expect(short).not.toContain('See 1 more shift');
expect(short).not.toContain('shift-more');
const distant = await createEvent(app, cookie, 'Holiday', true);
await addShift(app, cookie, distant, { role: 'Early', date: '2026-11-04', capacity: '2' });
await addShift(app, cookie, distant, { role: 'Later', date: '2026-11-18', capacity: '2' });
const far = await (await app.request(`/admin/events/${distant}`, { headers: { cookie } })).text();
const farMore = far.indexOf('See 1 more shift');
expect(farMore).toBeGreaterThan(0);
expect(far.slice(0, farMore)).toContain('Early');
expect(far.slice(farMore)).toContain('Later');
});
it('treats an expired session as signed out', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
db.prepare('UPDATE sessions SET expires_at = ?').run(NOW);
expect((await app.request('/admin', { headers: { cookie } })).status).toBe(303);
});
});
const LINK_GONE = 'This sign-in link is not available.';
async function buildApp() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-admin-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
const created = bootstrapAdmin(db, config.bootstrapAdminEmail, NOW);
const app = createApp(config, db, {
now: NOW,
clientIp: () => '203.0.113.10',
verifyTurnstile: async () => ({ ok: true }),
});
return { app, db, config, created };
}
async function signIn(app: Awaited<ReturnType<typeof buildApp>>['app'], db: Awaited<ReturnType<typeof buildApp>>['db']) {
await postLogin(app, 'coordinator@example.invalid');
const token = magicToken(db);
const page = await app.request(`/login/link/${token}`);
const signedIn = await postLink(app, token, field(await page.text(), 'proof'));
return cookieHeader(signedIn);
}
function postLogin(app: Awaited<ReturnType<typeof buildApp>>['app'], email: string) {
return app.request('/login', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ email, company_website: '', 'cf-turnstile-response': 'token' }),
});
}
function postLink(app: Awaited<ReturnType<typeof buildApp>>['app'], token: string, proof: string) {
return app.request(`/login/link/${token}`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ proof }),
});
}
async function postForm(
app: Awaited<ReturnType<typeof buildApp>>['app'],
pathname: string,
cookie: string,
fields: Record<string, string>,
extraHeaders: Record<string, string> = {},
) {
const current = await app.request('/admin', { headers: { cookie } });
const csrf = field(await current.text(), 'csrf');
return app.request(pathname, {
method: 'POST',
headers: {
origin: extraHeaders.origin ?? ORIGIN,
'content-type': 'application/x-www-form-urlencoded',
cookie,
...extraHeaders,
},
body: new URLSearchParams({ csrf, ...fields }),
});
}
function reserve(db: Awaited<ReturnType<typeof buildApp>>['db'], shiftId: number, name: string, email: string, operationId: string) {
const result = reserveSignup(db, {
shiftId,
name,
email,
phone: '712-555-0100',
notes: 'Bring gloves',
isMinor: false,
guardianName: null,
guardianEmail: null,
operationId,
now: NOW,
mail: MAIL,
});
if (!result.ok || !result.manageToken) throw new Error('Reservation did not save.');
return result;
}
function magicToken(db: Awaited<ReturnType<typeof buildApp>>['db']): string {
const row = db
.prepare("SELECT body_text AS body_text FROM outbox WHERE kind = 'magic_link' AND status = 'pending' ORDER BY id DESC LIMIT 1")
.get() as { body_text: string } | undefined;
const token = /\/login\/link\/([A-Za-z0-9_-]+)/.exec(row?.body_text ?? '')?.[1];
if (!token) throw new Error('The sign-in link was not queued.');
return token;
}
function usedAt(db: Awaited<ReturnType<typeof buildApp>>['db'], token: string): string | null {
const row = db.prepare('SELECT used_at AS used_at FROM login_tokens WHERE token_hash = ?').get(sha256(token)) as { used_at: string | null };
return row.used_at;
}
function cookieHeader(response: Response): string {
const match = /hope_session=([^;]+)/.exec(response.headers.get('set-cookie') ?? '');
if (!match?.[1]) throw new Error('The session cookie was not set.');
return `hope_session=${match[1]}`;
}
async function createEvent(
app: Awaited<ReturnType<typeof buildApp>>['app'],
cookie: string,
title: string,
published: boolean,
) {
const created = await postForm(app, '/admin/events', cookie, {
title,
slug: '',
description: '',
location: 'Sioux Center, Iowa',
tz: 'America/Chicago',
...(published ? { published: 'yes' } : {}),
});
return Number(/\/admin\/events\/(\d+)/.exec(created.headers.get('location') ?? '')?.[1]);
}
async function addShift(
app: Awaited<ReturnType<typeof buildApp>>['app'],
cookie: string,
eventId: number,
input: { role: string; date: string; capacity: string; start?: string; end?: string },
) {
const shift = await postForm(app, `/admin/events/${eventId}/shifts`, cookie, {
role: input.role,
date: input.date,
start: input.start ?? '09:00',
end: input.end ?? '12:00',
capacity: input.capacity,
});
return Number(/\/admin\/shifts\/(\d+)/.exec(shift.headers.get('location') ?? '')?.[1]);
}
function postMove(
app: Awaited<ReturnType<typeof buildApp>>['app'],
cookie: string,
signupId: number,
html: string,
destination: string,
) {
return postBody(
app,
`/admin/signups/${signupId}/move`,
cookie,
new URLSearchParams({
csrf: field(html, 'csrf'),
move_token: field(html, 'move_token'),
destination,
}),
);
}
function optionValues(html: string, name: string): string[] {
const select = new RegExp(`<select\\b[^>]*\\bname="${name}"[^>]*>([\\s\\S]*?)</select>`).exec(html)?.[1] ?? '';
return [...select.matchAll(/value="(\d+)"/g)].map((match) => match[1] ?? '');
}
function signupIdFor(db: Awaited<ReturnType<typeof buildApp>>['db'], email: string): number {
return Number((db.prepare('SELECT id AS id FROM signups WHERE email_norm = ? ORDER BY id LIMIT 1').get(email) as { id: number }).id);
}
function manageToken(db: Awaited<ReturnType<typeof buildApp>>['db'], signupId: number, kind: string): string {
const row = db.prepare('SELECT body_text AS body_text FROM outbox WHERE signup_id = ? AND kind = ? LIMIT 1').get(signupId, kind) as {
body_text: string;
};
const token = /\/m\/([A-Za-z0-9_-]+)/.exec(row.body_text)?.[1];
if (!token) throw new Error('The manage link was not queued.');
return token;
}
function shiftVersions(db: Awaited<ReturnType<typeof buildApp>>['db']): Array<{ id: number; version: number }> {
return db.prepare('SELECT id AS id, version AS version FROM shifts ORDER BY id').all() as Array<{ id: number; version: number }>;
}
function counted(db: Awaited<ReturnType<typeof buildApp>>['db'], signupId: number, kind: string, status: string): number {
return Number(
(db.prepare('SELECT COUNT(*) AS n FROM outbox WHERE signup_id = ? AND kind = ? AND status = ?').get(signupId, kind, status) as { n: number }).n,
);
}
async function openShift(
app: Awaited<ReturnType<typeof buildApp>>['app'],
cookie: string,
input: { published: boolean; capacity: string; role: string; date: string; start?: string; end?: string },
) {
const created = await postForm(app, '/admin/events', cookie, {
title: input.role,
slug: '',
description: '',
location: 'Sioux Center, Iowa',
tz: 'America/Chicago',
...(input.published ? { published: 'yes' } : {}),
});
const eventId = Number(/\/admin\/events\/(\d+)/.exec(created.headers.get('location') ?? '')?.[1]);
const shift = await postForm(app, `/admin/events/${eventId}/shifts`, cookie, {
role: input.role,
date: input.date,
start: input.start ?? '09:00',
end: input.end ?? '12:00',
capacity: input.capacity,
});
return Number(/\/admin\/shifts\/(\d+)/.exec(shift.headers.get('location') ?? '')?.[1]);
}
async function postWalkIn(
app: Awaited<ReturnType<typeof buildApp>>['app'],
cookie: string,
shiftId: number,
fields: Record<string, string>,
) {
const page = await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } });
return postBody(app, `/admin/shifts/${shiftId}/walk-in`, cookie, walkInBody(await page.text(), fields));
}
function walkInBody(html: string, fields: Record<string, string>) {
return new URLSearchParams({
csrf: field(html, 'csrf'),
form_token: field(html, 'form_token'),
name: fields.name ?? '',
email: fields.email ?? '',
phone: fields.phone ?? '',
notes: fields.notes ?? '',
guardianName: fields.guardianName ?? '',
guardianEmail: fields.guardianEmail ?? '',
...(fields.under18 ? { under18: fields.under18 } : {}),
});
}
function postBody(
app: Awaited<ReturnType<typeof buildApp>>['app'],
pathname: string,
cookie: string,
body: URLSearchParams,
) {
return app.request(pathname, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body,
});
}
function field(html: string, name: string): string {
const tag = new RegExp(`<input\\b[^>]*\\bname="${name}"[^>]*>`).exec(html)?.[0] ?? '';
return /value="([^"]*)"/.exec(tag)?.[1] ?? '';
}
function count(db: Awaited<ReturnType<typeof buildApp>>['db'], sql: string): number {
return Number((db.prepare(sql).get() as { n: number }).n);
}
function auditJson(db: Awaited<ReturnType<typeof buildApp>>['db']): string {
return (db.prepare('SELECT detail_json AS detail_json FROM audit').all() as Array<{ detail_json: string }>)
.map((row) => row.detail_json)
.join('\n');
}
function sha256(value: string): string {
return createHash('sha256').update(value).digest('hex');
}
+188
View File
@@ -0,0 +1,188 @@
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { Temporal } from '@js-temporal/polyfill';
import Database from 'better-sqlite3';
import { afterEach, describe, expect, it } from 'vitest';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { describeBackup, runDueBackup, startBackupRunner } from '../src/jobs/backup.js';
import { formatUtc } from '../src/time.js';
import { devEnv } from './env.js';
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('daily database backup', () => {
it('saves one consistent copy after 2:30 and does not rewrite it later the same day', async () => {
const { db, backups } = await openDb();
const at = localUtc('2026-06-15', 2, 30);
const before = localUtc('2026-06-15', 2, 0);
db.prepare(`INSERT INTO settings (key, value_json, updated_at) VALUES ('probe', '"first"', ?)`).run(at);
expect((await runDueBackup(db, backups, before)).ran).toBe(false);
expect(existsSync(path.join(backups, 'daily-2026-06-15.db'))).toBe(false);
const saved = await runDueBackup(db, backups, at);
expect(saved).toMatchObject({ ran: true, date: '2026-06-15', weekly: false, prunedDaily: 0, prunedWeekly: 0 });
const copy = new Database(path.join(backups, 'daily-2026-06-15.db'), { readonly: true, fileMustExist: true });
try {
expect(copy.pragma('journal_mode', { simple: true })).toBe('delete');
expect(copy.pragma('integrity_check', { simple: true })).toBe('ok');
expect(copy.prepare(`SELECT value_json FROM settings WHERE key = 'probe'`).get()).toEqual({ value_json: '"first"' });
} finally {
copy.close();
}
expect(readdirSync(backups).filter((name) => name.includes('wal') || name.includes('shm') || name.endsWith('.partial'))).toEqual([]);
expect(existsSync(path.join(backups, 'weekly-2026-06-15.db'))).toBe(false);
db.prepare(`UPDATE settings SET value_json = '"later"' WHERE key = 'probe'`).run();
expect((await runDueBackup(db, backups, localUtc('2026-06-15', 3, 0))).ran).toBe(false);
const again = new Database(path.join(backups, 'daily-2026-06-15.db'), { readonly: true, fileMustExist: true });
try {
expect(again.prepare(`SELECT value_json FROM settings WHERE key = 'probe'`).get()).toEqual({ value_json: '"first"' });
} finally {
again.close();
}
expect(db.prepare(`SELECT detail_json FROM audit WHERE action = 'backup.save'`).get()).toEqual({
detail_json: '{"prunedDaily":0,"prunedWeekly":0}',
});
expect(JSON.stringify(db.prepare('SELECT detail_json FROM audit').all())).not.toContain('@');
});
it('keeps 14 daily copies, 8 Sunday copies, and files that are not snapshots', async () => {
const { db, backups } = await openDb();
mkdirSync(backups, { recursive: true });
for (let day = 1; day <= 20; day += 1) {
writeFileSync(path.join(backups, `daily-2026-05-${String(day).padStart(2, '0')}.db`), '');
}
for (let day = 1; day <= 10; day += 1) {
writeFileSync(path.join(backups, `weekly-2026-01-${String(day).padStart(2, '0')}.db`), '');
}
writeFileSync(path.join(backups, 'pre-migrate-20260601T000000000Z.db'), 'keep');
writeFileSync(path.join(backups, 'notes.txt'), 'keep');
const sunday = localUtc('2026-06-14', 2, 30);
const saved = await runDueBackup(db, backups, sunday);
expect(saved).toMatchObject({ ran: true, date: '2026-06-14', weekly: true, prunedDaily: 7, prunedWeekly: 3 });
const names = readdirSync(backups).sort();
expect(names).toContain('pre-migrate-20260601T000000000Z.db');
expect(names).toContain('notes.txt');
expect(names).toContain('daily-2026-06-14.db');
expect(names).toContain('weekly-2026-06-14.db');
expect(names).not.toContain('daily-2026-05-01.db');
expect(names).not.toContain('daily-2026-05-07.db');
expect(names).toContain('daily-2026-05-08.db');
expect(names).not.toContain('weekly-2026-01-01.db');
expect(names).toContain('weekly-2026-01-04.db');
expect(names.filter((name) => name.includes('wal') || name.includes('shm') || name.endsWith('.partial'))).toEqual([]);
const weekly = new Database(path.join(backups, 'weekly-2026-06-14.db'), { readonly: true, fileMustExist: true });
try {
expect(weekly.pragma('integrity_check', { simple: true })).toBe('ok');
} finally {
weekly.close();
}
});
it('leaves older copies in place when the new backup fails', async () => {
const { db, backups } = await openDb();
mkdirSync(backups, { recursive: true });
writeFileSync(path.join(backups, 'daily-2026-06-01.db'), 'older');
writeFileSync(path.join(backups, 'pre-migrate-20260601T000000000Z.db'), 'keep');
const errors: string[] = [];
const write = console.error;
console.error = (message?: unknown) => {
errors.push(String(message));
};
let result: Awaited<ReturnType<typeof runDueBackup>>;
try {
result = await runDueBackup(db, backups, localUtc('2026-06-15', 2, 30), async () => {
throw new Error('disk full');
});
} finally {
console.error = write;
}
expect(result.ran).toBe(false);
expect(readdirSync(backups).sort()).toEqual(['daily-2026-06-01.db', 'pre-migrate-20260601T000000000Z.db']);
expect(db.prepare(`SELECT COUNT(*) AS n FROM job_runs WHERE job = 'backup'`).get()).toEqual({ n: 0 });
expect(errors.join(' ')).toContain('disk full');
expect(errors.join(' ')).not.toContain('@');
});
it('waits through the missing 2:30 and runs once when the hour repeats its earlier neighbor', async () => {
const spring = await openDb();
expect((await runDueBackup(spring.db, spring.backups, localUtc('2026-03-08', 1, 30, 'reject'))).ran).toBe(false);
expect((await runDueBackup(spring.db, spring.backups, localUtc('2026-03-08', 3, 0, 'reject'))).ran).toBe(true);
expect((await runDueBackup(spring.db, spring.backups, localUtc('2026-03-08', 3, 30, 'reject'))).ran).toBe(false);
const fall = await openDb();
const duringRepeat = localUtc('2026-11-01', 1, 30, 'later');
const atHalf = localUtc('2026-11-01', 2, 30, 'reject');
expect((await runDueBackup(fall.db, fall.backups, duringRepeat)).ran).toBe(false);
expect((await runDueBackup(fall.db, fall.backups, atHalf)).ran).toBe(true);
expect((await runDueBackup(fall.db, fall.backups, localUtc('2026-11-01', 2, 45, 'reject'))).ran).toBe(false);
expect(fall.db.prepare(`SELECT COUNT(*) AS n FROM job_runs WHERE job = 'backup'`).get()).toEqual({ n: 1 });
});
it('describes a missing, current, or old backup without naming a file path', () => {
const root = mkdtempSync(path.join(tmpdir(), 'hope-backup-status-'));
dirs.push(root);
const early = localUtc('2026-06-15', 2, 0);
const due = localUtc('2026-06-15', 2, 30);
expect(describeBackup(root, early)).toEqual({
state: 'waiting',
text: 'No database backup has been saved yet.',
});
expect(describeBackup(root, due)).toEqual({
state: 'behind',
text: 'No database backup has been saved yet.',
});
writeFileSync(path.join(root, 'daily-2026-06-14.db'), '');
expect(describeBackup(root, early).text).toBe('Database backup saved June 14, 2026.');
expect(describeBackup(root, due)).toEqual({
state: 'behind',
text: 'Database backup is behind. The newest saved copy is June 14, 2026.',
});
writeFileSync(path.join(root, 'daily-2026-06-15.db'), '');
expect(describeBackup(root, due)).toEqual({
state: 'saved',
text: 'Database backup saved June 15, 2026.',
});
expect(JSON.stringify(describeBackup(root, due))).not.toContain('/');
});
it('saves the backup on the first check after 2:30', async () => {
const { db, backups } = await openDb();
const runner = startBackupRunner(db, backups, () => localUtc('2026-06-15', 2, 30));
const file = path.join(backups, 'daily-2026-06-15.db');
for (let attempt = 0; attempt < 50 && !existsSync(file); attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 20));
}
runner.stop();
expect(existsSync(file)).toBe(true);
});
});
function localUtc(date: string, hour: number, minute: number, disambiguation: 'earlier' | 'later' | 'reject' = 'reject'): string {
const [year, month, day] = date.split('-').map(Number);
const zoned = Temporal.ZonedDateTime.from(
{ timeZone: 'America/Chicago', year, month, day, hour, minute, second: 0, millisecond: 0 },
{ disambiguation },
);
return formatUtc(zoned.toInstant());
}
async function openDb() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-backup-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
const backups = path.join(root, 'data', 'backups');
return { db, backups };
}
+55
View File
@@ -0,0 +1,55 @@
import { Temporal } from '@js-temporal/polyfill';
import { describe, expect, it } from 'vitest';
import { calendarMonth, calendarToday, chooseCalendarMonth, monthStep, monthsCovering, parseMonthId } from '../src/calendar.js';
describe('calendar months', () => {
it('builds a Sunday-first grid for the month', () => {
const october = calendarMonth('2026-10');
expect(october.label).toBe('October 2026');
expect(october.id).toBe('2026-10');
const inMonth = october.weeks.flat().filter((day) => day.inMonth);
expect(inMonth).toHaveLength(31);
expect(inMonth[0]).toMatchObject({ date: '2026-10-01', day: 1, label: 'Thursday, October 1, 2026' });
expect(inMonth.at(-1)).toMatchObject({ date: '2026-10-31', day: 31 });
expect(october.weeks[0]?.[0]).toMatchObject({ date: '2026-09-27', inMonth: false });
expect(october.weeks[0]?.[4]).toMatchObject({ date: '2026-10-01', inMonth: true });
for (const week of october.weeks) {
expect(week).toHaveLength(7);
const start = week[0];
expect(start).toBeDefined();
expect(Temporal.PlainDate.from(start?.date ?? '').dayOfWeek).toBe(7);
}
});
it('uses four exact weeks when the month starts on Sunday and ends on Saturday', () => {
const february = calendarMonth('2026-02');
expect(february.label).toBe('February 2026');
expect(february.weeks).toHaveLength(4);
expect(february.weeks[0]?.[0]).toMatchObject({ date: '2026-02-01', inMonth: true, day: 1 });
expect(february.weeks[3]?.[6]).toMatchObject({ date: '2026-02-28', inMonth: true, day: 28 });
expect(february.weeks.flat().every((day) => day.inMonth)).toBe(true);
});
it('lists the months that contain shifts, earliest first', () => {
expect(monthsCovering(['2026-11-04', '2026-10-15', '2026-10-01'])).toEqual(['2026-10', '2026-11']);
});
it('chooses one month and the months on either side', () => {
const dates = ['2026-10-15', '2026-11-04', '2026-12-02'];
expect(parseMonthId('2026-13')).toBeNull();
expect(parseMonthId('October')).toBeNull();
expect(chooseCalendarMonth(undefined, dates, '2026-10-14')).toBe('2026-10');
expect(chooseCalendarMonth('2026-11', dates, '2026-10-14')).toBe('2026-11');
expect(chooseCalendarMonth('nope', dates, '2026-10-14')).toBe('2026-10');
expect(chooseCalendarMonth('2026-09', dates, '2026-10-14')).toBe('2026-10');
expect(monthStep('2026-11', dates)).toEqual({ previous: '2026-10', next: '2026-12' });
expect(monthStep('2026-10', dates).previous).toBeNull();
expect(monthStep('2026-12', dates).next).toBeNull();
});
it('reads today in the event time zone', () => {
expect(calendarToday('America/Chicago', '2026-10-14T18:00:00.000Z')).toBe('2026-10-14');
expect(calendarToday('America/Chicago', '2026-10-15T04:30:00.000Z')).toBe('2026-10-14');
expect(calendarToday('America/Chicago', '2026-10-15T05:00:00.000Z')).toBe('2026-10-15');
});
});
+417
View File
@@ -0,0 +1,417 @@
import { randomBytes } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { Temporal } from '@js-temporal/polyfill';
import { afterEach, describe, expect, it } from 'vitest';
import { createApp } from '../src/app.js';
import { issueCancelToken } from '../src/cancel-token.js';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { issueFormToken } from '../src/form-token.js';
import { MANAGE_TOKEN_LIMIT } from '../src/rate-limit.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const NOW_MS = Temporal.Instant.from(NOW).epochMilliseconds;
const SECRET = 'dev-only-change-me-not-for-production-use';
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('manage-link cancellation', () => {
it('cancels one signup, frees the spot, and does not send mail', async () => {
const { app, db, shiftId } = await buildApp({ capacity: 1 });
const { managePath, token } = await openManage(app, shiftId, 'pat.cancel@example.invalid', '203.0.113.70');
const before = db.prepare('SELECT status, created_at, updated_at FROM signups').get() as {
status: string;
created_at: string;
updated_at: string;
};
const viewed = await app.request(managePath);
expect(viewed.status).toBe(200);
expect(await viewed.text()).toContain('Cancel this signup');
expect(db.prepare('SELECT status, updated_at FROM signups').get()).toEqual({
status: 'confirmed',
updated_at: before.updated_at,
});
expect(before.created_at).toBe(before.updated_at);
const full = await app.request(`/s/${shiftId}`);
expect(await full.text()).toContain('1/1 spots filled');
const cancelled = await postCancel(app, managePath, token);
expect(cancelled.status).toBe(303);
expect(cancelled.headers.get('location')).toBe(managePath);
const page = await app.request(managePath);
const html = await page.text();
expect(page.status).toBe(200);
expect(html).toContain('Cancelled');
expect(html).toContain('This signup is cancelled');
expect(html).toContain('Pat Cancel');
expect(html).not.toContain('<form');
expect(db.prepare('SELECT status FROM signups').all()).toEqual([{ status: 'cancelled' }]);
expect(db.prepare("SELECT kind, status FROM outbox ORDER BY id").all()).toEqual([
{ kind: 'confirmation', status: 'cancelled' },
{ kind: 'cancelled', status: 'pending' },
]);
const open = await app.request(`/s/${shiftId}`);
const openHtml = await open.text();
expect(openHtml).toContain('0/1 spots filled');
expect(openHtml).not.toContain('pat.cancel@example.invalid');
const again = await postCancel(app, managePath, token, { ip: '203.0.113.71' });
expect(again.status).toBe(303);
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE status = 'cancelled'").get()).toEqual({ n: 1 });
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled'").get()).toEqual({ n: 1 });
const returned = await postSignup(app, shiftId, { name: 'Pat Cancel', email: 'pat.cancel@example.invalid' }, '203.0.113.72');
expect(returned.status).toBe(303);
expect(db.prepare('SELECT status FROM signups ORDER BY id').all()).toEqual([
{ status: 'cancelled' },
{ status: 'confirmed' },
]);
expect((await (await app.request(`/s/${shiftId}`)).text())).toContain('1/1 spots filled');
expect((await (await app.request('/')).text())).not.toContain('Pat Cancel');
});
it('refuses a cancel that did not come from this signup page', async () => {
const { app, db, shiftId } = await buildApp();
const first = await openManage(app, shiftId, 'keep@example.invalid', '203.0.113.73');
const crossSite = await postCancel(app, first.managePath, first.token, { origin: 'https://evil.example', ip: '203.0.113.74' });
expect(crossSite.status).toBe(403);
expect(await crossSite.text()).toContain('could not be sent from this page');
const missing = await postCancel(app, first.managePath, '', { ip: '203.0.113.75' });
expect(missing.status).toBe(400);
expect(await missing.text()).toContain('could not be confirmed');
const tampered = `${first.token.slice(0, -1)}${first.token.endsWith('a') ? 'b' : 'a'}`;
const bad = await postCancel(app, first.managePath, tampered, { ip: '203.0.113.76' });
expect(bad.status).toBe(400);
const other = issueCancelToken(SECRET, 'another-manage-token-value');
const mismatched = await postCancel(app, first.managePath, other, { ip: '203.0.113.77' });
expect(mismatched.status).toBe(400);
expect(db.prepare('SELECT status FROM signups').get()).toEqual({ status: 'confirmed' });
expect(db.prepare("SELECT kind, status FROM outbox").all()).toEqual([{ kind: 'confirmation', status: 'pending' }]);
const opaque = await postCancel(app, first.managePath, first.token, {
origin: 'null',
site: 'same-origin',
ip: '203.0.113.78',
});
expect(opaque.status).toBe(303);
});
it('keeps an expired link from cancelling and limits unknown links without storing them', async () => {
const { app, db, shiftId } = await buildApp();
const saved = await openManage(app, shiftId, 'later@example.invalid', '203.0.113.80');
db.prepare("UPDATE signups SET token_expires_at = '2026-10-14T18:00:00.000Z'").run();
const expired = await postCancel(app, saved.managePath, saved.token, { ip: '203.0.113.80' });
expect(expired.status).toBe(404);
expect(await expired.text()).toContain('That page is not available');
expect(db.prepare('SELECT status FROM signups').get()).toEqual({ status: 'confirmed' });
const ip = '203.0.113.90';
for (let index = 0; index < MANAGE_TOKEN_LIMIT; index += 1) {
const response = await app.request(`/m/not-a-real-token-${index}-abcdefghij`, { headers: { 'x-test-ip': ip } });
expect(response.status).toBe(404);
}
const blocked = await app.request('/m/not-a-real-token-extra-abcdefghij', { headers: { 'x-test-ip': ip } });
expect(blocked.status).toBe(429);
expect(Number(blocked.headers.get('retry-after'))).toBeGreaterThan(0);
const blockedHtml = await blocked.text();
expect(blockedHtml).toContain('Too many attempts');
expect(blockedHtml).not.toContain('not-a-real-token-extra');
const otherIp = await app.request('/m/not-a-real-token-other-abcdefghij', { headers: { 'x-test-ip': '203.0.113.91' } });
expect(otherIp.status).toBe(404);
const { app: fresh, shiftId: freshShift } = await buildApp();
const live = await openManage(fresh, freshShift, 'still@example.invalid', ip);
for (let index = 0; index < MANAGE_TOKEN_LIMIT; index += 1) {
expect((await fresh.request(`/m/missing-token-${index}-abcdefghijk`, { headers: { 'x-test-ip': ip } })).status).toBe(404);
}
expect((await fresh.request(live.managePath, { headers: { 'x-test-ip': ip } })).status).toBe(200);
const keys = db.prepare('SELECT key FROM rate_hits').all() as { key: string }[];
const stored = JSON.stringify(keys);
expect(stored).not.toContain('203.0.113.90');
expect(stored).not.toContain('not-a-real-token');
});
});
describe('manage-link switch', () => {
it('switches to another open shift and replaces the private link', async () => {
const { app, db, shiftId } = await buildApp({ capacity: 2 });
const eventId = Number((db.prepare('SELECT id AS id FROM events').get() as { id: number }).id);
const destinationId = insertShift(db, eventId, 'Distribution', '2026-10-17T14:00:00.000Z', '2026-10-17T17:00:00.000Z', 2);
const { managePath } = await openManage(app, shiftId, 'pat.switch@example.invalid', '203.0.113.40');
const signupId = Number((db.prepare('SELECT id AS id FROM signups').get() as { id: number }).id);
db.prepare('UPDATE signups SET attended = 1 WHERE id = ?').run(signupId);
db.prepare(
`INSERT INTO outbox (
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
headers_json, send_after, attempts, status, created_at
) VALUES (?, ?, ?, 'reminder', 'pat.switch@example.invalid', 'Reminder', 'Soon', '<p>Soon</p>', '{}', ?, 0, 'pending', ?)`,
).run(`reminder:${signupId}`, signupId, shiftId, NOW, NOW);
const before = await app.request(managePath);
const html = await before.text();
expect(before.status).toBe(200);
expect(optionValues(html)).toEqual([String(destinationId)]);
expect(html).toContain('>Switch<');
expect(db.prepare('SELECT status, shift_id FROM signups').get()).toEqual({ status: 'confirmed', shift_id: shiftId });
const switched = await postSwitch(app, managePath, html, String(destinationId));
expect(switched.status).toBe(303);
const nextPath = switched.headers.get('location') ?? '';
expect(nextPath.startsWith('/m/')).toBe(true);
expect(nextPath.startsWith(managePath)).toBe(false);
const next = await app.request(nextPath);
const nextHtml = await next.text();
expect(next.status).toBe(200);
expect(nextHtml).toContain('<h2>Distribution</h2>');
expect(nextHtml).toContain('This link replaces the earlier one.');
expect(nextHtml).toContain('Confirmed');
expect(await (await app.request(managePath)).status).toBe(404);
expect(db.prepare('SELECT status, attended, shift_id FROM signups WHERE id = ?').get(signupId)).toEqual({
status: 'cancelled',
attended: 1,
shift_id: shiftId,
});
const created = db.prepare("SELECT status, attended, shift_id FROM signups WHERE status = 'confirmed'").get() as {
status: string;
attended: number | null;
shift_id: number;
};
expect(created).toEqual({ status: 'confirmed', attended: null, shift_id: destinationId });
expect(db.prepare("SELECT status FROM outbox WHERE kind = 'confirmation'").get()).toEqual({ status: 'cancelled' });
expect(db.prepare("SELECT status FROM outbox WHERE kind = 'reminder'").get()).toEqual({ status: 'cancelled' });
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled'").get()).toEqual({ n: 0 });
const letter = db.prepare("SELECT subject, body_text FROM outbox WHERE kind = 'changed'").get() as { subject: string; body_text: string };
expect(letter.subject).toBe('Your signup was switched to Distribution');
expect(letter.body_text).toContain('You switched this signup to a different shift.');
expect(letter.body_text).not.toContain('A coordinator moved');
expect(letter.body_text).toContain(nextPath.split('?')[0]);
const home = await (await app.request('/')).text();
expect(home).not.toContain('pat.switch@example.invalid');
expect(home).not.toContain('Pat Cancel');
expect(home).toContain('0/2 spots filled');
expect(home).toContain('1/2 spots filled');
const again = await postSwitch(app, managePath, html, String(destinationId));
expect(again.status).toBe(200);
expect(await again.text()).toContain('already switched');
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE status = 'confirmed'").get()).toEqual({ n: 1 });
const audit = db.prepare("SELECT coordinator_id, detail_json FROM audit WHERE action = 'signup.switch'").get() as {
coordinator_id: number | null;
detail_json: string;
};
expect(audit.coordinator_id).toBeNull();
expect(audit.detail_json).not.toContain('@');
});
it('switches onto a shift that already has the same email for someone else', async () => {
const { app, db, shiftId } = await buildApp({ capacity: 2 });
const eventId = Number((db.prepare('SELECT id AS id FROM events').get() as { id: number }).id);
const openId = insertShift(db, eventId, 'Distribution', '2026-10-17T14:00:00.000Z', '2026-10-17T17:00:00.000Z', 2);
await openManage(app, openId, 'home.switch@example.invalid', '203.0.113.43');
db.prepare("UPDATE signups SET name = 'Sam Cancel' WHERE email = 'home.switch@example.invalid'").run();
const { managePath } = await openManage(app, shiftId, 'home.switch@example.invalid', '203.0.113.44');
const html = await (await app.request(managePath)).text();
expect(optionValues(html)).toEqual([String(openId)]);
const switched = await postSwitch(app, managePath, html, String(openId));
expect(switched.status).toBe(303);
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE email = 'home.switch@example.invalid' AND shift_id = ? AND status = 'confirmed'").get(openId)).toEqual({ n: 2 });
});
it('keeps the original signup when the switch cannot be saved', async () => {
const { app, db, shiftId } = await buildApp({ capacity: 2 });
const eventId = Number((db.prepare('SELECT id AS id FROM events').get() as { id: number }).id);
const fullId = insertShift(db, eventId, 'Full shift', '2026-10-18T14:00:00.000Z', '2026-10-18T17:00:00.000Z', 1);
const openId = insertShift(db, eventId, 'Distribution', '2026-10-17T14:00:00.000Z', '2026-10-17T17:00:00.000Z', 2);
const endedId = insertShift(db, eventId, 'Morning', '2026-10-14T14:00:00.000Z', '2026-10-14T17:00:00.000Z', 2);
const otherEvent = Number(
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES ('other', 'Other', '', 'Sioux Center, Iowa', 'America/Chicago', 1, ?)`,
).run(NOW).lastInsertRowid,
);
const otherShift = insertShift(db, otherEvent, 'Elsewhere', '2026-10-19T14:00:00.000Z', '2026-10-19T17:00:00.000Z', 2);
await openManage(app, fullId, 'dee.switch@example.invalid', '203.0.113.41');
const { managePath } = await openManage(app, shiftId, 'ria.switch@example.invalid', '203.0.113.42');
const html = await (await app.request(managePath)).text();
expect(optionValues(html)).toEqual([String(openId)]);
const full = await postSwitch(app, managePath, html, String(fullId));
expect(full.status).toBe(400);
expect(await full.text()).toContain('That shift is full.');
const ended = await postSwitch(app, managePath, html, String(endedId));
expect(ended.status).toBe(400);
expect(await ended.text()).toContain('That shift is closed.');
const elsewhere = await postSwitch(app, managePath, html, String(otherShift));
expect(elsewhere.status).toBe(400);
expect(await elsewhere.text()).toContain('Choose a shift in this event.');
db.prepare('UPDATE events SET published = 0 WHERE id = ?').run(eventId);
const hidden = await postSwitch(app, managePath, html, String(openId));
expect(hidden.status).toBe(400);
expect(await hidden.text()).toContain('That shift is not available.');
const wrong = await postSwitch(app, managePath, html.replace(/name="switch_token" value="[^"]*"/, 'name="switch_token" value="not-a-switch-token-value"'), String(openId));
expect(wrong.status).toBe(400);
expect(await wrong.text()).toContain('could not be confirmed');
const cancelToken = html.match(/name="cancel_token" value="([^"]+)"/)?.[1] ?? '';
const reused = await postSwitch(app, managePath, html.replace(/name="switch_token" value="[^"]*"/, `name="switch_token" value="${cancelToken}"`), String(openId));
expect(reused.status).toBe(400);
const crossSite = await postSwitch(app, managePath, html, String(openId), { origin: 'https://evil.example' });
expect(crossSite.status).toBe(403);
expect(db.prepare("SELECT status, shift_id FROM signups WHERE email = 'ria.switch@example.invalid'").get()).toEqual({
status: 'confirmed',
shift_id: shiftId,
});
expect(db.prepare("SELECT status FROM outbox WHERE to_email = 'ria.switch@example.invalid' AND kind = 'confirmation'").get()).toEqual({
status: 'pending',
});
expect(db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action = 'signup.switch'").get()).toEqual({ n: 0 });
});
});
async function buildApp(options?: { capacity?: number }) {
const root = mkdtempSync(path.join(tmpdir(), 'hope-cancel-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
const eventId = Number(
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES ('weekly-pantry', 'Weekly pantry', 'Bring a hat.', 'Sioux Center, Iowa', 'America/Chicago', 1, ?)`,
).run(NOW).lastInsertRowid,
);
const shiftId = Number(
db.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, 'Sorting', '2026-10-15T14:00:00.000Z', '2026-10-15T17:00:00.000Z', ?, '', 0)`,
).run(eventId, options?.capacity ?? 3).lastInsertRowid,
);
const app = createApp(config, db, {
now: NOW,
clientIp: (c) => c.req.header('x-test-ip') ?? null,
verifyTurnstile: async () => ({ ok: true }),
});
return { app, db, shiftId };
}
async function openManage(app: ReturnType<typeof createApp>, shiftId: number, email: string, ip: string) {
const saved = await postSignup(app, shiftId, { name: 'Pat Cancel', email }, ip);
const confirmed = await app.request(saved.headers.get('location') ?? '', {
headers: { cookie: (saved.headers.get('set-cookie') ?? '').split(';')[0] ?? '' },
});
const confirmedHtml = await confirmed.text();
const managePath = confirmedHtml.match(/href="(\/m\/[^"]+)"/)?.[1] ?? '';
const manage = await app.request(managePath);
const html = await manage.text();
const token = html.match(/name="cancel_token" value="([^"]+)"/)?.[1] ?? '';
expect(managePath.length).toBeGreaterThan(20);
expect(token).not.toBe(managePath.slice(3));
expect(html).not.toContain('challenges.cloudflare.com');
return { managePath, token };
}
async function postSignup(
app: ReturnType<typeof createApp>,
shiftId: number,
fields: { name: string; email: string },
ip: string,
) {
const body = new URLSearchParams({
form_token: issueFormToken(SECRET, {
shiftId,
issuedAt: NOW_MS - 10_000,
operationId: randomBytes(16).toString('hex'),
}),
name: fields.name,
email: fields.email,
phone: '',
notes: '',
guardianName: '',
guardianEmail: '',
company_website: '',
'cf-turnstile-response': 'widget-token',
});
return app.request(`/s/${shiftId}`, {
method: 'POST',
headers: {
origin: 'http://127.0.0.1:3000',
'content-type': 'application/x-www-form-urlencoded',
'x-test-ip': ip,
},
body,
});
}
function insertShift(db: Awaited<ReturnType<typeof buildApp>>['db'], eventId: number, role: string, starts: string, ends: string, capacity: number) {
return Number(
db.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, ?, ?, ?, ?, '', 0)`,
).run(eventId, role, starts, ends, capacity).lastInsertRowid,
);
}
function optionValues(html: string): string[] {
const select = /<select\b[^>]*\bname="destination"[^>]*>([\s\S]*?)<\/select>/.exec(html)?.[1] ?? '';
return [...select.matchAll(/value="(\d+)"/g)].map((match) => match[1] ?? '');
}
function postSwitch(
app: ReturnType<typeof createApp>,
managePath: string,
html: string,
destination: string,
options?: { origin?: string },
) {
return app.request(`${managePath}/switch`, {
method: 'POST',
headers: {
origin: options?.origin ?? 'http://127.0.0.1:3000',
'content-type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
switch_token: field(html, 'switch_token'),
form_token: field(html, 'form_token'),
destination,
}),
});
}
function field(html: string, name: string): string {
const tag = new RegExp(`<input\\b[^>]*\\bname="${name}"[^>]*>`).exec(html)?.[0] ?? '';
return /value="([^"]*)"/.exec(tag)?.[1] ?? '';
}
function postCancel(
app: ReturnType<typeof createApp>,
managePath: string,
token: string,
options?: { origin?: string; site?: string; ip?: string },
) {
const body = new URLSearchParams();
if (token) body.set('cancel_token', token);
return app.request(managePath, {
method: 'POST',
headers: {
origin: options?.origin ?? 'http://127.0.0.1:3000',
'content-type': 'application/x-www-form-urlencoded',
'x-test-ip': options?.ip ?? '203.0.113.70',
...(options?.site ? { 'sec-fetch-site': options.site } : {}),
},
body,
});
}
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest';
import { clientAddress, parseTrustProxy } from '../src/client-ip.js';
describe('client address', () => {
const disabled = parseTrustProxy('false');
const loopback = parseTrustProxy('loopback');
const bridge = parseTrustProxy('172.18.0.1');
it('ignores a spoofed forwarding header when the proxy is not trusted', () => {
expect(clientAddress(disabled, '203.0.113.5', '198.51.100.5')).toBe('203.0.113.5');
expect(clientAddress(loopback, '203.0.113.5', '198.51.100.8')).toBe('203.0.113.5');
expect(clientAddress(bridge, '172.18.0.2', '203.0.113.9')).toBe('172.18.0.2');
});
it('uses one forwarding header from a trusted peer', () => {
expect(clientAddress(loopback, '127.0.0.1', '203.0.113.9')).toBe('203.0.113.9');
expect(clientAddress(loopback, '::ffff:127.0.0.1', '203.0.113.9')).toBe('203.0.113.9');
expect(clientAddress(bridge, '172.18.0.1', '203.0.113.10')).toBe('203.0.113.10');
});
it('does not trust a list of forwarded addresses', () => {
expect(clientAddress(loopback, '127.0.0.1', '198.51.100.8, 203.0.113.9')).toBe('127.0.0.1');
});
it('falls back to the peer when the header is not a single IP', () => {
expect(clientAddress(loopback, '127.0.0.1', 'not-an-ip')).toBe('127.0.0.1');
expect(clientAddress(loopback, '127.0.0.1', '')).toBe('127.0.0.1');
});
it('treats a 10/8 network as one trusted source and rejects a worldwide prefix', () => {
const ten = parseTrustProxy('10.0.0.0/8');
expect(clientAddress(ten, '10.1.2.3', '203.0.113.4')).toBe('203.0.113.4');
expect(clientAddress(ten, '11.0.0.1', '203.0.113.4')).toBe('11.0.0.1');
expect(() => parseTrustProxy('0.0.0.0/0')).toThrow(/8 through 32/);
});
});
+168
View File
@@ -0,0 +1,168 @@
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { isTurnstileTestKey, loadConfig } from '../src/config.js';
import { devEnv, productionEnv } from './env.js';
const projectRoot = path.resolve(import.meta.dirname, '..');
describe('loadConfig', () => {
it('accepts the development example shape', () => {
const config = loadConfig(devEnv());
expect(config.nodeEnv).toBe('development');
expect(config.baseUrl).toBe('http://127.0.0.1:3000');
expect(config.basePath).toBe('');
expect(config.secureCookies).toBe(false);
expect(config.mail.driver).toBe('console');
expect(config.mail.from).toBe('Hope Food Pantry <volunteer@example.invalid>');
expect(config.mail.replyTo).toBe('volunteer@example.invalid');
expect(config.defaultTimeZone).toBe('America/Chicago');
expect(config.trustProxy).toEqual({ mode: 'disabled' });
expect(config.databaseFile.endsWith(`${path.sep}app.db`)).toBe(true);
});
it('normalizes a volunteer mount prefix', () => {
const config = loadConfig(devEnv({ BASE_PATH: '/volunteer/' }));
expect(config.basePath).toBe('/volunteer');
});
it('rejects a path on BASE_URL', () => {
expect(() => loadConfig(devEnv({ BASE_URL: 'http://127.0.0.1:3000/volunteer' }))).toThrow(/BASE_PATH/);
});
it('rejects a prefix that does not start with a slash', () => {
expect(() => loadConfig(devEnv({ BASE_PATH: 'volunteer' }))).toThrow(/BASE_PATH/);
});
it('rejects a prefix that climbs out of the mount', () => {
expect(() => loadConfig(devEnv({ BASE_PATH: '/volunteer/../admin' }))).toThrow(/BASE_PATH/);
});
it('requires NODE_ENV', () => {
const env = devEnv();
delete env.NODE_ENV;
expect(() => loadConfig(env)).toThrow(/NODE_ENV/);
});
it('rejects an unknown time zone', () => {
expect(() => loadConfig(devEnv({ DEFAULT_TZ: 'Not/AZone' }))).toThrow(/time zone/i);
});
it('rejects a line break in the from address', () => {
expect(() => loadConfig(devEnv({ MAIL_FROM: 'Hope\r\nBcc: x <a@example.invalid>' }))).toThrow(/MAIL_FROM/);
});
it('accepts a production configuration with real-looking keys', () => {
const config = loadConfig(productionEnv('/tmp/hope-data'));
expect(config.secureCookies).toBe(true);
expect(config.mail.driver).toBe('postmark');
expect(config.mail.postmarkToken).toBe('pm-server-token-9f3a2c1e5b8d4f70');
expect(config.baseUrl).toBe('https://volunteer.example.org');
});
it('rejects console mail, test keys, http, and the example secret in production', () => {
expect(() => loadConfig(productionEnv('/tmp/hope-data', { MAIL_DRIVER: 'console' }))).toThrow(/console/);
expect(() =>
loadConfig(productionEnv('/tmp/hope-data', { TURNSTILE_SITE_KEY: '1x00000000000000000000AA' })),
).toThrow(/test key/i);
expect(() => loadConfig(productionEnv('/tmp/hope-data', { BASE_URL: 'http://volunteer.example.org' }))).toThrow(
/https/,
);
expect(() =>
loadConfig(
productionEnv('/tmp/hope-data', { SESSION_SECRET: 'dev-only-change-me-not-for-production-use' }),
),
).toThrow(/SESSION_SECRET/);
expect(() =>
loadConfig(productionEnv('/tmp/hope-data', { SESSION_SECRET: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' })),
).toThrow(/random enough/);
});
it('requires credentials for the selected mail driver', () => {
expect(() => loadConfig(devEnv({ MAIL_DRIVER: 'postmark', POSTMARK_TOKEN: '' }))).toThrow(/POSTMARK_TOKEN/);
expect(() =>
loadConfig(
productionEnv('/tmp/hope-data', {
MAIL_DRIVER: 'ses',
SES_REGION: 'us-east-1',
SES_ACCESS_KEY_ID: '',
SES_SECRET_ACCESS_KEY: '',
}),
),
).toThrow(/SES_ACCESS_KEY_ID/);
});
it('rejects TRUST_PROXY=true', () => {
expect(() => loadConfig(devEnv({ TRUST_PROXY: 'true' }))).toThrow(/cannot be true/);
});
it('accepts a named proxy address', () => {
const config = loadConfig(devEnv({ TRUST_PROXY: 'loopback, 172.18.0.1' }));
expect(config.trustProxy.mode).toBe('list');
});
it('listens on localhost unless Docker asks for every interface', () => {
expect(loadConfig(devEnv()).bindHost).toBe('127.0.0.1');
expect(loadConfig(devEnv({ BIND_HOST: '0.0.0.0' })).bindHost).toBe('0.0.0.0');
expect(() => loadConfig(devEnv({ BIND_HOST: '10.1.2.3' }))).toThrow(/BIND_HOST/);
});
it('loads .env.example as development and refuses that file for production', () => {
const script = `console.log(JSON.stringify({
NODE_ENV: process.env.NODE_ENV,
PORT: process.env.PORT,
BASE_URL: process.env.BASE_URL,
BASE_PATH: process.env.BASE_PATH,
DATA_DIR: process.env.DATA_DIR,
SESSION_SECRET: process.env.SESSION_SECRET,
DEFAULT_TZ: process.env.DEFAULT_TZ,
MAIL_DRIVER: process.env.MAIL_DRIVER,
MAIL_FROM: process.env.MAIL_FROM,
MAIL_REPLY_TO: process.env.MAIL_REPLY_TO,
POSTMARK_TOKEN: process.env.POSTMARK_TOKEN ?? '',
SES_REGION: process.env.SES_REGION ?? '',
SES_ACCESS_KEY_ID: process.env.SES_ACCESS_KEY_ID ?? '',
SES_SECRET_ACCESS_KEY: process.env.SES_SECRET_ACCESS_KEY ?? '',
TURNSTILE_SITE_KEY: process.env.TURNSTILE_SITE_KEY,
TURNSTILE_SECRET_KEY: process.env.TURNSTILE_SECRET_KEY,
BRAND_SRC: process.env.BRAND_SRC,
BOOTSTRAP_ADMIN_EMAIL: process.env.BOOTSTRAP_ADMIN_EMAIL,
TRUST_PROXY: process.env.TRUST_PROXY,
BIND_HOST: process.env.BIND_HOST
}))`;
const result = spawnSync(process.execPath, ['--env-file=.env.example', '-e', script], {
cwd: projectRoot,
encoding: 'utf8',
env: { PATH: process.env.PATH ?? '' },
});
expect(result.status, result.stderr).toBe(0);
const parsed = JSON.parse(result.stdout) as NodeJS.ProcessEnv;
const config = loadConfig(parsed);
expect(config.basePath).toBe('');
expect(config.mail.driver).toBe('console');
expect(config.trustProxy).toEqual({ mode: 'disabled' });
expect(config.bindHost).toBe('127.0.0.1');
expect(config.turnstile.siteKey).toBe('1x00000000000000000000AA');
expect(config.brandSrc).toBe('../Hope Food Pantry Website/brand');
expect(config.bootstrapAdminEmail).toBe('coordinator@example.invalid');
let message = '';
try {
loadConfig({ ...parsed, NODE_ENV: 'production' });
} catch (err) {
message = err instanceof Error ? err.message : String(err);
}
expect(message).toMatch(/console/);
expect(message).toMatch(/test key/i);
expect(message).toMatch(/SESSION_SECRET/);
expect(message).toMatch(/https/);
});
});
describe('isTurnstileTestKey', () => {
it('recognizes the documented dummy keys and not a production-shaped key', () => {
expect(isTurnstileTestKey('1x00000000000000000000AA')).toBe(true);
expect(isTurnstileTestKey('2x0000000000000000000000000000000AA')).toBe(true);
expect(isTurnstileTestKey('3x0000000000000000000000000000000AA')).toBe(true);
expect(isTurnstileTestKey('0x4AAAAAAA8k2mRealishSiteKey00')).toBe(false);
});
});
+180
View File
@@ -0,0 +1,180 @@
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { Temporal } from '@js-temporal/polyfill';
import { afterEach, describe, expect, it } from 'vitest';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { runDueTemplateExpansion, startDailyExpansionRunner } from '../src/jobs/daily-expand.js';
import { formatUtc } from '../src/time.js';
import { devEnv } from './env.js';
const CHICAGO = 'America/Chicago';
const HONOLULU = 'Pacific/Honolulu';
const BEFORE = '2026-01-15T06:30:00.000Z';
const AT_ONE = '2026-01-15T07:00:00.000Z';
const NEXT_WEEK = '2026-01-22T07:00:00.000Z';
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('daily weekly refill', () => {
it('waits for 1:00 in that event time zone and does not refill a zone that is still earlier', async () => {
const db = await openDb();
const chicago = insertEvent(db, 'chicago', CHICAGO);
const honolulu = insertEvent(db, 'honolulu', HONOLULU);
insertTemplate(db, chicago, 4, '2026-01-15');
insertTemplate(db, honolulu, 3, '2026-01-14');
const ended = insertEvent(db, 'ended', CHICAGO);
insertTemplate(db, ended, 4, '2026-01-15', 0);
expect(runDueTemplateExpansion(db, BEFORE)).toEqual({ zones: [HONOLULU], created: 9, skipped: [] });
expect(shiftCount(db, chicago)).toBe(0);
expect(shiftCount(db, honolulu)).toBe(9);
expect(shiftCount(db, ended)).toBe(0);
expect(marks(db)).toEqual([{ scope: HONOLULU, local_date: '2026-01-14' }]);
expect(runDueTemplateExpansion(db, AT_ONE).zones).toEqual([CHICAGO]);
expect(shiftCount(db, chicago)).toBe(9);
expect(shiftCount(db, honolulu)).toBe(9);
expect(shiftCount(db, ended)).toBe(0);
expect(runDueTemplateExpansion(db, AT_ONE)).toEqual({ zones: [], created: 0, skipped: [] });
expect(marks(db)).toEqual([
{ scope: CHICAGO, local_date: '2026-01-15' },
{ scope: HONOLULU, local_date: '2026-01-14' },
]);
});
it('adds the next week after the window moves, and leaves a cancelled date alone', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'chicago', CHICAGO);
const templateId = insertTemplate(db, eventId, 4, '2026-01-15');
db.prepare(
`INSERT INTO shifts (
event_id, template_id, occurrence_date, template_revision, role,
starts_at_utc, ends_at_utc, capacity, notes, cancelled, manually_modified, version
) VALUES (?, ?, '2026-01-15', 1, 'Kept', '2026-01-15T15:00:00.000Z', '2026-01-15T18:00:00.000Z', 2, '', 1, 1, 1)`,
).run(eventId, templateId);
runDueTemplateExpansion(db, AT_ONE);
const kept = db.prepare(`SELECT role AS role, cancelled AS cancelled FROM shifts WHERE occurrence_date = '2026-01-15'`).get();
expect(kept).toEqual({ role: 'Kept', cancelled: 1 });
expect(lastDate(db, eventId)).toBe('2026-03-12');
runDueTemplateExpansion(db, NEXT_WEEK);
expect(lastDate(db, eventId)).toBe('2026-03-19');
expect(shiftCount(db, eventId)).toBe(10);
expect(db.prepare(`SELECT detail_json AS detail_json FROM audit`).all().map((row) => (row as { detail_json: string }).detail_json).join(' ')).not.toContain('@');
});
it('runs once when 1:00 happens twice, and still runs when 1:00 does not exist', async () => {
const repeated = await openDb();
const chicago = insertEvent(repeated, 'chicago', CHICAGO);
insertTemplate(repeated, chicago, 0, '2026-11-01');
const firstHour = localUtc(CHICAGO, '2026-11-01', 1, 0, 'earlier');
const secondHour = localUtc(CHICAGO, '2026-11-01', 1, 30, 'later');
const before = localUtc(CHICAGO, '2026-11-01', 0, 30, 'reject');
expect(runDueTemplateExpansion(repeated, before).zones).toEqual([]);
const first = runDueTemplateExpansion(repeated, firstHour);
expect(first.created).toBeGreaterThan(0);
expect(runDueTemplateExpansion(repeated, secondHour)).toEqual({ zones: [], created: 0, skipped: [] });
expect(marks(repeated)).toEqual([{ scope: CHICAGO, local_date: '2026-11-01' }]);
const gap = await openDb();
const troll = insertEvent(gap, 'troll', 'Antarctica/Troll');
insertTemplate(gap, troll, 0, '2026-03-29');
expect(runDueTemplateExpansion(gap, '2026-03-29T00:30:00.000Z').zones).toEqual([]);
expect(runDueTemplateExpansion(gap, '2026-03-29T01:00:00.000Z').zones).toEqual(['Antarctica/Troll']);
expect(shiftCount(gap, troll)).toBeGreaterThan(0);
expect(runDueTemplateExpansion(gap, '2026-03-29T02:00:00.000Z')).toEqual({ zones: [], created: 0, skipped: [] });
});
it('skips a time zone it cannot read and still fills the others', async () => {
const db = await openDb();
const broken = insertEvent(db, 'broken', 'Not/AZone');
insertTemplate(db, broken, 4, '2026-01-15');
const chicago = insertEvent(db, 'chicago', CHICAGO);
insertTemplate(db, chicago, 4, '2026-01-15');
const errors: string[] = [];
const write = console.error;
console.error = (message?: unknown) => {
errors.push(String(message));
};
try {
expect(runDueTemplateExpansion(db, AT_ONE).zones).toEqual([CHICAGO]);
} finally {
console.error = write;
}
expect(shiftCount(db, chicago)).toBe(9);
expect(shiftCount(db, broken)).toBe(0);
expect(marks(db).map((row) => row.scope)).toEqual([CHICAGO]);
expect(errors.join(' ')).toContain('Not/AZone');
expect(errors.join(' ')).not.toContain('@');
});
it('fills due zones on the first check', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'chicago', CHICAGO);
insertTemplate(db, eventId, 4, '2026-01-15');
const runner = startDailyExpansionRunner(db, () => AT_ONE);
expect(shiftCount(db, eventId)).toBe(9);
runner.stop();
expect(shiftCount(db, eventId)).toBe(9);
});
});
function localUtc(zone: string, date: string, hour: number, minute: number, disambiguation: 'earlier' | 'later' | 'reject'): string {
const [year, month, day] = date.split('-').map(Number);
const zoned = Temporal.ZonedDateTime.from(
{ timeZone: zone, year, month, day, hour, minute, second: 0, millisecond: 0 },
{ disambiguation },
);
return formatUtc(zoned.toInstant());
}
async function openDb() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-refill-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
return db;
}
function insertEvent(db: Awaited<ReturnType<typeof openDb>>, slug: string, tz: string): number {
return Number(
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES (?, ?, '', 'Sioux Center, Iowa', ?, 1, ?)`,
).run(slug, slug, tz, AT_ONE).lastInsertRowid,
);
}
function insertTemplate(db: Awaited<ReturnType<typeof openDb>>, eventId: number, weekday: number, startsOn: string, active = 1): number {
return Number(
db.prepare(
`INSERT INTO shift_templates (
event_id, role, weekday, start_local, end_local, capacity, starts_on, ends_on, active, revision
) VALUES (?, 'Sorting', ?, '09:00', '12:00', 6, ?, NULL, ?, 1)`,
).run(eventId, weekday, startsOn, active).lastInsertRowid,
);
}
function shiftCount(db: Awaited<ReturnType<typeof openDb>>, eventId: number): number {
return Number((db.prepare('SELECT COUNT(*) AS n FROM shifts WHERE event_id = ?').get(eventId) as { n: number }).n);
}
function lastDate(db: Awaited<ReturnType<typeof openDb>>, eventId: number): string {
return (db.prepare('SELECT MAX(occurrence_date) AS d FROM shifts WHERE event_id = ?').get(eventId) as { d: string }).d;
}
function marks(db: Awaited<ReturnType<typeof openDb>>): Array<{ scope: string; local_date: string }> {
return db.prepare('SELECT scope AS scope, local_date AS local_date FROM job_runs ORDER BY scope, local_date').all() as Array<{
scope: string;
local_date: string;
}>;
}
+403
View File
@@ -0,0 +1,403 @@
import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
import { afterEach, describe, expect, it } from 'vitest';
import { loadConfig } from '../src/config.js';
import {
applyMigrations,
defaultMigrationsDir,
openAppDatabase,
openDatabaseFile,
} from '../src/db.js';
import { devEnv, productionEnv } from './env.js';
const dirs: string[] = [];
const INSTANT = '2026-10-20T14:00:00.000Z';
const LATER = '2026-10-20T17:00:00.000Z';
function makeDir(): string {
const dir = mkdtempSync(path.join(tmpdir(), 'hope-volunteer-'));
dirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
describe('database startup', () => {
it('applies the real schema once, in WAL mode, with foreign keys on', async () => {
const dataDir = path.join(makeDir(), 'data');
const config = loadConfig(devEnv({ DATA_DIR: dataDir }));
const db = await openAppDatabase(config);
try {
expect(db.pragma('journal_mode', { simple: true })).toBe('wal');
expect(db.pragma('foreign_keys', { simple: true })).toBe(1);
const names = (
db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all() as {
name: string;
}[]
)
.map((row) => row.name)
.sort();
expect(names).toEqual(
[
'audit',
'coordinators',
'events',
'job_runs',
'login_tokens',
'outbox',
'rate_hits',
'reminders_sent',
'schema_migrations',
'sessions',
'settings',
'shift_templates',
'shifts',
'signups',
].sort(),
);
const first = db.prepare('SELECT name, checksum, applied_at FROM schema_migrations').get();
const again = await applyMigrations(db, { migrationsDir: defaultMigrationsDir() });
expect(again.applied).toEqual([]);
expect(db.prepare('SELECT name, checksum, applied_at FROM schema_migrations').get()).toEqual(first);
} finally {
db.close();
}
});
it('backs up an existing production database before a new migration and not before the first one', async () => {
const root = makeDir();
const migrations = path.join(root, 'migrations');
const dataDir = path.join(root, 'data');
mkdirSync(migrations);
copyFileSync(path.join(defaultMigrationsDir(), '001_init.sql'), path.join(migrations, '001_init.sql'));
const config = loadConfig(productionEnv(dataDir));
const first = await openAppDatabase(config, { migrationsDir: migrations });
first.close();
expect(readdirSync(dataDir).includes('backups')).toBe(false);
writeFileSync(
path.join(migrations, '002_probe.sql'),
`INSERT INTO settings (key, value_json, updated_at) VALUES ('probe', '"ok"', '${INSTANT}');\n`,
);
const second = await openAppDatabase(config, { migrationsDir: migrations });
try {
expect(second.prepare(`SELECT value_json FROM settings WHERE key = 'probe'`).get()).toEqual({
value_json: '"ok"',
});
const backups = readdirSync(path.join(dataDir, 'backups'));
expect(backups.some((name) => name.startsWith('pre-migrate-') && name.endsWith('.db'))).toBe(true);
const backupName = backups.find((name) => name.startsWith('pre-migrate-'));
if (!backupName) throw new Error('missing backup');
const backup = new Database(path.join(dataDir, 'backups', backupName), { readonly: true, fileMustExist: true });
try {
expect(backup.pragma('journal_mode', { simple: true })).toBe('delete');
expect(backup.pragma('integrity_check', { simple: true })).toBe('ok');
expect(backup.prepare(`SELECT COUNT(*) AS n FROM settings WHERE key = 'probe'`).get()).toEqual({ n: 0 });
expect(backup.prepare(`SELECT COUNT(*) AS n FROM events`).get()).toEqual({ n: 0 });
} finally {
backup.close();
}
} finally {
second.close();
}
});
it('does not apply a migration when the pre-migration backup fails', async () => {
const root = makeDir();
const migrations = path.join(root, 'migrations');
mkdirSync(migrations);
writeFileSync(path.join(migrations, '001_init.sql'), 'CREATE TABLE marker (id INTEGER PRIMARY KEY);\n');
const db = openDatabaseFile(path.join(root, 'app.db'));
try {
await applyMigrations(db, { migrationsDir: migrations });
writeFileSync(path.join(migrations, '002_next.sql'), 'CREATE TABLE extra (id INTEGER PRIMARY KEY);\n');
await expect(
applyMigrations(db, {
migrationsDir: migrations,
backupBeforePending: async () => {
throw new Error('disk full');
},
}),
).rejects.toThrow(/backup failed/i);
expect(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'extra'").get()).toBeUndefined();
expect(db.prepare('SELECT name FROM schema_migrations').all()).toEqual([{ name: '001_init.sql' }]);
} finally {
db.close();
}
});
it('stops startup when an applied migration file changes', async () => {
const root = makeDir();
const migrations = path.join(root, 'migrations');
mkdirSync(migrations);
const file = path.join(migrations, '001_init.sql');
writeFileSync(file, 'CREATE TABLE marker (id INTEGER PRIMARY KEY);\n');
const db = openDatabaseFile(path.join(root, 'app.db'));
try {
await applyMigrations(db, { migrationsDir: migrations });
writeFileSync(file, 'CREATE TABLE marker (id INTEGER PRIMARY KEY);\nCREATE TABLE extra (id INTEGER PRIMARY KEY);\n');
await expect(applyMigrations(db, { migrationsDir: migrations })).rejects.toThrow(/changed after it was applied/);
expect(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'extra'").get()).toBeUndefined();
} finally {
db.close();
}
});
it('rolls back a bad migration and names the file', async () => {
const root = makeDir();
const migrations = path.join(root, 'migrations');
mkdirSync(migrations);
writeFileSync(path.join(migrations, '001_init.sql'), 'CREATE TABLE marker (id INTEGER PRIMARY KEY);\n');
writeFileSync(path.join(migrations, '002_bad.sql'), 'CREATE TABLE (\n');
const db = openDatabaseFile(path.join(root, 'app.db'));
try {
await expect(applyMigrations(db, { migrationsDir: migrations })).rejects.toThrow(/002_bad\.sql/);
expect(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'marker'").get()).toEqual({
name: 'marker',
});
expect(db.prepare('SELECT name FROM schema_migrations').all()).toEqual([{ name: '001_init.sql' }]);
} finally {
db.close();
}
});
it('rejects duplicate numbers, unnamed files, and a connection without foreign keys', async () => {
const root = makeDir();
const migrations = path.join(root, 'migrations');
mkdirSync(migrations);
writeFileSync(path.join(migrations, '001_a.sql'), 'CREATE TABLE a (id INTEGER PRIMARY KEY);\n');
writeFileSync(path.join(migrations, '001_b.sql'), 'CREATE TABLE b (id INTEGER PRIMARY KEY);\n');
const db = openDatabaseFile(path.join(root, 'app.db'));
try {
await expect(applyMigrations(db, { migrationsDir: migrations })).rejects.toThrow(/Duplicate migration number 001/);
} finally {
db.close();
}
const raw = new Database(path.join(root, 'raw.db'));
raw.pragma('foreign_keys = OFF');
try {
await expect(applyMigrations(raw, { migrationsDir: migrations })).rejects.toThrow(/foreign_keys/);
} finally {
raw.close();
}
const loose = path.join(root, 'loose');
mkdirSync(loose);
writeFileSync(path.join(loose, 'notes.sql'), 'SELECT 1;\n');
const other = openDatabaseFile(path.join(root, 'other.db'));
try {
await expect(applyMigrations(other, { migrationsDir: loose })).rejects.toThrow(/notes\.sql/);
} finally {
other.close();
}
});
});
describe('signup and shift constraints', () => {
it('enforces capacity, individual signups, duplicates, anonymization, and history', async () => {
const dataDir = path.join(makeDir(), 'data');
const db = await openAppDatabase(loadConfig(devEnv({ DATA_DIR: dataDir })));
try {
const parents = insertParents(db);
expect(() =>
db.prepare(`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity) VALUES (?, 'Sorting', ?, ?, 0)`).run(
parents.eventId,
INSTANT,
LATER,
),
).toThrow(/CHECK/);
expect(() =>
db
.prepare(`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity) VALUES (?, 'Sorting', ?, ?, 1)`)
.run(parents.eventId, LATER, INSTANT),
).toThrow(/CHECK/);
expect(() =>
db
.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity) VALUES (?, 'Sorting', '2026-10-20T14:00:00Z', ?, 1)`,
)
.run(parents.eventId, LATER),
).toThrow(/CHECK/);
insertSignup(db, parents.shiftId, { email: 'Ada@Example.invalid', emailNorm: 'ada@example.invalid' });
expect(() =>
insertSignup(db, parents.shiftId, { email: 'ada@example.invalid', emailNorm: 'ada@example.invalid' }),
).toThrow(/UNIQUE/);
expect(() =>
insertSignup(db, parents.shiftId, { name: 'fake person', email: 'ada@example.invalid', emailNorm: 'ada@example.invalid' }),
).toThrow(/UNIQUE/);
insertSignup(db, parents.shiftId, { name: 'Other Person', email: 'ada@example.invalid', emailNorm: 'ada@example.invalid' });
const otherShift = insertShift(db, parents.eventId);
insertSignup(db, otherShift, { email: 'ada@example.invalid', emailNorm: 'ada@example.invalid' });
insertSignup(db, parents.shiftId, {
email: 'ada@example.invalid',
emailNorm: 'ada@example.invalid',
status: 'cancelled',
});
insertSignup(db, parents.shiftId, {
email: 'ada@example.invalid',
emailNorm: 'ada@example.invalid',
status: 'cancelled',
});
expect(() =>
insertSignup(db, parents.shiftId, { email: 'ben@example.invalid', emailNorm: 'ben@example.invalid', groupSize: 2 }),
).toThrow(/CHECK/);
expect(() =>
insertSignup(db, parents.shiftId, {
email: 'min@example.invalid',
emailNorm: 'min@example.invalid',
isMinor: 1,
}),
).toThrow(/CHECK/);
insertSignup(db, parents.shiftId, {
email: 'min@example.invalid',
emailNorm: 'min@example.invalid',
isMinor: 1,
guardianName: 'Guardian Pat',
guardianEmail: 'pat@example.invalid',
});
expect(() =>
insertSignup(db, parents.shiftId, { email: 'Up@Example.invalid', emailNorm: 'Up@Example.invalid' }),
).toThrow(/CHECK/);
insertAnonymized(db, parents.shiftId);
insertAnonymized(db, parents.shiftId);
expect(() =>
db
.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, is_minor, group_size, status, reminders_off, created_at, updated_at, anonymized_at
) VALUES (?, 'Still Named', NULL, NULL, 0, 1, 'confirmed', 0, ?, ?, ?)`,
)
.run(parents.shiftId, INSTANT, INSTANT, INSTANT),
).toThrow(/CHECK/);
expect(() => db.prepare('DELETE FROM shifts WHERE id = ?').run(parents.shiftId)).toThrow(/FOREIGN KEY/);
expect(() => db.prepare('INSERT INTO signups (shift_id, name, email, email_norm, group_size, status, created_at, updated_at) VALUES (999999, ?, ?, ?, 1, ?, ?, ?)').run(
'Nope',
'nope@example.invalid',
'nope@example.invalid',
'confirmed',
INSTANT,
INSTANT,
)).toThrow(/FOREIGN KEY/);
db.prepare(
`INSERT INTO shifts (
event_id, template_id, occurrence_date, template_revision, role, starts_at_utc, ends_at_utc, capacity, cancelled
) VALUES (?, ?, '2026-10-27', 1, 'Sorting', ?, ?, 3, 1)`,
).run(parents.eventId, parents.templateId, INSTANT, LATER);
expect(() =>
db
.prepare(
`INSERT INTO shifts (
event_id, template_id, occurrence_date, template_revision, role, starts_at_utc, ends_at_utc, capacity, cancelled
) VALUES (?, ?, '2026-10-27', 1, 'Sorting', ?, ?, 3, 0)`,
)
.run(parents.eventId, parents.templateId, INSTANT, LATER),
).toThrow(/UNIQUE/);
const coordinator = db
.prepare(`INSERT INTO coordinators (email, name, role, created_at) VALUES ('ada@example.invalid', 'Ada', 'admin', ?)`)
.run(INSTANT);
db.prepare(`INSERT INTO audit (coordinator_id, action, detail_json, at) VALUES (?, 'test', '{}', ?)`).run(
coordinator.lastInsertRowid,
INSTANT,
);
expect(() => db.prepare('DELETE FROM coordinators WHERE id = ?').run(coordinator.lastInsertRowid)).toThrow(
/FOREIGN KEY/,
);
expect(() => db.prepare(`INSERT INTO settings (key, value_json, updated_at) VALUES ('bad', '{', ?)`).run(INSTANT)).toThrow(
/CHECK/,
);
db.prepare(`INSERT INTO settings (key, value_json, updated_at) VALUES ('good', '{}', ?)`).run(INSTANT);
const realSql = readFileSync(path.join(defaultMigrationsDir(), '001_init.sql'), 'utf8');
expect(realSql).toContain('TODO(D2)');
expect(realSql).not.toMatch(/ON DELETE CASCADE/i);
} finally {
db.close();
}
});
});
function insertParents(db: Database.Database): { eventId: number; templateId: number; shiftId: number } {
const event = db
.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES ('weekly-pantry', 'Weekly pantry', '', 'Sioux Center, Iowa', 'America/Chicago', 1, ?)`,
)
.run(INSTANT);
const template = db
.prepare(
`INSERT INTO shift_templates (
event_id, role, weekday, start_local, end_local, capacity, starts_on, active, revision
) VALUES (?, 'Sorting', 2, '09:00', '12:00', 4, '2026-10-13', 1, 1)`,
)
.run(event.lastInsertRowid);
const shiftId = insertShift(db, Number(event.lastInsertRowid));
return {
eventId: Number(event.lastInsertRowid),
templateId: Number(template.lastInsertRowid),
shiftId,
};
}
function insertShift(db: Database.Database, eventId: number): number {
const shift = db
.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes)
VALUES (?, 'Sorting', ?, ?, 3, '')`,
)
.run(eventId, INSTANT, LATER);
return Number(shift.lastInsertRowid);
}
function insertSignup(
db: Database.Database,
shiftId: number,
options: {
name?: string;
email: string;
emailNorm: string;
status?: string;
groupSize?: number;
isMinor?: number;
guardianName?: string | null;
guardianEmail?: string | null;
},
): void {
db.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, is_minor, guardian_name, guardian_email, group_size,
status, reminders_off, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`,
).run(
shiftId,
options.name ?? 'Fake Person',
options.email,
options.emailNorm,
options.isMinor ?? 0,
options.guardianName ?? null,
options.guardianEmail ?? null,
options.groupSize ?? 1,
options.status ?? 'confirmed',
INSTANT,
INSTANT,
);
}
function insertAnonymized(db: Database.Database, shiftId: number): void {
db.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, phone, is_minor, guardian_name, guardian_email, group_size,
notes, status, manage_token_hash, token_expires_at, reminders_off, attended, created_at, updated_at, anonymized_at
) VALUES (?, NULL, NULL, NULL, NULL, 0, NULL, NULL, 1, NULL, 'confirmed', NULL, NULL, 0, NULL, ?, ?, ?)`,
).run(shiftId, INSTANT, INSTANT, INSTANT);
}
+13
View File
@@ -0,0 +1,13 @@
import { describe, expect, it } from 'vitest';
import { normalizeEmail } from '../src/email.js';
describe('normalizeEmail', () => {
it('trims and lowercases without removing dots', () => {
expect(normalizeEmail(' Ada@Example.com ')).toBe('ada@example.com');
expect(normalizeEmail('a.b+tag@gmail.com')).toBe('a.b+tag@gmail.com');
});
it('rejects a blank address', () => {
expect(() => normalizeEmail(' ')).toThrow(/email/i);
});
});
+42
View File
@@ -0,0 +1,42 @@
export function devEnv(overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {
return {
NODE_ENV: 'development',
PORT: '3000',
BASE_URL: 'http://127.0.0.1:3000',
BASE_PATH: '',
DATA_DIR: './data',
SESSION_SECRET: 'dev-only-change-me-not-for-production-use',
DEFAULT_TZ: 'America/Chicago',
MAIL_DRIVER: 'console',
MAIL_FROM: 'Hope Food Pantry <volunteer@example.invalid>',
MAIL_REPLY_TO: 'volunteer@example.invalid',
POSTMARK_TOKEN: '',
SES_REGION: '',
SES_ACCESS_KEY_ID: '',
SES_SECRET_ACCESS_KEY: '',
TURNSTILE_SITE_KEY: '1x00000000000000000000AA',
TURNSTILE_SECRET_KEY: '1x0000000000000000000000000000000AA',
BRAND_SRC: '../Hope Food Pantry Website/brand',
BOOTSTRAP_ADMIN_EMAIL: 'coordinator@example.invalid',
TRUST_PROXY: 'false',
...overrides,
};
}
export function productionEnv(dataDir: string, overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {
return devEnv({
NODE_ENV: 'production',
BASE_URL: 'https://volunteer.example.org',
DATA_DIR: dataDir,
SESSION_SECRET: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
MAIL_DRIVER: 'postmark',
MAIL_FROM: 'Hope Food Pantry <volunteer@example.org>',
MAIL_REPLY_TO: 'volunteer@example.org',
POSTMARK_TOKEN: 'pm-server-token-9f3a2c1e5b8d4f70',
TURNSTILE_SITE_KEY: '0x4AAAAAAA8k2mRealishSiteKey00',
TURNSTILE_SECRET_KEY: '0x4AAAAAAA8k2mRealishSecretKey00',
BOOTSTRAP_ADMIN_EMAIL: 'coordinator@example.org',
TRUST_PROXY: 'false',
...overrides,
});
}
+235
View File
@@ -0,0 +1,235 @@
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 { csvCell, exportDateRange, exportEventRoster, exportShiftRoster } from '../src/export.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('roster export', () => {
it('keeps formula-looking cells as text and quotes commas', () => {
expect(csvCell('=cmd')).toBe("'=cmd");
expect(csvCell('\t+1')).toBe("'\t+1");
expect(csvCell(' -Ada')).toBe("' -Ada");
expect(csvCell('@sum')).toBe("'@sum");
expect(csvCell('Ada, "Pat"')).toBe('"Ada, ""Pat"""');
expect(csvCell('Ada')).toBe('Ada');
});
it('exports one shift, including a cancelled person, and leaves another shift out', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'weekly', 'Weekly pantry');
const shiftId = insertShift(db, eventId, '2026-10-15T14:00:00.000Z', '2026-10-15T17:00:00.000Z');
const other = insertShift(db, eventId, '2026-10-17T14:00:00.000Z', '2026-10-17T17:00:00.000Z');
insertSignup(db, shiftId, { name: '=Ada', email: 'ada@example.invalid', notes: 'Blue, shirt', attended: 1 });
insertSignup(db, shiftId, { name: 'Ben', email: 'ben@example.invalid', status: 'cancelled', attended: 0 });
insertSignup(db, shiftId, { name: null, email: null, anonymized: true });
insertSignup(db, other, { name: 'Cam', email: 'cam@example.invalid' });
const exported = exportShiftRoster(db, shiftId);
expect(exported).not.toBeNull();
const text = exported?.csv ?? '';
expect(text.startsWith('\uFEFFDate,Start,End,Time zone,Role,')).toBe(true);
expect(text).toContain('\r\n');
expect(text).toContain("'=Ada");
expect(text).toContain('"Blue, shirt"');
expect(text).toContain('ada@example.invalid');
expect(text).toContain('Cancelled');
expect(text).toContain('No-show');
expect(text).toContain('Attended');
expect(text).toContain('2026-10-15');
expect(text).toContain('America/Chicago (CDT)');
expect(text).not.toContain('cam@example.invalid');
expect(text).not.toContain('Cam');
const anonymized = text.split('\r\n').find((line) => line.includes(',Confirmed,') && !line.includes('@'));
expect(anonymized).toBeTruthy();
});
it('uses the event local date for a range and refuses a backwards range', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'weekly', 'Weekly pantry');
const late = insertShift(db, eventId, '2026-10-15T04:30:00.000Z', '2026-10-15T06:00:00.000Z');
const morning = insertShift(db, eventId, '2026-10-15T14:00:00.000Z', '2026-10-15T17:00:00.000Z');
insertSignup(db, late, { name: 'Late', email: 'late@example.invalid' });
insertSignup(db, morning, { name: 'Morning', email: 'morning@example.invalid' });
const hidden = insertEvent(db, 'hidden', 'Hidden drive', 0);
const hiddenShift = insertShift(db, hidden, '2026-10-15T15:00:00.000Z', '2026-10-15T16:00:00.000Z');
insertSignup(db, hiddenShift, { name: 'Hidden', email: 'hidden@example.invalid' });
const range = exportDateRange(db, '2026-10-15', '2026-10-15');
expect(range.ok).toBe(true);
if (!range.ok) return;
expect(range.export.rows).toBe(2);
expect(range.export.csv).toContain('morning@example.invalid');
expect(range.export.csv).toContain('hidden@example.invalid');
expect(range.export.csv).not.toContain('late@example.invalid');
const event = exportEventRoster(db, eventId);
expect(event?.rows).toBe(2);
expect(event?.csv).not.toContain('hidden@example.invalid');
expect(exportDateRange(db, '2026-10-16', '2026-10-15')).toEqual({ ok: false, error: 'The end date is before the start date.' });
expect(exportDateRange(db, '2026-02-31', '2026-03-01')).toEqual({ ok: false, error: 'Use real dates.' });
expect(exportDateRange(db, '2024-01-01', '2026-01-02').ok).toBe(false);
});
it('downloads through the coordinator session and records the count, not the people', async () => {
const { app, db } = await buildApp();
const eventId = insertEvent(db, 'weekly', 'Weekly pantry');
const shiftId = insertShift(db, eventId, '2026-10-15T14:00:00.000Z', '2026-10-15T17:00:00.000Z');
insertSignup(db, shiftId, { name: 'Ada', email: 'ada@example.invalid', phone: '+1 712' });
const cookie = await signIn(app, db);
const loggedOut = await app.request(`/admin/shifts/${shiftId}/export`, { method: 'POST' });
expect(loggedOut.status).toBe(303);
expect(await loggedOut.text()).not.toContain('ada@example.invalid');
const stale = await postExport(app, cookie, `/admin/shifts/${shiftId}/export`, 'nope');
expect(stale.status).toBe(403);
expect(await stale.text()).not.toContain('ada@example.invalid');
const file = await postExport(app, cookie, `/admin/shifts/${shiftId}/export`);
expect(file.status).toBe(200);
expect(file.headers.get('content-type')).toContain('text/csv');
expect(file.headers.get('cache-control')).toBe('no-store');
expect(file.headers.get('content-disposition')).toBe(`attachment; filename="hope-shift-${shiftId}.csv"`);
const bytes = new Uint8Array(await file.arrayBuffer());
expect([...bytes.slice(0, 3)]).toEqual([0xef, 0xbb, 0xbf]);
const body = new TextDecoder().decode(bytes);
expect(body).toContain("'+1 712");
const audit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'roster.export'`).get() as { detail_json: string };
expect(audit.detail_json).toBe(`{"shiftId":${shiftId},"rows":1}`);
expect(audit.detail_json).not.toContain('@');
const ranged = await postExport(app, cookie, '/admin/export', undefined, { from: '2026-10-15', to: '2026-10-15' });
expect(ranged.headers.get('content-disposition')).toBe('attachment; filename="hope-roster-2026-10-15-to-2026-10-15.csv"');
const backwards = await postExport(app, cookie, '/admin/export', undefined, { from: '2026-10-20', to: '2026-10-01' });
expect(backwards.status).toBe(400);
expect(await backwards.text()).toContain('The end date is before the start date.');
});
});
async function openDb() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-export-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
return db;
}
async function buildApp() {
const db = await openDb();
bootstrapAdmin(db, 'coordinator@example.invalid', NOW);
const config = loadConfig(devEnv({ DATA_DIR: path.join(rootOf(db), 'data') }));
const app = createApp(config, db, {
now: NOW,
clientIp: () => '203.0.113.50',
verifyTurnstile: async () => ({ ok: true }),
});
return { app, db };
}
function rootOf(db: { name: string }): string {
return path.dirname(path.dirname(db.name));
}
function insertEvent(db: Awaited<ReturnType<typeof openDb>>, slug: string, title: string, published = 1): number {
return Number(
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES (?, ?, '', 'Sioux Center, Iowa', 'America/Chicago', ?, ?)`,
).run(slug, title, published, NOW).lastInsertRowid,
);
}
function insertShift(db: Awaited<ReturnType<typeof openDb>>, eventId: number, start: string, end: string): number {
return Number(
db.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, 'Sorting', ?, ?, 4, '', 0)`,
).run(eventId, start, end).lastInsertRowid,
);
}
function insertSignup(
db: Awaited<ReturnType<typeof openDb>>,
shiftId: number,
options: {
name: string | null;
email: string | null;
notes?: string | null;
phone?: string | null;
status?: string;
attended?: number | null;
anonymized?: boolean;
},
): void {
const anonymized = options.anonymized === true;
db.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, phone, is_minor, guardian_name, guardian_email, group_size, notes,
status, reminders_off, attended, created_at, updated_at, anonymized_at
) VALUES (?, ?, ?, ?, ?, 0, NULL, NULL, 1, ?, ?, 0, ?, ?, ?, ?)`,
).run(
shiftId,
anonymized ? null : options.name,
anonymized ? null : options.email,
anonymized ? null : options.email,
anonymized ? null : options.phone ?? null,
anonymized ? null : options.notes ?? null,
options.status ?? 'confirmed',
options.attended ?? null,
NOW,
NOW,
anonymized ? NOW : null,
);
}
async function signIn(app: Awaited<ReturnType<typeof buildApp>>['app'], db: Awaited<ReturnType<typeof openDb>>) {
await app.request('/login', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ email: 'coordinator@example.invalid', company_website: '', 'cf-turnstile-response': 'token' }),
});
const queued = db.prepare(`SELECT body_text AS body_text FROM outbox WHERE kind = 'magic_link'`).get() as { body_text: string };
const token = /\/login\/link\/([A-Za-z0-9_-]+)/.exec(queued.body_text)?.[1] ?? '';
const page = await app.request(`/login/link/${token}`);
const proof = /name="proof"[^>]*value="([^"]*)"/.exec(await page.text())?.[1] ?? '';
const signedIn = await app.request(`/login/link/${token}`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ proof }),
});
const cookie = /hope_session=([^;]+)/.exec(signedIn.headers.get('set-cookie') ?? '')?.[1] ?? '';
return `hope_session=${cookie}`;
}
async function postExport(
app: Awaited<ReturnType<typeof buildApp>>['app'],
cookie: string,
pathName: string,
csrf?: string,
fields?: { from: string; to: string },
) {
const current = await app.request(pathName.startsWith('/admin/export') ? '/admin' : pathName.replace(/\/export$/, ''), { headers: { cookie } });
const token = csrf ?? (/name="csrf"[^>]*value="([^"]*)"/.exec(await current.text())?.[1] ?? '');
const body = new URLSearchParams({ csrf: token, from: fields?.from ?? '', to: fields?.to ?? '' });
return app.request(pathName, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body,
});
}
+307
View File
@@ -0,0 +1,307 @@
import { createHash } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { SendEmailCommand } from '@aws-sdk/client-sesv2';
import { Temporal } from '@js-temporal/polyfill';
import { afterEach, describe, expect, it } from 'vitest';
import { createApp } from '../src/app.js';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { issueFormToken } from '../src/form-token.js';
import { deliverDueMail } from '../src/mail/deliver.js';
import { createPostmarkMailer } from '../src/mail/postmark.js';
import { createSesMailer } from '../src/mail/ses.js';
import { renderConfirmation } from '../src/mail/templates.js';
import type { Mailer } from '../src/mail/types.js';
import { reserveSignup, type ReserveInput } from '../src/signup.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const MAIL = {
baseUrl: 'http://127.0.0.1:3000',
basePath: '',
from: 'Hope Food Pantry <volunteer@example.invalid>',
replyTo: 'volunteer@example.invalid',
};
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('transactional mail', () => {
it('escapes the person\'s name in HTML and keeps the subject on one line', () => {
const rendered = renderConfirmation({
audience: 'volunteer',
volunteerName: 'Pat <script>\nReview',
shift: { role: 'Sorting', eventTitle: 'Weekly pantry', location: 'Sioux Center, Iowa', whenLabel: 'Thursday, October 15, 2026, 9:00 AM to 12:00 PM CDT' },
manageUrl: 'http://127.0.0.1:3000/m/token-value-abcdefghijk',
replyTo: 'volunteer@example.invalid',
});
expect(rendered.subject).toBe("You're signed up for Sorting");
expect(rendered.subject).not.toContain('\n');
expect(rendered.html).toContain('Pat &lt;script&gt; Review');
expect(rendered.html).not.toContain('<script>');
expect(rendered.text).toContain('http://127.0.0.1:3000/m/token-value-abcdefghijk');
});
it('queues one confirmation, a guardian copy when the address differs, and no second copy on replay', async () => {
const { db, shiftId } = await buildDb();
const saved = reserveSignup(db, reservation(shiftId, { email: 'minor@example.invalid', isMinor: true, guardianEmail: 'guardian@example.invalid', name: 'Minor Pat' }));
expect(saved.ok).toBe(true);
const rows = db.prepare('SELECT to_email, kind, status FROM outbox ORDER BY id').all();
expect(rows).toEqual([
{ to_email: 'minor@example.invalid', kind: 'confirmation', status: 'pending' },
{ to_email: 'guardian@example.invalid', kind: 'confirmation', status: 'pending' },
]);
const same = reserveSignup(db, reservation(shiftId, { email: 'minor@example.invalid', isMinor: true, guardianEmail: 'guardian@example.invalid', name: 'Minor Pat', operationId: 'same-operation' }));
expect(same.ok && same.replay).toBe(true);
expect(db.prepare('SELECT COUNT(*) AS n FROM outbox').get()).toEqual({ n: 2 });
const shared = reserveSignup(db, reservation(shiftId, { email: 'shared@example.invalid', isMinor: true, guardianEmail: 'shared@example.invalid', operationId: 'shared-operation' }));
expect(shared.ok).toBe(true);
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE to_email = 'shared@example.invalid'").get()).toEqual({ n: 1 });
});
it('sends the queued letter once and does not send it again', async () => {
const { db, shiftId } = await buildDb();
const saved = reserveSignup(db, reservation(shiftId, { name: 'Pat <b>Review</b>' }));
expect(saved.ok).toBe(true);
const seen: string[] = [];
const mailer: Mailer = {
async send(message) {
seen.push(message.html);
expect(message.from).toBe(MAIL.from);
expect(message.replyTo).toBe(MAIL.replyTo);
expect(message.html).toContain('Pat &lt;b&gt;Review&lt;/b&gt;');
expect(message.html).not.toContain('<b>Review</b>');
return { result: 'sent', providerId: 'console-1' };
},
};
expect(await deliverDueMail(db, mailer, NOW)).toBe(1);
expect(await deliverDueMail(db, mailer, NOW)).toBe(0);
const stored = db.prepare('SELECT status, provider_id, sent_at, body_text FROM outbox').get() as {
status: string;
provider_id: string;
sent_at: string;
body_text: string;
};
expect(stored.status).toBe('sent');
expect(stored.provider_id).toBe('console-1');
expect(stored.sent_at).toBe(NOW);
const token = stored.body_text.match(/\/m\/([A-Za-z0-9_-]+)/)?.[1] ?? '';
const hash = createHash('sha256').update(token).digest('hex');
expect(db.prepare('SELECT manage_token_hash FROM signups').get()).toEqual({ manage_token_hash: hash });
expect(seen).toHaveLength(1);
});
it('drops a confirmation that is no longer current and retries only a clear failure', async () => {
const { db, shiftId } = await buildDb();
reserveSignup(db, reservation(shiftId, { email: 'gone@example.invalid', operationId: 'gone-operation' }));
db.prepare("UPDATE signups SET status = 'cancelled' WHERE email_norm = 'gone@example.invalid'").run();
let calls = 0;
const unused: Mailer = { async send() { calls += 1; return { result: 'sent', providerId: null }; } };
expect(await deliverDueMail(db, unused, NOW)).toBe(0);
expect(calls).toBe(0);
expect(db.prepare('SELECT status, last_error FROM outbox').get()).toEqual({
status: 'cancelled',
last_error: 'The signup changed before this message was sent.',
});
reserveSignup(db, reservation(shiftId, { email: 'retry@example.invalid', operationId: 'retry-operation' }));
const retry: Mailer = { async send() { return { result: 'retry', error: 'busy for retry@example.invalid /m/secret-token-value' }; } };
expect(await deliverDueMail(db, retry, NOW, () => 0)).toBe(0);
const waiting = db.prepare("SELECT status, attempts, send_after, last_error FROM outbox WHERE to_email = 'retry@example.invalid'").get() as {
status: string;
attempts: number;
send_after: string;
last_error: string;
};
expect(waiting.status).toBe('pending');
expect(waiting.attempts).toBe(1);
expect(waiting.send_after > NOW).toBe(true);
expect(waiting.last_error).not.toContain('retry@example.invalid');
expect(waiting.last_error).not.toContain('/m/secret');
let now = waiting.send_after;
for (let attempt = 2; attempt <= 5; attempt += 1) {
expect(await deliverDueMail(db, retry, now, () => 0)).toBe(0);
const row = db.prepare("SELECT status, attempts, send_after FROM outbox WHERE to_email = 'retry@example.invalid'").get() as {
status: string;
attempts: number;
send_after: string;
};
expect(row.attempts).toBe(attempt);
now = row.send_after;
}
expect(db.prepare("SELECT status FROM outbox WHERE to_email = 'retry@example.invalid'").get()).toEqual({ status: 'failed' });
});
it('keeps an uncertain send from being sent again, including an expired lease', async () => {
const { db, shiftId } = await buildDb();
reserveSignup(db, reservation(shiftId));
const unknown: Mailer = { async send() { return { result: 'unknown', error: 'timeout' }; } };
expect(await deliverDueMail(db, unknown, NOW)).toBe(0);
expect(db.prepare('SELECT status FROM outbox').get()).toEqual({ status: 'delivery_unknown' });
expect(await deliverDueMail(db, unknown, NOW)).toBe(0);
expect(db.prepare('SELECT COUNT(*) AS n FROM outbox WHERE status = \'delivery_unknown\'').get()).toEqual({ n: 1 });
const { db: leased, shiftId: leasedShift } = await buildDb();
reserveSignup(leased, reservation(leasedShift, { operationId: 'leased-operation' }));
leased.prepare("UPDATE outbox SET status = 'sending', attempts = 1, claimed_at = ?, lease_expires_at = ?").run(NOW, NOW);
let called = 0;
const later = '2026-10-14T18:05:00.000Z';
expect(await deliverDueMail(leased, { async send() { called += 1; return { result: 'sent', providerId: null }; } }, later)).toBe(0);
expect(called).toBe(0);
expect(leased.prepare('SELECT status FROM outbox').get()).toEqual({ status: 'delivery_unknown' });
});
it('does not put the volunteer address on the public shift list', async () => {
const root = mkdtempSync(path.join(tmpdir(), 'hope-mail-http-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
const shiftId = insertShift(db);
const app = createApp(config, db, {
now: NOW,
clientIp: () => '203.0.113.10',
verifyTurnstile: async () => ({ ok: true }),
});
const body = new URLSearchParams({
form_token: issueFormToken(config.sessionSecret, {
shiftId,
issuedAt: Temporal.Instant.from(NOW).epochMilliseconds - 10_000,
operationId: 'mail-http-operation',
}),
name: 'Listed Person',
email: 'listed@example.invalid',
phone: '',
notes: '',
guardianName: '',
guardianEmail: '',
company_website: '',
'cf-turnstile-response': 'widget-token',
});
const saved = await app.request(`/s/${shiftId}`, {
method: 'POST',
headers: { origin: 'http://127.0.0.1:3000', 'content-type': 'application/x-www-form-urlencoded' },
body,
});
expect(saved.status).toBe(303);
const home = await (await app.request('/')).text();
expect(home).not.toContain('listed@example.invalid');
expect(home).not.toContain('Listed Person');
expect(db.prepare("SELECT status FROM outbox").get()).toEqual({ status: 'pending' });
});
});
describe('mail drivers', () => {
it('treats Postmark acceptance, rejection, and a lost connection differently', async () => {
const message = sample();
const accepted = createPostmarkMailer('server-token-value', async (_url, init) => {
expect(String(init?.headers && (init.headers as Record<string, string>)['X-Postmark-Server-Token'])).toBe('server-token-value');
expect(String(init?.body)).toContain('Pat Review');
return json({ ErrorCode: 0, MessageID: 'pm-1' }, 200);
});
expect(await accepted.send(message)).toEqual({ result: 'sent', providerId: 'pm-1' });
const rejected = createPostmarkMailer('server-token-value', async () => json({ ErrorCode: 406, Message: 'Inactive recipient pat@example.invalid' }, 422));
const failed = await rejected.send(message);
expect(failed.result).toBe('failed');
if (failed.result === 'failed') expect(failed.error).not.toContain('pat@example.invalid');
const busy = createPostmarkMailer('server-token-value', async () => new Response('no', { status: 503 }));
expect((await busy.send(message)).result).toBe('retry');
const down = createPostmarkMailer('server-token-value', async () => {
throw Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' });
});
expect((await down.send(message)).result).toBe('retry');
});
it('treats a rejected SES address as permanent and a throttle as retryable', async () => {
const message = sample();
const rejected = createSesMailer({
region: 'us-east-1',
accessKeyId: 'AKIAexamplekeyvalue',
secretAccessKey: 'secret-access-key-value',
client: { async send() { throw Object.assign(new Error('Address pat@example.invalid is not verified'), { name: 'MessageRejected' }); } },
});
const failed = await rejected.send(message);
expect(failed.result).toBe('failed');
if (failed.result === 'failed') expect(failed.error).not.toContain('pat@example.invalid');
const throttled = createSesMailer({
region: 'us-east-1',
accessKeyId: 'AKIAexamplekeyvalue',
secretAccessKey: 'secret-access-key-value',
client: {
async send(command) {
expect(command).toBeInstanceOf(SendEmailCommand);
throw Object.assign(new Error('slow down'), { name: 'TooManyRequestsException' });
},
},
});
expect((await throttled.send(message)).result).toBe('retry');
});
});
function sample() {
return {
from: MAIL.from,
to: 'pat@example.invalid',
replyTo: MAIL.replyTo,
subject: 'You are signed up',
text: 'Hello Pat Review',
html: '<p>Hello Pat Review</p>',
};
}
function json(body: unknown, status: number): Response {
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
}
async function buildDb() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-mail-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
return { db, shiftId: insertShift(db) };
}
function insertShift(db: Awaited<ReturnType<typeof openAppDatabase>>): number {
const eventId = Number(
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES ('weekly-pantry', 'Weekly pantry', 'Bring a hat.', 'Sioux Center, Iowa', 'America/Chicago', 1, ?)`,
).run(NOW).lastInsertRowid,
);
return Number(
db.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, 'Sorting', '2026-10-15T14:00:00.000Z', '2026-10-15T17:00:00.000Z', 4, '', 0)`,
).run(eventId).lastInsertRowid,
);
}
function reservation(shiftId: number, overrides: Partial<ReserveInput> = {}): ReserveInput {
return {
shiftId,
name: 'Pat Review',
email: 'pat.review@example.invalid',
phone: null,
notes: null,
isMinor: false,
guardianName: overrides.isMinor ? 'Guardian Pat' : null,
guardianEmail: null,
operationId: 'same-operation',
now: NOW,
mail: MAIL,
...overrides,
};
}
+211
View File
@@ -0,0 +1,211 @@
import { createHmac, randomBytes } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import type Database from 'better-sqlite3';
import { Temporal } from '@js-temporal/polyfill';
import { afterEach, describe, expect, it } from 'vitest';
import { createApp } from '../src/app.js';
import { issueCancelToken } from '../src/cancel-token.js';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { issueFormToken } from '../src/form-token.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const NOW_MS = Temporal.Instant.from(NOW).epochMilliseconds;
const SECRET = 'dev-only-change-me-not-for-production-use';
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('management links are scoped to one signup', () => {
it('cannot list, cancel, or move a victim signup by reusing their name and email', async () => {
const { app, db, shiftId } = await buildApp();
const victimShift = insertShift(db, eventOf(db), 'Distribution', '2026-10-17T14:00:00.000Z', '2026-10-17T17:00:00.000Z', 2);
insertSignup(db, victimShift, 'Victim Person', 'victim@example.invalid');
const victimId = signupIdFor(db, victimShift, 'victim@example.invalid');
const before = db.prepare('SELECT * FROM signups WHERE id = ?').get(victimId);
const attacker = await openManage(app, db, shiftId, 'victim person', 'victim@example.invalid', '203.0.113.90');
const html = await (await app.request(attacker.managePath)).text();
expect(html).not.toContain('Your other shifts');
expect(html).not.toContain('/also/');
const token = attacker.managePath.slice(3);
// Even a previously rendered form with a valid legacy proof must fail.
for (const suffix of ['', '/switch']) {
const response = await app.request(`${attacker.managePath}/also/${victimId}${suffix}`, {
method: 'POST',
headers: { origin: 'http://127.0.0.1:3000' },
body: new URLSearchParams({
cancel_token: legacyProof('cancel', token, victimId),
switch_token: legacyProof('switch', token, victimId),
destination: String(shiftId),
}),
});
expect(response.status).toBe(404);
}
expect(db.prepare('SELECT * FROM signups WHERE id = ?').get(victimId)).toEqual(before);
// Their own link remains usable, including after cancellation.
const cancelled = await app.request(attacker.managePath, {
method: 'POST', headers: { origin: 'http://127.0.0.1:3000' },
body: new URLSearchParams({ cancel_token: issueCancelToken(SECRET, token) }),
});
expect(cancelled.status).toBe(303);
expect(await (await app.request(attacker.managePath)).text()).not.toContain('Your other shifts');
expect(db.prepare('SELECT * FROM signups WHERE id = ?').get(victimId)).toEqual(before);
});
it('rejects oversized fixed-length and streamed bodies before signup or login processing', async () => {
const { app, db, shiftId } = await buildApp();
for (const route of [`/s/${shiftId}`, '/login']) {
for (const withLength of [true, false]) {
const payload = 'name=' + 'A'.repeat(128 * 1024);
const headers: Record<string, string> = {origin: 'https://invalid.example', 'content-type': 'application/x-www-form-urlencoded'};
if (withLength) headers['content-length'] = String(payload.length);
const body = withLength ? payload : new ReadableStream({start(controller) {
controller.enqueue(new TextEncoder().encode(payload.slice(0, 65536)));
controller.enqueue(new TextEncoder().encode(payload.slice(65536)));
controller.close();
}});
const response = await app.request(route, {method:'POST', headers, body, duplex:'half'} as RequestInit);
expect(response.status).toBe(413);
expect((await response.text()).length).toBeLessThan(100);
expect(response.headers.get('content-security-policy')).toContain("default-src 'self'");
}
}
expect(db.prepare('SELECT COUNT(*) AS n FROM signups').get()).toEqual({n:0});
expect(db.prepare('SELECT COUNT(*) AS n FROM rate_hits').get()).toEqual({n:0});
});
it('does not reflect form data for a rejected origin or a rate-limited request', async () => {
const { app, shiftId } = await buildApp();
const send = (origin: string) => app.request(`/s/${shiftId}`, {
method:'POST', headers:{origin, 'x-test-ip':'203.0.113.91'},
body:new URLSearchParams({name:'DO-NOT-REFLECT'}),
});
const invalid = await send('https://invalid.example');
expect(invalid.status).toBe(403);
expect(await invalid.text()).not.toContain('DO-NOT-REFLECT');
for (let i = 0; i < 5; i++) await send('http://127.0.0.1:3000');
const limited = await send('http://127.0.0.1:3000');
expect(limited.status).toBe(429);
expect(await limited.text()).not.toContain('DO-NOT-REFLECT');
});
});
async function buildApp(options?: { capacity?: number }) {
const root = mkdtempSync(path.join(tmpdir(), 'hope-other-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES ('weekly-pantry', 'Weekly pantry', 'Bring a hat.', 'Sioux Center, Iowa', 'America/Chicago', 1, ?)`,
).run(NOW);
const shiftId = insertShift(db, eventOf(db), 'Sorting', '2026-10-15T14:00:00.000Z', '2026-10-15T17:00:00.000Z', options?.capacity ?? 4);
const app = createApp(config, db, {
now: NOW,
clientIp: (c) => c.req.header('x-test-ip') ?? null,
verifyTurnstile: async () => ({ ok: true }),
});
return { app, db, shiftId };
}
function eventOf(db: Database.Database): number {
return Number((db.prepare('SELECT id AS id FROM events').get() as { id: number }).id);
}
function insertShift(
db: Database.Database,
eventId: number,
role: string,
starts: string,
ends: string,
capacity: number,
) {
return Number(
db.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, ?, ?, ?, ?, '', 0)`,
).run(eventId, role, starts, ends, capacity).lastInsertRowid,
);
}
async function openManage(
app: ReturnType<typeof createApp>,
db: Database.Database,
shiftId: number,
name: string,
email: string,
ip: string,
) {
const saved = await postSignup(app, shiftId, { name, email }, ip);
expect(saved.status).toBe(303);
const confirmed = await app.request(saved.headers.get('location') ?? '', {
headers: { cookie: (saved.headers.get('set-cookie') ?? '').split(';')[0] ?? '' },
});
const confirmedHtml = await confirmed.text();
const managePath = confirmedHtml.match(/href="(\/m\/[^"]+)"/)?.[1] ?? '';
expect(managePath.length).toBeGreaterThan(20);
const signupId = Number(
(db.prepare('SELECT id AS id FROM signups WHERE shift_id = ? AND email_norm = ? ORDER BY id DESC LIMIT 1').get(shiftId, email) as { id: number }).id,
);
return { managePath, signupId };
}
async function postSignup(
app: ReturnType<typeof createApp>,
shiftId: number,
fields: { name: string; email: string },
ip: string,
) {
const body = new URLSearchParams({
form_token: issueFormToken(SECRET, {
shiftId,
issuedAt: NOW_MS - 10_000,
operationId: randomBytes(16).toString('hex'),
}),
name: fields.name,
email: fields.email,
phone: '',
notes: '',
guardianName: '',
guardianEmail: '',
company_website: '',
'cf-turnstile-response': 'widget-token',
});
return app.request(`/s/${shiftId}`, {
method: 'POST',
headers: {
origin: 'http://127.0.0.1:3000',
'content-type': 'application/x-www-form-urlencoded',
'x-test-ip': ip,
},
body,
});
}
function insertSignup(db: Database.Database, shiftId: number, name: string, email: string): void {
db.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, is_minor, group_size, notes, status,
manage_token_hash, token_expires_at, reminders_off, created_at, updated_at
) VALUES (?, ?, ?, ?, 0, 1, NULL, 'confirmed', ?, '2026-10-24T17:00:00.000Z', 0, ?, ?)`,
).run(shiftId, name, email, email, randomBytes(32).toString('hex'), NOW, NOW);
}
function signupIdFor(db: Database.Database, shiftId: number, email: string): number {
return Number(
(db.prepare("SELECT id AS id FROM signups WHERE shift_id = ? AND email_norm = ? AND status = 'confirmed'").get(shiftId, email) as { id: number }).id,
);
}
function legacyProof(action: string, token: string, id: number): string {
return createHmac('sha256', SECRET).update(`hope-owned-${action}-v1\0${token}\0${id}`).digest('base64url');
}
+356
View File
@@ -0,0 +1,356 @@
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, publicDirectory } from '../src/app.js';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { Hono } from 'hono';
import { CONTENT_SECURITY_POLICY, PERMISSIONS_POLICY, securityHeaders, STRICT_TRANSPORT_SECURITY } from '../src/security.js';
import { localShiftToUtc } from '../src/time.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
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('public pages', () => {
it('lists upcoming published shifts and hides private details', async () => {
const { app, ids } = await buildApp();
const home = await app.request('/');
expect(home.status).toBe(200);
const html = await home.text();
expect(html).toContain('Weekly pantry');
expect(html).not.toContain('Upcoming shifts');
expect(html).toContain('Open Sorting');
expect(html).toContain('Full Intake');
expect(html).toContain('Live Greeting');
expect(html).toContain('1/3 spots filled');
expect(html).toContain('1/1 spots filled');
expect(html).toContain('9:00 AM');
expect(html).toContain('CDT');
expect(html).toContain('October 15');
expect(html).toContain('October 2026');
expect(html).toContain('shift-calendar');
expect(html).toContain('class="cal-line"');
expect(html).toContain('class="cal-hold"');
expect(html).toContain('class="cal-detail"');
expect(html).toContain('>Sun</span>');
expect(html).toContain('Today');
expect(html).toContain('aria-current="date"');
expect(html).toContain('In progress');
expect(html).not.toContain('Volunteer tools');
const header = html.slice(html.indexOf('class="site-header"'), html.indexOf('<main'));
expect(header).toContain('Coordinator');
expect(header).toContain('>Privacy</a>');
expect(header).toContain('href="/" aria-current="page">Calendar</a>');
expect(header).toContain('class="main-nav-link" href="/" aria-current="page">Volunteering</a>');
expect(header).not.toContain('href="/privacy" aria-current="page"');
expect(header).not.toContain('Log out');
const nav = html.slice(html.indexOf('class="nav-links"'), html.indexOf('</nav>'));
expect(nav).toContain('Donate');
expect(nav).not.toContain('Coordinator');
expect(nav).not.toContain('Privacy');
expect(nav).not.toContain('Log out');
const footer = html.slice(html.indexOf('site-footer'));
expect(footer).toContain('Privacy');
expect(footer).not.toContain('Coordinator');
expect(html).not.toContain('Cancelled Distribution');
expect(html).not.toContain('Past Setup');
expect(html).not.toContain('Hidden draft');
expect(html).not.toContain('Secret Person');
expect(html).not.toContain('secret.person@example.invalid');
expect(html).not.toContain('SECRET-PERSON-NOTE');
expect(html).not.toContain('SECRET-SHIFT-NOTE');
expect(html).not.toContain('<form');
expect(html).toContain('src="/js/desk.js"');
expect(html).toContain('src="/js/enhance.js"');
expect(html).not.toContain('<script>alert(1)</script>');
expect(html).toContain('href="/css/app.css"');
expect(html).toContain('href="/brand/tokens.css"');
expect(html).toContain(`href="/s/${ids.open}"`);
expect(home.headers.get('content-security-policy')).toBe(CONTENT_SECURITY_POLICY);
expect(home.headers.get('referrer-policy')).toBe('no-referrer');
expect(home.headers.get('x-content-type-options')).toBe('nosniff');
expect(home.headers.get('permissions-policy')).toBe(PERMISSIONS_POLICY);
expect(home.headers.get('strict-transport-security')).toBeNull();
expect(home.headers.get('cache-control')).toBe('no-store');
const event = await app.request('/e/weekly-pantry');
const eventHtml = await event.text();
expect(event.status).toBe(200);
expect(eventHtml).toContain('&lt;script&gt;alert(1)&lt;/script&gt;');
expect(eventHtml).not.toContain('<script>alert(1)</script>');
expect(eventHtml).toContain('Sioux Center, Iowa');
expect(eventHtml).toContain('October 2026');
expect(eventHtml).toContain('shift-calendar');
expect(eventHtml).toContain('Sign up');
expect(eventHtml).toContain('View shift');
expect(eventHtml).not.toContain('November 2026');
expect(eventHtml).not.toContain('SECRET-PERSON-NOTE');
const shift = await app.request(`/s/${ids.open}`);
const shiftHtml = await shift.text();
expect(shift.status).toBe(200);
expect(shiftHtml).toContain('Open Sorting');
expect(shiftHtml).not.toContain('class="crumb"');
const shiftMain = shiftHtml.slice(shiftHtml.indexOf('<main'), shiftHtml.indexOf('site-footer'));
expect(shiftMain).not.toContain('Weekly pantry');
expect(shiftMain).not.toContain('sunburst');
expect(shiftHtml).toContain('1/3 spots filled');
expect(shiftHtml).toContain('spots is-open');
expect(shiftHtml).toContain('<form');
expect(shiftHtml).toContain('We will not text you');
expect(shiftHtml).toContain('https://challenges.cloudflare.com/turnstile/v0/api.js');
expect(shiftHtml).toContain('data-under-18');
expect(shiftHtml).toContain('data-guardian');
expect(shiftHtml).not.toMatch(/id="signup-under-18"[^>]*\schecked/);
const css = await (await app.request('/css/app.css')).text();
expect(css).toContain('.signup-form:not(:has([data-under-18]:checked)) [data-guardian]');
expect(shiftHtml).not.toContain('SECRET-SHIFT-NOTE');
expect(shiftHtml).not.toContain('Secret Person');
const full = await app.request(`/s/${ids.full}`);
const fullHtml = await full.text();
expect(fullHtml).toContain('1/1 spots filled');
expect(fullHtml).toContain('spots is-full');
expect(fullHtml).not.toContain('<form');
const cancelled = await app.request(`/s/${ids.cancelled}`);
const cancelledHtml = await cancelled.text();
expect(cancelled.status).toBe(200);
expect(cancelledHtml).toContain('Cancelled. This shift is closed.');
expect(cancelledHtml).not.toContain('<form');
const past = await app.request(`/s/${ids.past}`);
const pastHtml = await past.text();
expect(pastHtml).toContain('Ended. This shift is closed.');
expect(pastHtml).not.toContain('<form');
const live = await app.request(`/s/${ids.live}`);
expect(await live.text()).toContain('In progress');
expect((await app.request('/e/hidden-draft')).status).toBe(404);
expect((await app.request(`/s/${ids.hidden}`)).status).toBe(404);
expect((await app.request('/e/missing')).status).toBe(404);
expect((await app.request('/s/nope')).status).toBe(404);
});
it('leaves the event name and sunburst off shift pages', async () => {
const { app, ids } = await buildApp();
const shiftHtml = await (await app.request(`/s/${ids.open}`)).text();
const shiftMain = shiftHtml.slice(shiftHtml.indexOf('<main'), shiftHtml.indexOf('site-footer'));
expect(shiftMain).toContain('Open Sorting');
expect(shiftMain).not.toContain('class="crumb"');
expect(shiftMain).not.toContain('Weekly pantry');
expect(shiftMain).not.toContain('sunburst');
const stylesheet = await (await app.request('/css/app.css')).text();
expect(stylesheet).not.toContain('sunburst');
expect(stylesheet).not.toContain('h1.bare');
});
it('serves an honest privacy page, a minimal health check, and static assets', async () => {
const { app } = await buildApp();
const privacy = await app.request('/privacy');
const privacyHtml = await privacy.text();
expect(privacy.status).toBe(200);
expect(privacyHtml).toContain('href="/">Calendar</a>');
expect(privacyHtml).toContain('class="main-nav-link" href="/">Volunteering</a>');
expect(privacyHtml).not.toContain('href="/" aria-current="page"');
expect(privacyHtml).toContain('href="/privacy" aria-current="page">Privacy</a>');
expect(privacyHtml).toContain('does not have an approved privacy notice yet');
expect(privacyHtml).toContain('This page is not a privacy policy.');
expect(privacyHtml).not.toContain('24 months');
const health = await app.request('/healthz');
expect(health.status).toBe(200);
const healthBody = await health.json();
expect(healthBody).toEqual({ ok: true, database: 'ok' });
expect(JSON.stringify(healthBody)).not.toMatch(/session|turnstile|secret|@/i);
const css = await app.request('/css/app.css');
expect(css.status).toBe(200);
expect(css.headers.get('content-type')).toContain('text/css');
const stylesheet = await css.text();
expect(stylesheet).toContain('var(--hope-ink)');
expect(stylesheet).not.toContain('sunburst');
const tokens = await app.request('/brand/tokens.css');
expect(tokens.status).toBe(200);
expect(await tokens.text()).toContain('--hope-yellow:#f9e194');
});
it('prefixes routes and assets when the app is mounted at /volunteer', async () => {
const { app } = await buildApp({ basePath: '/volunteer' });
expect((await app.request('/')).status).toBe(404);
expect((await app.request('/healthz')).status).toBe(404);
const home = await app.request('/volunteer');
expect(home.status).toBe(200);
const html = await home.text();
expect(html).toContain('href="/volunteer/css/app.css"');
expect(html).toContain('href="/volunteer/brand/tokens.css"');
expect(html).toContain('Weekly pantry');
expect(html).not.toContain('Upcoming shifts');
expect((await app.request('/volunteer/e/weekly-pantry')).status).toBe(200);
expect(html).toContain('href="/volunteer/privacy"');
expect(html).toMatch(/href="\/volunteer\/s\/\d+"/);
const slash = await app.request('/volunteer/');
expect(slash.status).toBe(302);
expect(slash.headers.get('location')).toBe('/volunteer');
const css = await app.request('/volunteer/css/app.css');
expect(css.status).toBe(200);
expect(await css.text()).toContain('var(--font-body)');
const health = await app.request('/volunteer/healthz');
expect(await health.json()).toEqual({ ok: true, database: 'ok' });
});
it('shows one month at a time and cycles between months that have shifts', async () => {
const { app, db } = await buildApp();
const event = db.prepare(`SELECT id AS id FROM events WHERE slug = 'weekly-pantry'`).get() as { id: number };
insertShift(db, event.id, 'November Sorting', '2026-11-04', '09:00', '12:00', 4, 0);
insertShift(db, event.id, 'Edge Sorting', '2026-11-30', '09:00', '12:00', 4, 0);
insertShift(db, event.id, 'December Sorting', '2026-12-02', '09:00', '12:00', 4, 0);
const html = await (await app.request('/e/weekly-pantry')).text();
const home = await (await app.request('/')).text();
expect(html).toContain('October 2026');
expect(html).toContain('Next month');
expect(html).not.toContain('Previous month');
expect(html).not.toContain('November 2026');
expect(html).not.toContain('September');
expect(home).toContain('href="/?month=2026-11"');
expect(home).toContain('Next month');
expect(html).toContain('Open Sorting');
expect(html).not.toContain('November Sorting');
expect(html).toContain('href="/e/weekly-pantry?month=2026-11"');
expect(html.match(/class="cal-title"/g)).toHaveLength(1);
const november = await (await app.request('/e/weekly-pantry?month=2026-11')).text();
expect(november).toContain('November 2026');
expect(november).toContain('November Sorting');
expect(november).not.toContain('Open Sorting');
expect(november).toContain('Previous month');
expect(november).toContain('Next month');
expect(november).toContain('href="/e/weekly-pantry?month=2026-10"');
expect(november).toContain('href="/e/weekly-pantry?month=2026-12"');
expect(november.match(/class="role">Edge Sorting/g)).toHaveLength(1);
const december = await (await app.request('/e/weekly-pantry?month=2026-12')).text();
expect(december).toContain('December Sorting');
expect(december).toContain('Previous month');
expect(december).not.toContain('Next month');
expect(december).not.toContain('November Sorting');
const invalid = await (await app.request('/e/weekly-pantry?month=nope')).text();
expect(invalid).toContain('October 2026');
expect(invalid).toContain('Open Sorting');
});
it('shows an empty list when nothing is upcoming', async () => {
const { app } = await buildApp({ empty: true });
const html = await (await app.request('/')).text();
expect(html).toContain('No upcoming shifts are posted.');
});
});
async function buildApp(options?: { basePath?: string; empty?: boolean }) {
const dataDir = path.join(mkdtempSync(path.join(tmpdir(), 'hope-volunteer-')), 'data');
dirs.push(path.dirname(dataDir));
const config = loadConfig(
devEnv({
DATA_DIR: dataDir,
BASE_PATH: options?.basePath ?? '',
}),
);
const db = await openAppDatabase(config);
databases.push(db);
const ids = options?.empty ? emptyIds() : seedCatalog(db);
const app = createApp(config, db, { now: NOW, publicDir: publicDirectory() });
return { app, ids, db, close: () => db.close() };
}
function emptyIds() {
return { open: 0, full: 0, cancelled: 0, past: 0, live: 0, hidden: 0 };
}
function seedCatalog(db: import('better-sqlite3').Database) {
const event = insertEvent(db, {
slug: 'weekly-pantry',
title: 'Weekly pantry',
description: 'Bring a hat.\n<script>alert(1)</script>',
published: 1,
});
const hidden = insertEvent(db, {
slug: 'hidden-draft',
title: 'Hidden draft',
description: '',
published: 0,
});
const open = insertShift(db, event, 'Open Sorting', '2026-10-15', '09:00', '12:00', 3, 0);
insertSignup(db, open);
const full = insertShift(db, event, 'Full Intake', '2026-10-16', '09:00', '12:00', 1, 0);
insertSignup(db, full);
const cancelled = insertShift(db, event, 'Cancelled Distribution', '2026-10-17', '09:00', '12:00', 4, 1);
const past = insertShift(db, event, 'Past Setup', '2026-10-14', '09:00', '12:00', 2, 0);
const live = insertShift(db, event, 'Live Greeting', '2026-10-14', '12:00', '15:00', 2, 0);
const hiddenShift = insertShift(db, hidden, 'Hidden Shift', '2026-10-18', '09:00', '12:00', 2, 0);
return { open, full, cancelled, past, live, hidden: hiddenShift };
}
function insertEvent(
db: import('better-sqlite3').Database,
values: { slug: string; title: string; description: string; published: number },
): number {
const result = db
.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES (?, ?, ?, 'Sioux Center, Iowa', 'America/Chicago', ?, '2026-10-01T15:00:00.000Z')`,
)
.run(values.slug, values.title, values.description, values.published);
return Number(result.lastInsertRowid);
}
function insertShift(
db: import('better-sqlite3').Database,
eventId: number,
role: string,
date: string,
start: string,
end: string,
capacity: number,
cancelled: number,
): number {
const times = localShiftToUtc(date, start, end, 'America/Chicago');
const result = db
.prepare(
`INSERT INTO shifts (
event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled
) VALUES (?, ?, ?, ?, ?, 'SECRET-SHIFT-NOTE', ?)`,
)
.run(eventId, role, times.startsAtUtc, times.endsAtUtc, capacity, cancelled);
return Number(result.lastInsertRowid);
}
function insertSignup(db: import('better-sqlite3').Database, shiftId: number): void {
db.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, is_minor, group_size, notes, status, reminders_off, created_at, updated_at
) VALUES (?, 'Secret Person', 'secret.person@example.invalid', 'secret.person@example.invalid', 0, 1, 'SECRET-PERSON-NOTE', 'confirmed', 0, '2026-10-01T15:00:00.000Z', '2026-10-01T15:00:00.000Z')`,
).run(shiftId);
}
describe('security headers', () => {
it('sends HSTS only for an https origin', async () => {
for (const https of [true, false]) {
const app = new Hono();
app.use('*', securityHeaders({ https }));
app.get('/', (c) => c.text('ok'));
const response = await app.request('/');
expect(response.headers.get('strict-transport-security')).toBe(https ? STRICT_TRANSPORT_SECURITY : null);
expect(response.headers.get('permissions-policy')).toBe(PERMISSIONS_POLICY);
}
});
});
+264
View File
@@ -0,0 +1,264 @@
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 { expandTemplates } from '../src/recurrence.js';
import { formatInstantInZone } from '../src/time.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const ORIGIN = 'http://127.0.0.1:3000';
const ZONE = 'America/Chicago';
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('weekly template expansion', () => {
it('adds the next eight weeks and leaves an existing occurrence alone', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'weekly', ZONE);
const templateId = insertTemplate(db, eventId, { weekday: 3, startsOn: '2026-10-14' });
db.prepare(
`INSERT INTO shifts (
event_id, template_id, occurrence_date, template_revision, role,
starts_at_utc, ends_at_utc, capacity, notes, cancelled, manually_modified, version
) VALUES (?, ?, '2026-10-14', 1, 'Kept', '2026-10-14T14:00:00.000Z', '2026-10-14T17:00:00.000Z', 2, 'leave me', 1, 1, 4)`,
).run(eventId, templateId);
db.prepare(
`INSERT INTO shifts (
event_id, template_id, occurrence_date, template_revision, role,
starts_at_utc, ends_at_utc, capacity, notes, cancelled, manually_modified, version
) VALUES (?, NULL, NULL, NULL, 'One-off', '2026-10-15T14:00:00.000Z', '2026-10-15T17:00:00.000Z', 3, '', 0, 0, 1)`,
).run(eventId);
const first = expandTemplates(db, NOW);
expect(first).toEqual({ created: 8, templates: 1, skipped: [] });
const dates = db
.prepare(
`SELECT occurrence_date AS occurrence_date, role AS role, capacity AS capacity, cancelled AS cancelled, template_revision AS template_revision
FROM shifts WHERE template_id = ? ORDER BY occurrence_date`,
)
.all(templateId) as Array<{ occurrence_date: string; role: string; capacity: number; cancelled: number; template_revision: number }>;
expect(dates.map((row) => row.occurrence_date)).toEqual([
'2026-10-14',
'2026-10-21',
'2026-10-28',
'2026-11-04',
'2026-11-11',
'2026-11-18',
'2026-11-25',
'2026-12-02',
'2026-12-09',
]);
expect(dates[0]).toMatchObject({ role: 'Kept', capacity: 2, cancelled: 1, template_revision: 1 });
expect(dates.slice(1).every((row) => row.role === 'Sorting' && row.capacity === 6 && row.cancelled === 0)).toBe(true);
expect(db.prepare("SELECT role AS role FROM shifts WHERE template_id IS NULL").get()).toEqual({ role: 'One-off' });
const again = expandTemplates(db, NOW, { coordinatorId: 4 });
expect(again.created).toBe(0);
expect(db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action = 'template.expand'").get()).toEqual({ n: 1 });
const audit = db.prepare("SELECT coordinator_id AS coordinator_id, detail_json AS detail_json FROM audit").get() as {
coordinator_id: number | null;
detail_json: string;
};
expect(audit.coordinator_id).toBeNull();
expect(audit.detail_json).not.toContain('@');
expect(JSON.parse(audit.detail_json)).toEqual({ templateId, created: 8 });
});
it('keeps 9:00 local on both sides of a daylight-saving change', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'spring', ZONE);
insertTemplate(db, eventId, { weekday: 0, startsOn: '2026-03-01' });
expandTemplates(db, '2026-03-01T17:00:00.000Z');
expect(localClock(db, '2026-03-01')).toEqual({ time24: '09:00', abbreviation: 'CST' });
expect(localClock(db, '2026-03-08')).toEqual({ time24: '09:00', abbreviation: 'CDT' });
expect(localClock(db, '2026-03-15')).toEqual({ time24: '09:00', abbreviation: 'CDT' });
const fall = insertEvent(db, 'fall', ZONE);
insertTemplate(db, fall, { weekday: 0, startsOn: '2026-10-25' });
expandTemplates(db, '2026-10-25T17:00:00.000Z', { eventId: fall });
expect(localClock(db, '2026-10-25')).toEqual({ time24: '09:00', abbreviation: 'CDT' });
expect(localClock(db, '2026-11-01')).toEqual({ time24: '09:00', abbreviation: 'CST' });
});
it('skips a local time that does not exist or happens twice', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'gap', ZONE);
insertTemplate(db, eventId, { weekday: 0, startsOn: '2026-03-01', start: '02:30', end: '04:00' });
const gap = expandTemplates(db, '2026-03-01T17:00:00.000Z');
expect(gap.created).toBeGreaterThan(0);
expect(gap.skipped.some((message) => message.includes('2026-03-08') && message.includes('does not exist'))).toBe(true);
expect(db.prepare("SELECT COUNT(*) AS n FROM shifts WHERE occurrence_date = '2026-03-08'").get()).toEqual({ n: 0 });
expect(localClock(db, '2026-03-01').time24).toBe('02:30');
expect(localClock(db, '2026-03-15').time24).toBe('02:30');
const overlapEvent = insertEvent(db, 'overlap', ZONE);
insertTemplate(db, overlapEvent, { weekday: 0, startsOn: '2026-10-25', start: '01:30', end: '03:30' });
const overlap = expandTemplates(db, '2026-10-25T17:00:00.000Z', { eventId: overlapEvent });
expect(overlap.skipped.some((message) => message.includes('2026-11-01') && message.includes('happens twice'))).toBe(true);
expect(db.prepare("SELECT COUNT(*) AS n FROM shifts WHERE event_id = ? AND occurrence_date = '2026-11-01'").get(overlapEvent)).toEqual({ n: 0 });
expect(localClock(db, '2026-10-25', overlapEvent).time24).toBe('01:30');
});
it('respects the template dates and does not fill another event', async () => {
const db = await openDb();
const limited = insertEvent(db, 'limited', ZONE);
insertTemplate(db, limited, { weekday: 3, startsOn: '2026-11-04', endsOn: '2026-11-18' });
insertTemplate(db, limited, { weekday: 3, startsOn: '2026-10-14', active: 0 });
const other = insertEvent(db, 'other', ZONE);
insertTemplate(db, other, { weekday: 3, startsOn: '2026-10-14' });
const result = expandTemplates(db, NOW, { eventId: limited });
expect(result.templates).toBe(1);
expect(
db.prepare('SELECT occurrence_date AS occurrence_date FROM shifts WHERE event_id = ? ORDER BY occurrence_date').all(limited),
).toEqual([{ occurrence_date: '2026-11-04' }, { occurrence_date: '2026-11-11' }, { occurrence_date: '2026-11-18' }]);
expect(db.prepare('SELECT COUNT(*) AS n FROM shifts WHERE event_id = ?').get(other)).toEqual({ n: 0 });
});
});
describe('add weekly shifts', () => {
it('adds from the event page once and refuses a form that is out of date', async () => {
const { app, db } = await buildApp();
const eventId = insertEvent(db, 'weekly-pantry', ZONE);
insertTemplate(db, eventId, { weekday: 3, startsOn: '2026-10-14' });
const empty = insertEvent(db, 'plain', ZONE);
const cookie = await signIn(app, db);
const missing = await postGenerate(app, eventId, cookie, { csrf: 'wrong' });
expect(missing.status).toBe(403);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(0);
const added = await postGenerate(app, eventId, cookie);
expect(added.status).toBe(303);
expect(added.headers.get('location')).toBe(`/admin/events/${eventId}?notice=generated`);
const page = await app.request(added.headers.get('location') ?? '', { headers: { cookie } });
const html = await page.text();
expect(html).toContain('Weekly shifts for the next eight weeks are on the schedule.');
expect(html).toContain('Add weekly shifts');
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(9);
const repeat = await postGenerate(app, eventId, cookie);
expect(repeat.headers.get('location')).toBe(`/admin/events/${eventId}?notice=generated`);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(9);
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'template.expand'")).toBe(1);
const none = await postGenerate(app, empty, cookie);
expect(none.headers.get('location')).toBe(`/admin/events/${empty}?notice=no-template`);
});
});
async function openDb() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-recur-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
return db;
}
async function buildApp() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-recur-http-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
bootstrapAdmin(db, config.bootstrapAdminEmail, NOW);
const app = createApp(config, db, {
now: NOW,
clientIp: () => '203.0.113.10',
verifyTurnstile: async () => ({ ok: true }),
});
return { app, db };
}
function insertEvent(db: Awaited<ReturnType<typeof openDb>>, slug: string, tz: string): number {
const saved = db
.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES (?, ?, '', 'Sioux Center, Iowa', ?, 1, ?)`,
)
.run(slug, slug, tz, NOW);
return Number(saved.lastInsertRowid);
}
function insertTemplate(
db: Awaited<ReturnType<typeof openDb>>,
eventId: number,
options: { weekday: number; startsOn: string; endsOn?: string; start?: string; end?: string; active?: number },
): number {
const saved = db
.prepare(
`INSERT INTO shift_templates (
event_id, role, weekday, start_local, end_local, capacity, starts_on, ends_on, active, revision
) VALUES (?, 'Sorting', ?, ?, ?, 6, ?, ?, ?, 1)`,
)
.run(
eventId,
options.weekday,
options.start ?? '09:00',
options.end ?? '12:00',
options.startsOn,
options.endsOn ?? null,
options.active ?? 1,
);
return Number(saved.lastInsertRowid);
}
function localClock(db: Awaited<ReturnType<typeof openDb>>, date: string, eventId?: number) {
const row = db
.prepare(
`SELECT starts_at_utc AS starts_at_utc FROM shifts
WHERE occurrence_date = ?${eventId === undefined ? '' : ' AND event_id = ?'}`,
)
.get(...(eventId === undefined ? [date] : [date, eventId])) as { starts_at_utc: string };
const clock = formatInstantInZone(row.starts_at_utc, ZONE);
return { time24: clock.time24, abbreviation: clock.abbreviation };
}
async function signIn(app: Awaited<ReturnType<typeof buildApp>>['app'], db: Awaited<ReturnType<typeof openDb>>) {
await app.request('/login', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ email: 'coordinator@example.invalid', company_website: '', 'cf-turnstile-response': 'token' }),
});
const queued = db.prepare("SELECT body_text AS body_text FROM outbox WHERE kind = 'magic_link'").get() as { body_text: string };
const token = /\/login\/link\/([A-Za-z0-9_-]+)/.exec(queued.body_text)?.[1] ?? '';
const page = await app.request(`/login/link/${token}`);
const proof = /name="proof"[^>]*value="([^"]*)"/.exec(await page.text())?.[1] ?? '';
const signedIn = await app.request(`/login/link/${token}`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ proof }),
});
const cookie = /hope_session=([^;]+)/.exec(signedIn.headers.get('set-cookie') ?? '')?.[1] ?? '';
return `hope_session=${cookie}`;
}
async function postGenerate(
app: Awaited<ReturnType<typeof buildApp>>['app'],
eventId: number,
cookie: string,
options?: { csrf?: string },
) {
const current = await app.request(`/admin/events/${eventId}`, { headers: { cookie } });
const csrf = options?.csrf ?? (/name="csrf"[^>]*value="([^"]*)"/.exec(await current.text())?.[1] ?? '');
return app.request(`/admin/events/${eventId}/generate`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ csrf }),
});
}
function count(db: Awaited<ReturnType<typeof openDb>>, sql: string): number {
return Number((db.prepare(sql).get() as { n: number }).n);
}
+256
View File
@@ -0,0 +1,256 @@
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { updateShift } from '../src/admin/store.js';
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 { deliverDueMail } from '../src/mail/deliver.js';
import type { Mailer } from '../src/mail/types.js';
import { issueReminderOffToken } from '../src/reminders.js';
import { queueDueReminders } from '../src/reminders.js';
import { reserveSignup, type ReserveInput } from '../src/signup.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const SOON = '2026-10-14T18:30:00.000Z';
const SOON_END = '2026-10-14T20:00:00.000Z';
const LATER_START = '2026-10-15T14:00:00.000Z';
const LATER_END = '2026-10-15T17:00:00.000Z';
const FAR_START = '2026-10-20T14:00:00.000Z';
const FAR_END = '2026-10-20T17:00:00.000Z';
const SECRET = 'dev-only-change-me-not-for-production-use';
const ORIGIN = 'http://127.0.0.1:3000';
const MAIL = {
baseUrl: ORIGIN,
basePath: '',
from: 'Hope Food Pantry <volunteer@example.invalid>',
replyTo: 'volunteer@example.invalid',
};
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('reminder mail', () => {
it('queues the 48 hour reminder, sends it once, and records provider acceptance', async () => {
const db = await openDb();
const shiftId = insertShift(db, LATER_START, LATER_END);
reserveSignup(db, reservation(shiftId, { name: 'Pat <script>' }));
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 1, suppressed: 0 });
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 });
const reminders = db.prepare(`SELECT kind, status, subject, body_html, headers_json FROM outbox WHERE kind = 'reminder'`).all() as Array<{
kind: string;
status: string;
subject: string;
body_html: string;
headers_json: string;
}>;
expect(reminders).toEqual([
expect.objectContaining({ kind: 'reminder', status: 'pending', subject: 'Reminder: Sorting' }),
]);
expect(reminders[0]?.body_html).toContain('Pat &lt;script&gt;');
expect(reminders[0]?.body_html).not.toContain('<script>');
expect(reminders[0]?.body_html).toContain('use the link in your confirmation email');
const headers = JSON.parse(reminders[0]?.headers_json ?? '{}') as Record<string, string>;
expect(headers['List-Unsubscribe']).toContain('mailto:volunteer@example.invalid?subject=Stop%20reminder%20emails');
expect(headers['List-Unsubscribe-Post']).toBe('List-Unsubscribe=One-Click');
expect(db.prepare(`SELECT kind, sent_at FROM reminders_sent`).get()).toEqual({ kind: '48h', sent_at: null });
const seen: string[] = [];
const mailer: Mailer = {
async send(message) {
seen.push(message.subject);
if (message.subject.startsWith('Reminder:')) {
expect(message.headers?.['List-Unsubscribe-Post']).toBe('List-Unsubscribe=One-Click');
}
return { result: 'sent', providerId: 'reminder-1' };
},
};
expect(await deliverDueMail(db, mailer, NOW)).toBe(2);
expect(seen).toEqual(["You're signed up for Sorting", 'Reminder: Sorting']);
expect(db.prepare(`SELECT sent_at FROM reminders_sent`).get()).toEqual({ sent_at: NOW });
expect(await deliverDueMail(db, mailer, NOW)).toBe(0);
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'reminder'`).get()).toEqual({ n: 1 });
});
it('sends only the closest reminder when several are already due', async () => {
const db = await openDb();
const shiftId = insertShift(db, SOON, SOON_END);
reserveSignup(db, reservation(shiftId, { email: 'late@example.invalid', operationId: 'late-signup' }));
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 1, suppressed: 1 });
const rows = db.prepare(`SELECT status, body_text FROM outbox WHERE kind = 'reminder' ORDER BY id`).all() as Array<{ status: string; body_text: string }>;
expect(rows.map((row) => row.status)).toEqual(['pending', 'cancelled']);
expect(rows[1]?.body_text).not.toContain('@');
expect(db.prepare(`SELECT kind FROM reminders_sent ORDER BY kind`).all()).toEqual([{ kind: '2h' }, { kind: '48h' }]);
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 });
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'reminder'`).get()).toEqual({ n: 2 });
});
it('does not queue a reminder after the shift has started, or when reminders are off', async () => {
const db = await openDb();
const started = insertShift(db, '2026-10-14T14:00:00.000Z', '2026-10-14T17:00:00.000Z');
insertConfirmed(db, started, 'started@example.invalid');
const far = insertShift(db, FAR_START, FAR_END, 'far');
reserveSignup(db, reservation(far, { email: 'far@example.invalid', operationId: 'far-signup' }));
const quiet = insertShift(db, LATER_START, LATER_END, 'quiet');
reserveSignup(db, reservation(quiet, { email: 'quiet@example.invalid', operationId: 'quiet-signup' }));
db.prepare(`UPDATE signups SET reminders_off = 1 WHERE email_norm = 'quiet@example.invalid'`).run();
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 });
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'reminder'`).get()).toEqual({ n: 0 });
expect(db.prepare(`SELECT status FROM outbox WHERE to_email = 'quiet@example.invalid'`).get()).toEqual({ status: 'pending' });
});
it('drops a reminder that is no longer current and queues again after the shift version changes', async () => {
const db = await openDb();
bootstrapAdmin(db, 'coordinator@example.invalid', NOW);
const shiftId = insertShift(db, LATER_START, LATER_END);
reserveSignup(db, reservation(shiftId));
queueDueReminders(db, MAIL, SECRET, NOW);
db.prepare(`UPDATE signups SET reminders_off = 1 WHERE email_norm = 'pat.review@example.invalid'`).run();
const mailer: Mailer = { async send() { return { result: 'sent', providerId: null }; } };
expect(await deliverDueMail(db, mailer, NOW)).toBe(1);
expect(db.prepare(`SELECT status, last_error FROM outbox WHERE kind = 'reminder'`).get()).toEqual({
status: 'cancelled',
last_error: 'Reminders were turned off before this message was sent.',
});
expect(db.prepare(`SELECT sent_at FROM reminders_sent`).get()).toEqual({ sent_at: null });
db.prepare(`UPDATE signups SET reminders_off = 0 WHERE email_norm = 'pat.review@example.invalid'`).run();
const changed = updateShift(db, 1, shiftId, { role: 'Intake', date: '2026-10-15', start: '09:00', end: '12:00', capacity: 4 }, NOW, MAIL);
expect(changed.ok).toBe(true);
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'reminder' AND subject = 'Reminder: Sorting'`).get()).toEqual({ status: 'cancelled' });
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 1, suppressed: 0 });
expect(db.prepare(`SELECT subject, status FROM outbox WHERE kind = 'reminder' AND status = 'pending'`).get()).toEqual({
subject: 'Reminder: Intake',
status: 'pending',
});
expect(db.prepare(`SELECT shift_version FROM reminders_sent WHERE kind = '48h' ORDER BY shift_version`).all()).toEqual([
{ shift_version: 1 },
{ shift_version: 2 },
]);
});
it('turns reminders off from the email link without cancelling, and leaves a visit unchanged', async () => {
const { app, db } = await buildApp();
const shiftId = insertShift(db, LATER_START, LATER_END);
const saved = reserveSignup(db, reservation(shiftId));
expect(saved.ok).toBe(true);
if (!saved.ok) return;
queueDueReminders(db, MAIL, SECRET, NOW);
const signupId = Number((db.prepare(`SELECT id AS id FROM signups`).get() as { id: number }).id);
const token = issueReminderOffToken(SECRET, signupId);
const visit = await app.request(`/u/${token}`);
expect(visit.status).toBe(200);
expect(await visit.text()).toContain('Stop reminder emails');
expect(db.prepare(`SELECT reminders_off, status FROM signups`).get()).toEqual({ reminders_off: 0, status: 'confirmed' });
const stopped = await app.request(`/u/${token}`, { method: 'POST' });
expect(stopped.status).toBe(200);
expect(await stopped.text()).toContain('Reminder emails for this signup are off.');
expect(db.prepare(`SELECT reminders_off, status FROM signups`).get()).toEqual({ reminders_off: 1, status: 'confirmed' });
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'reminder' AND status = 'pending'`).get()).toBeUndefined();
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'confirmation'`).get()).toEqual({ status: 'pending' });
const again = await app.request(`/u/${token}`, { method: 'POST' });
expect(again.status).toBe(200);
expect(db.prepare(`SELECT reminders_off FROM signups`).get()).toEqual({ reminders_off: 1 });
const missing = await app.request('/u/1.not-a-real-mac-value-here');
expect(missing.status).toBe(404);
expect(db.prepare(`SELECT reminders_off FROM signups`).get()).toEqual({ reminders_off: 1 });
});
it('turns reminders off from the private signup page and keeps the signup', async () => {
const { app, db } = await buildApp();
const shiftId = insertShift(db, LATER_START, LATER_END);
const saved = reserveSignup(db, reservation(shiftId));
expect(saved.ok && saved.manageToken).toBeTruthy();
if (!saved.ok || !saved.manageToken) return;
const page = await app.request(`/m/${saved.manageToken}`);
const html = await page.text();
const token = /name="reminder_token"[^>]*value="([^"]*)"/.exec(html)?.[1] ?? '';
expect(html).toContain('Stop reminder emails');
const stopped = await app.request(`/m/${saved.manageToken}/reminders`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ reminder_token: token }),
});
expect(stopped.status).toBe(303);
expect(db.prepare(`SELECT reminders_off, status FROM signups`).get()).toEqual({ reminders_off: 1, status: 'confirmed' });
const after = await app.request(`/m/${saved.manageToken}`);
const afterHtml = await after.text();
expect(afterHtml).toContain('Reminder emails for this signup are off.');
expect(afterHtml).not.toContain('name="reminder_token"');
});
});
async function openDb() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-reminder-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
return db;
}
async function buildApp() {
const db = await openDb();
const config = loadConfig(devEnv({ DATA_DIR: path.join(rootOf(db), 'data') }));
const app = createApp(config, db, { now: NOW, clientIp: () => '203.0.113.40' });
return { app, db };
}
function rootOf(db: { name: string }): string {
return path.dirname(path.dirname(db.name));
}
function insertShift(db: Awaited<ReturnType<typeof openDb>>, start: string, end: string, slug = 'weekly'): number {
const eventId = Number(
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES (?, 'Weekly pantry', '', 'Sioux Center, Iowa', 'America/Chicago', 1, ?)`,
).run(slug, NOW).lastInsertRowid,
);
return Number(
db.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, 'Sorting', ?, ?, 4, '', 0)`,
).run(eventId, start, end).lastInsertRowid,
);
}
function insertConfirmed(db: Awaited<ReturnType<typeof openDb>>, shiftId: number, email: string): void {
db.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, is_minor, group_size, status, reminders_off, created_at, updated_at,
manage_token_hash, token_expires_at
) VALUES (?, 'Ada', ?, ?, 0, 1, 'confirmed', 0, ?, ?, 'abc', ?)`,
).run(shiftId, email, email, NOW, NOW, '2026-10-22T17:00:00.000Z');
}
function reservation(shiftId: number, overrides: Partial<ReserveInput> = {}): ReserveInput {
return {
shiftId,
name: 'Pat Review',
email: 'pat.review@example.invalid',
phone: null,
notes: null,
isMinor: false,
guardianName: null,
guardianEmail: null,
operationId: 'reminder-operation',
now: NOW,
mail: MAIL,
...overrides,
};
}
+382
View File
@@ -0,0 +1,382 @@
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { deleteCancelledSignup, deleteEvent, deleteEndedTemplate, deleteFinishedShift } from '../src/admin/store.js';
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 { expandTemplates } from '../src/recurrence.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const PAST_END = '2026-10-14T17:00:00.000Z';
const FUTURE_START = '2026-10-21T14:00:00.000Z';
const FUTURE_END = '2026-10-21T17:00:00.000Z';
const ORIGIN = 'http://127.0.0.1:3000';
const ZONE = 'America/Chicago';
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('removing finished records', () => {
it('deletes a cancelled person and the mail tied to them', async () => {
const db = await openDb();
const eventId = insertEvent(db);
const shiftId = insertShift(db, eventId, { cancelled: 1 });
const cancelledId = insertSignup(db, shiftId, 'cancelled');
const confirmedId = insertSignup(db, shiftId, 'confirmed');
const outboxId = insertOutbox(db, cancelledId, shiftId);
db.prepare(
`INSERT INTO reminders_sent (signup_id, kind, shift_version, outbox_id, queued_at)
VALUES (?, '48h', 1, ?, ?)`,
).run(cancelledId, outboxId, NOW);
expect(deleteCancelledSignup(db, 1, confirmedId, NOW)).toEqual({ ok: false, error: 'Cancel this signup before removing it.' });
expect(deleteCancelledSignup(db, 1, cancelledId, NOW)).toEqual({ ok: true, shiftId });
expect(count(db, 'SELECT COUNT(*) AS n FROM signups WHERE id = ?', cancelledId)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups WHERE id = ?', confirmedId)).toBe(1);
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM reminders_sent')).toBe(0);
const audit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'signup.delete'`).get() as { detail_json: string };
expect(audit.detail_json).not.toContain('@');
});
it('deletes an empty finished shift and lets an active template add that date again', async () => {
const db = await openDb();
const eventId = insertEvent(db);
const openId = insertShift(db, eventId, { start: FUTURE_START, end: FUTURE_END });
expect(deleteFinishedShift(db, 1, openId, NOW).ok).toBe(false);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE id = ?', openId)).toBe(1);
const templateId = insertTemplate(db, eventId, 1);
expandTemplates(db, NOW, { eventId, coordinatorId: 1 });
const generated = db.prepare(`SELECT id AS id FROM shifts WHERE template_id = ? AND occurrence_date = '2026-10-21'`).get(templateId) as { id: number };
db.prepare('UPDATE shifts SET cancelled = 1 WHERE id = ?').run(generated.id);
expect(deleteFinishedShift(db, 1, generated.id, NOW)).toEqual({ ok: true, eventId });
expandTemplates(db, NOW, { eventId, coordinatorId: 1 });
expect(count(db, `SELECT COUNT(*) AS n FROM shifts WHERE template_id = ? AND occurrence_date = '2026-10-21'`, templateId)).toBe(1);
const occupied = insertShift(db, eventId, { cancelled: 1 });
insertSignup(db, occupied, 'cancelled');
expect(deleteFinishedShift(db, 1, occupied, NOW)).toEqual({ ok: false, error: 'Remove everyone on this roster first.' });
});
it('removes an ended template and leaves its shifts in place', async () => {
const db = await openDb();
const eventId = insertEvent(db);
const activeId = insertTemplate(db, eventId, 1);
expect(deleteEndedTemplate(db, 1, eventId, activeId, NOW).ok).toBe(false);
db.prepare('UPDATE shift_templates SET active = 0 WHERE id = ?').run(activeId);
const shiftId = insertShift(db, eventId, { templateId: activeId, occurrence: '2026-10-14' });
expect(deleteEndedTemplate(db, 1, eventId, activeId, NOW)).toEqual({ ok: true, eventId });
expect(count(db, 'SELECT COUNT(*) AS n FROM shift_templates')).toBe(0);
const shift = db.prepare('SELECT template_id, occurrence_date, template_revision FROM shifts WHERE id = ?').get(shiftId) as {
template_id: number | null;
occurrence_date: string | null;
template_revision: number | null;
};
expect(shift).toEqual({ template_id: null, occurrence_date: null, template_revision: null });
expect(count(db, `SELECT COUNT(*) AS n FROM audit WHERE action = 'template.delete'`)).toBe(1);
});
it('removes through the coordinator pages and refuses a stale form', async () => {
const { app, db } = await buildApp();
const eventId = insertEvent(db);
const shiftId = insertShift(db, eventId, { cancelled: 1, start: PAST_END, end: NOW });
const signupId = insertSignup(db, shiftId, 'cancelled');
const cookie = await signIn(app, db);
const stale = await postRemove(app, cookie, `/admin/signups/${signupId}/remove`, 'nope');
expect(stale.status).toBe(403);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(1);
const removedPerson = await postRemove(app, cookie, `/admin/signups/${signupId}/remove`);
expect(removedPerson.status).toBe(303);
expect(removedPerson.headers.get('location')).toBe(`/admin/shifts/${shiftId}?notice=signup-removed`);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
const removedShift = await postRemove(app, cookie, `/admin/shifts/${shiftId}/remove`);
expect(removedShift.headers.get('location')).toBe(`/admin/events/${eventId}?notice=shift-removed`);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(0);
const templateId = insertTemplate(db, eventId, 0);
const kept = insertShift(db, eventId, { templateId, occurrence: '2026-10-21', start: FUTURE_START, end: FUTURE_END });
const removedTemplate = await postRemove(app, cookie, `/admin/events/${eventId}/templates/${templateId}/remove`);
expect(removedTemplate.headers.get('location')).toBe(`/admin/events/${eventId}?notice=template-removed`);
expect(count(db, 'SELECT COUNT(*) AS n FROM shift_templates')).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE id = ?', kept)).toBe(1);
const page = await app.request(`/admin/events/${eventId}?notice=template-removed`, { headers: { cookie } });
expect(await page.text()).toContain('That weekly template is removed.');
});
it('deletes a hidden event together with its shifts, templates, and signups', async () => {
const db = await openDb();
const kept = insertEvent(db, { slug: 'kept', title: 'Kept drive', published: 0 });
const keptShift = insertShift(db, kept, { start: FUTURE_START, end: FUTURE_END });
const keptSignup = insertSignup(db, keptShift, 'confirmed', 'kept@example.invalid');
const keptMail = insertOutbox(db, keptSignup, keptShift);
db.prepare(
`INSERT INTO reminders_sent (signup_id, kind, shift_version, outbox_id, queued_at)
VALUES (?, '48h', 1, ?, ?)`,
).run(keptSignup, keptMail, NOW);
const published = insertEvent(db, { slug: 'open-day', title: 'Open day', published: 1 });
const templateId = insertTemplate(db, published, 1);
const openShift = insertShift(db, published, { start: FUTURE_START, end: FUTURE_END, templateId, occurrence: '2026-10-21' });
const signupId = insertSignup(db, openShift, 'confirmed', 'ada@example.invalid');
const outboxId = insertOutbox(db, signupId, openShift);
db.prepare(
`INSERT INTO reminders_sent (signup_id, kind, shift_version, outbox_id, queued_at)
VALUES (?, '48h', 1, ?, ?)`,
).run(signupId, outboxId, NOW);
expect(deleteEvent(db, 1, published, NOW)).toEqual({ ok: true });
expect(count(db, 'SELECT COUNT(*) AS n FROM events WHERE id = ?', published)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE event_id = ?', published)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM shift_templates WHERE id = ?', templateId)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups WHERE id = ?', signupId)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox WHERE id = ?', outboxId)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM reminders_sent WHERE signup_id = ?', signupId)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM events WHERE id = ?', kept)).toBe(1);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE id = ?', keptShift)).toBe(1);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups WHERE id = ?', keptSignup)).toBe(1);
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox WHERE id = ?', keptMail)).toBe(1);
expect(count(db, 'SELECT COUNT(*) AS n FROM reminders_sent WHERE signup_id = ?', keptSignup)).toBe(1);
expect(db.prepare('PRAGMA foreign_key_check').all()).toEqual([]);
const audit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'event.delete'`).get() as { detail_json: string };
expect(JSON.parse(audit.detail_json)).toEqual({ eventId: published, shifts: 1, templates: 1, signups: 1 });
expect(audit.detail_json).not.toContain('@');
});
it('removes an empty hidden event from the coordinator page', async () => {
const { app, db } = await buildApp();
const eventId = insertEvent(db);
const hidden = insertEvent(db, { slug: 'old-drive', title: 'Old drive', published: 0 });
const cookie = await signIn(app, db);
const asking = await app.request(`/admin/events/${eventId}/remove`, { headers: { cookie } });
const askingPage = await asking.text();
expect(askingPage).toContain('This deletes the event.');
expect(askingPage).toContain('This event is on the public list. Removing it takes that listing away.');
expect(askingPage).toContain('Remove this event</button>');
const stale = await postRemove(app, cookie, `/admin/events/${hidden}/remove`, 'nope');
expect(stale.status).toBe(403);
expect(count(db, 'SELECT COUNT(*) AS n FROM events WHERE id = ?', hidden)).toBe(1);
const removed = await postRemove(app, cookie, `/admin/events/${hidden}/remove`);
expect(removed.status).toBe(303);
expect(removed.headers.get('location')).toBe('/admin?notice=event-removed');
expect(count(db, 'SELECT COUNT(*) AS n FROM events WHERE id = ?', hidden)).toBe(0);
const home = await app.request('/admin?notice=event-removed', { headers: { cookie } });
expect(await home.text()).toContain('That event is removed.');
expect(count(db, 'SELECT COUNT(*) AS n FROM events WHERE id = ?', eventId)).toBe(1);
});
it('removes a public event and the shifts under it after one confirmation', async () => {
const { app, db } = await buildApp();
const kept = insertEvent(db, { slug: 'kept-drive', title: 'Kept drive', published: 1 });
const keptShift = insertShift(db, kept);
const eventId = insertEvent(db, { slug: 'old-drive-full', title: 'Old drive', published: 1 });
const shiftId = insertShift(db, eventId, { start: FUTURE_START, end: FUTURE_END });
insertTemplate(db, eventId, 1);
const signupId = insertSignup(db, shiftId, 'confirmed', 'ada@example.invalid');
const cookie = await signIn(app, db);
const page = await app.request(`/admin/events/${eventId}/remove`, { headers: { cookie } });
const html = await page.text();
expect(html).toContain('This deletes the event, 1 shift, and 1 weekly template.');
expect(html).toContain('The signup on those shifts is deleted too, including the name and email.');
expect(html).toContain('This event is on the public list. Removing it takes that listing away.');
expect(html).toContain('Remove this event</button>');
const removed = await postRemove(app, cookie, `/admin/events/${eventId}/remove`);
expect(removed.status).toBe(303);
expect(removed.headers.get('location')).toBe('/admin?notice=event-removed');
expect(count(db, 'SELECT COUNT(*) AS n FROM events WHERE id = ?', eventId)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE id = ?', shiftId)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups WHERE id = ?', signupId)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM events WHERE id = ?', kept)).toBe(1);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE id = ?', keptShift)).toBe(1);
});
it('removes selected finished shifts together and leaves the rest', async () => {
const { app, db } = await buildApp();
const eventId = insertEvent(db, { published: 0, slug: 'batch', title: 'Batch' });
const first = insertShift(db, eventId, { cancelled: 1 });
const second = insertShift(db, eventId, { cancelled: 1 });
const kept = insertShift(db, eventId, { start: FUTURE_START, end: FUTURE_END });
const cookie = await signIn(app, db);
const page = await app.request(`/admin/events/${eventId}`, { headers: { cookie } });
const token = /name="csrf"[^>]*value="([^"]*)"/.exec(await page.text())?.[1] ?? '';
const refused = await app.request(`/admin/events/${eventId}/shifts/remove`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams([
['csrf', token],
['shift[]', String(first)],
['shift[]', String(kept)],
]),
});
expect(refused.status).toBe(400);
expect(await refused.text()).toContain('Cancel this shift, or wait until it has ended, before removing it.');
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE event_id = ?', eventId)).toBe(3);
const removed = await app.request(`/admin/events/${eventId}/shifts/remove`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams([
['csrf', token],
['shift[]', String(first)],
['shift[]', String(second)],
]),
});
expect(removed.status).toBe(303);
expect(removed.headers.get('location')).toBe(`/admin/events/${eventId}?notice=shifts-removed`);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE id = ?', first)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE id = ?', second)).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE id = ?', kept)).toBe(1);
const after = await app.request(`/admin/events/${eventId}?notice=shifts-removed`, { headers: { cookie } });
const html = await after.text();
expect(html).toContain('Those shifts are removed.');
expect(html).toContain('data-dismiss-notice');
});
});
async function openDb() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-remove-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
bootstrapAdmin(db, config.bootstrapAdminEmail, NOW);
return db;
}
async function buildApp() {
const db = await openDb();
const config = loadConfig(devEnv({ DATA_DIR: path.join(rootOf(db), 'data') }));
const app = createApp(config, db, {
now: NOW,
clientIp: () => '203.0.113.20',
verifyTurnstile: async () => ({ ok: true }),
});
return { app, db };
}
function rootOf(db: { name: string }): string {
return path.dirname(path.dirname(db.name));
}
function insertEvent(
db: Awaited<ReturnType<typeof openDb>>,
options: { slug?: string; title?: string; published?: number } = {},
): number {
const saved = db
.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES (?, ?, '', 'Sioux Center, Iowa', ?, ?, ?)`,
)
.run(options.slug ?? 'weekly', options.title ?? 'Weekly pantry', ZONE, options.published ?? 1, NOW);
return Number(saved.lastInsertRowid);
}
function insertTemplate(db: Awaited<ReturnType<typeof openDb>>, eventId: number, active: number): number {
const saved = db
.prepare(
`INSERT INTO shift_templates (
event_id, role, weekday, start_local, end_local, capacity, starts_on, active, revision
) VALUES (?, 'Sorting', 3, '09:00', '12:00', 6, '2026-10-14', ?, 1)`,
)
.run(eventId, active);
return Number(saved.lastInsertRowid);
}
function insertShift(
db: Awaited<ReturnType<typeof openDb>>,
eventId: number,
options: { cancelled?: number; start?: string; end?: string; templateId?: number; occurrence?: string } = {},
): number {
const saved = db
.prepare(
`INSERT INTO shifts (
event_id, template_id, occurrence_date, template_revision, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled
) VALUES (?, ?, ?, ?, 'Sorting', ?, ?, 3, '', ?)`,
)
.run(
eventId,
options.templateId ?? null,
options.templateId ? options.occurrence ?? '2026-10-14' : null,
options.templateId ? 1 : null,
options.start ?? '2026-10-14T14:00:00.000Z',
options.end ?? PAST_END,
options.cancelled ?? 0,
);
return Number(saved.lastInsertRowid);
}
function insertSignup(
db: Awaited<ReturnType<typeof openDb>>,
shiftId: number,
status: 'confirmed' | 'cancelled',
email = 'ada@example.invalid',
): number {
const saved = db
.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, is_minor, group_size, status, reminders_off, created_at, updated_at
) VALUES (?, 'Ada', ?, ?, 0, 1, ?, 0, ?, ?)`,
)
.run(shiftId, email, email, status, NOW, NOW);
return Number(saved.lastInsertRowid);
}
function insertOutbox(db: Awaited<ReturnType<typeof openDb>>, signupId: number, shiftId: number): number {
const saved = db
.prepare(
`INSERT INTO outbox (
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
headers_json, send_after, attempts, status, created_at
) VALUES (?, ?, ?, 'cancelled', 'ada@example.invalid', 'Cancelled', 'Gone', '<p>Gone</p>', '{}', ?, 0, 'pending', ?)`,
)
.run(`cancelled:${signupId}`, signupId, shiftId, NOW, NOW);
return Number(saved.lastInsertRowid);
}
async function signIn(app: Awaited<ReturnType<typeof buildApp>>['app'], db: Awaited<ReturnType<typeof openDb>>) {
await app.request('/login', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ email: 'coordinator@example.invalid', company_website: '', 'cf-turnstile-response': 'token' }),
});
const queued = db.prepare(`SELECT body_text AS body_text FROM outbox WHERE kind = 'magic_link'`).get() as { body_text: string };
const token = /\/login\/link\/([A-Za-z0-9_-]+)/.exec(queued.body_text)?.[1] ?? '';
const page = await app.request(`/login/link/${token}`);
const proof = /name="proof"[^>]*value="([^"]*)"/.exec(await page.text())?.[1] ?? '';
const signedIn = await app.request(`/login/link/${token}`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ proof }),
});
const cookie = /hope_session=([^;]+)/.exec(signedIn.headers.get('set-cookie') ?? '')?.[1] ?? '';
return `hope_session=${cookie}`;
}
async function postRemove(app: Awaited<ReturnType<typeof buildApp>>['app'], cookie: string, pathName: string, csrf?: string) {
const current = await app.request(pathName, { headers: { cookie } });
const token = csrf ?? (/name="csrf"[^>]*value="([^"]*)"/.exec(await current.text())?.[1] ?? '');
return app.request(pathName, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ csrf: token }),
});
}
function count(db: Awaited<ReturnType<typeof openDb>>, sql: string, ...params: number[]): number {
return Number((db.prepare(sql).get(...params) as { n: number }).n);
}
+69
View File
@@ -0,0 +1,69 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { verifyTurnstile } from '../src/turnstile.js';
import { createPostmarkMailer } from '../src/mail/postmark.js';
import { createSesMailer } from '../src/mail/ses.js';
const timeout = AbortSignal.timeout.bind(AbortSignal);
afterEach(() => vi.restoreAllMocks());
function shortDeadline(expected: number) {
vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms) => {
expect(ms).toBe(expected);
return timeout(5);
});
}
function stalled(signal?: AbortSignal | null): Promise<never> {
if (!signal) throw new Error('Missing request deadline');
return new Promise((_resolve, reject) => {
if (signal.aborted) reject(signal.reason);
else signal.addEventListener('abort', () => reject(signal.reason), {once:true});
});
}
const mail = {
from:'pantry@example.invalid', to:'volunteer@example.invalid', replyTo:'pantry@example.invalid',
subject:'Test', text:'Test', html:'<p>Test</p>',
};
describe('outbound request deadlines', () => {
it('fails closed when Turnstile never responds', async () => {
shortDeadline(10_000);
const result = await verifyTurnstile({
secret:'real-secret', token:'token', remoteIp:'203.0.113.1',
expectedHostname:'example.invalid', expectedAction:'signup',
fetchImpl: async (_url, init) => stalled(init?.signal),
});
expect(result).toEqual({ok:false, reason:'unavailable'});
});
it('bounds Turnstile response-body reading too', async () => {
shortDeadline(10_000);
const result = await verifyTurnstile({
secret:'real-secret', token:'token', remoteIp:'203.0.113.1',
expectedHostname:'example.invalid', expectedAction:'signup',
fetchImpl: async (_url, init) => Object.assign(new Response('{}'), {json:() => stalled(init?.signal)}),
});
expect(result).toEqual({ok:false, reason:'unavailable'});
});
it('marks a Postmark timeout uncertain instead of retrying', async () => {
shortDeadline(15_000);
const driver = createPostmarkMailer('test-token', async (_url, init) => stalled(init?.signal));
expect((await driver.send(mail)).result).toBe('unknown');
});
it('marks a stalled Postmark success body uncertain', async () => {
shortDeadline(15_000);
const driver = createPostmarkMailer('test-token', async (_url, init) => Object.assign(new Response('{}'), {json:() => stalled(init?.signal)}));
expect((await driver.send(mail)).result).toBe('unknown');
});
it('passes SES a deadline and treats an abort as uncertain', async () => {
shortDeadline(15_000);
const driver = createSesMailer({region:'us-east-1', accessKeyId:'test', secretAccessKey:'test',
client:{send:async (_command, options) => stalled(options?.abortSignal)},
});
expect((await driver.send(mail)).result).toBe('unknown');
});
});
+380
View File
@@ -0,0 +1,380 @@
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { Temporal } from '@js-temporal/polyfill';
import { afterEach, describe, expect, it } from 'vitest';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { exportShiftRoster } from '../src/export.js';
import { purgeLoginPayloads, runDueRetention, runRetention, startRetentionRunner } from '../src/jobs/retention.js';
import { purgeRateHits } from '../src/rate-limit.js';
import { formatUtc } from '../src/time.js';
import { devEnv } from './env.js';
const NOW = '2026-06-15T15:00:00.000Z';
const BEFORE = '2026-06-15T05:30:00.000Z';
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('retention cleanup', () => {
it('clears signup details after the saved number of months and leaves a newer signup', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'pantry', 'America/Chicago');
const oldShift = insertShift(db, eventId, '2024-06-01T16:00:00.000Z', '2024-06-01T17:00:00.000Z');
const recentShift = insertShift(db, eventId, '2026-06-14T16:00:00.000Z', '2026-06-14T17:00:00.000Z');
insertSignup(db, oldShift, 'Old Volunteer', 'old.volunteer@example.invalid', 1, 1);
insertSignup(db, recentShift, 'New Volunteer', 'new.volunteer@example.invalid', 0, null);
const result = runRetention(db, NOW);
expect(result.signups).toBe(1);
const old = signup(db, oldShift);
expect(old).toMatchObject({
name: null,
email: null,
email_norm: null,
phone: null,
is_minor: 0,
guardian_name: null,
guardian_email: null,
notes: null,
manage_token_hash: null,
status: 'confirmed',
attended: 1,
anonymized_at: NOW,
});
expect(signup(db, recentShift).name).toBe('New Volunteer');
const csv = exportShiftRoster(db, oldShift)?.csv ?? '';
expect(csv).not.toContain('old.volunteer@example.invalid');
expect(csv).not.toContain(',No,');
expect(csv).toContain('Attended');
expect(JSON.stringify(db.prepare('SELECT detail_json AS detail_json FROM audit').all())).not.toContain('@');
});
it('uses a shorter saved retention period', async () => {
const db = await openDb();
db.prepare(`INSERT INTO settings (key, value_json, updated_at) VALUES ('retention_months', '1', ?)`).run(NOW);
const eventId = insertEvent(db, 'pantry', 'America/Chicago');
const dueShift = insertShift(db, eventId, '2026-04-01T16:00:00.000Z', '2026-04-01T17:00:00.000Z');
const earlyShift = insertShift(db, eventId, '2026-06-01T16:00:00.000Z', '2026-06-01T17:00:00.000Z');
const dueSignup = insertSignup(db, dueShift, 'Due Volunteer', 'due.volunteer@example.invalid', 0, null);
insertSignup(db, earlyShift, 'Early Volunteer', 'early.volunteer@example.invalid', 0, null);
insertOutbox(db, {
dedupe: 'confirmation:v1:due:due.volunteer@example.invalid',
signupId: dueSignup,
shiftId: dueShift,
kind: 'confirmation',
to: 'due.volunteer@example.invalid',
status: 'sent',
createdAt: '2026-06-10T15:00:00.000Z',
sentAt: '2026-06-10T15:00:00.000Z',
});
expect(runRetention(db, NOW).signups).toBe(1);
expect(signup(db, dueShift).name).toBeNull();
expect(signup(db, earlyShift).name).toBe('Early Volunteer');
expect(db.prepare('SELECT to_email AS to_email, body_text AS body_text FROM outbox').get()).toEqual({
to_email: '',
body_text: '',
});
});
it('clears old mail, expired sign-in records, audit notes, and rate-limit counters', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'pantry', 'America/Chicago');
const shiftId = insertShift(db, eventId, '2026-06-14T16:00:00.000Z', '2026-06-14T17:00:00.000Z');
const signupId = insertSignup(db, shiftId, 'Mail Volunteer', 'mail.volunteer@example.invalid', 0, null);
insertOutbox(db, {
dedupe: 'confirmation:v1:1:mail.volunteer@example.invalid',
signupId,
shiftId,
kind: 'confirmation',
to: 'mail.volunteer@example.invalid',
status: 'sent',
createdAt: '2026-05-01T15:00:00.000Z',
sentAt: '2026-05-01T15:00:00.000Z',
});
insertOutbox(db, {
dedupe: 'confirmation:v2:1:mail.volunteer@example.invalid',
signupId,
shiftId,
kind: 'confirmation',
to: 'mail.volunteer@example.invalid',
status: 'sent',
createdAt: '2026-06-14T15:00:00.000Z',
sentAt: '2026-06-14T15:00:00.000Z',
});
const expiredHash = 'ab'.repeat(32);
const liveHash = 'cd'.repeat(32);
insertOutbox(db, {
dedupe: `magic_link:${expiredHash}`,
signupId: null,
shiftId: null,
kind: 'magic_link',
to: 'coordinator@example.invalid',
status: 'pending',
createdAt: NOW,
sentAt: null,
});
insertOutbox(db, {
dedupe: `magic_link:${liveHash}`,
signupId: null,
shiftId: null,
kind: 'magic_link',
to: 'coordinator@example.invalid',
status: 'pending',
createdAt: NOW,
sentAt: null,
});
db.prepare(
`INSERT INTO login_tokens (token_hash, coordinator_id, expires_at, used_at, created_at)
VALUES (?, 1, ?, NULL, ?)`,
).run(expiredHash, '2026-06-15T14:00:00.000Z', NOW);
db.prepare(
`INSERT INTO login_tokens (token_hash, coordinator_id, expires_at, used_at, created_at)
VALUES (?, 1, ?, NULL, ?)`,
).run(liveHash, '2026-06-15T16:00:00.000Z', NOW);
db.prepare(
`INSERT INTO sessions (id_hash, coordinator_id, csrf, expires_at, created_at, last_seen_at)
VALUES ('expired-session', 1, 'csrf-expired', ?, ?, ?),
('live-session', 1, 'csrf-live', '2026-06-20T15:00:00.000Z', ?, ?)`,
).run(BEFORE, NOW, NOW, NOW, NOW);
db.prepare(`INSERT INTO audit (coordinator_id, action, detail_json, at) VALUES (NULL, 'login', '{}', ?)`).run(
'2024-05-01T15:00:00.000Z',
);
db.prepare(`INSERT INTO audit (coordinator_id, action, detail_json, at) VALUES (NULL, 'login', '{}', ?)`).run(NOW);
db.prepare(`INSERT INTO rate_hits (key, window_start, count) VALUES ('old', ?, 1), ('new', ?, 1)`).run(
'2026-06-01T15:00:00.000Z',
NOW,
);
const result = runRetention(db, NOW);
expect(result.messages).toBe(2);
expect(result.sessions).toBe(1);
expect(result.loginTokens).toBe(1);
expect(result.auditRows).toBe(1);
expect(result.rateHits).toBe(1);
const rows = db
.prepare('SELECT dedupe_key, to_email, subject, body_text, body_html, headers_json, status FROM outbox ORDER BY id')
.all() as Array<{
dedupe_key: string;
to_email: string;
subject: string;
body_text: string;
body_html: string;
headers_json: string;
status: string;
}>;
expect(rows[0]).toMatchObject({ dedupe_key: 'purged:1', to_email: '', subject: '', body_text: '', status: 'sent' });
expect(rows[1]?.to_email).toBe('mail.volunteer@example.invalid');
expect(rows[2]).toMatchObject({ dedupe_key: 'purged:3', to_email: '', status: 'cancelled' });
expect(rows[3]?.dedupe_key).toBe(`magic_link:${liveHash}`);
expect(rows[3]?.to_email).toBe('coordinator@example.invalid');
expect(db.prepare('SELECT id_hash FROM sessions').all()).toEqual([{ id_hash: 'live-session' }]);
expect(db.prepare('SELECT token_hash FROM login_tokens').all()).toEqual([{ token_hash: liveHash }]);
expect(db.prepare(`SELECT action FROM audit WHERE action = 'login'`).all()).toEqual([{ action: 'login' }]);
expect(db.prepare('SELECT key FROM rate_hits').all()).toEqual([{ key: 'new' }]);
expect(JSON.stringify(rows.filter((row) => row.to_email === ''))).not.toContain('@');
});
it('clears an expired sign-in message before 1:00 AM', async () => {
const db = await openDb();
const hash = 'ef'.repeat(32);
insertOutbox(db, {
dedupe: `magic_link:${hash}`,
signupId: null,
shiftId: null,
kind: 'magic_link',
to: 'coordinator@example.invalid',
status: 'pending',
createdAt: BEFORE,
sentAt: null,
});
db.prepare(
`INSERT INTO login_tokens (token_hash, coordinator_id, expires_at, used_at, created_at) VALUES (?, 1, ?, NULL, ?)`,
).run(hash, '2026-06-15T05:00:00.000Z', BEFORE);
expect(purgeLoginPayloads(db, BEFORE).messages).toBe(1);
expect(db.prepare('SELECT to_email AS to_email, status AS status FROM outbox').get()).toEqual({
to_email: '',
status: 'cancelled',
});
expect(purgeRateHits(db, BEFORE)).toBe(0);
});
it('waits for 1:00 AM Central Time, runs once when that hour repeats, and skips a bad time zone', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'pantry', 'America/Chicago');
const shiftId = insertShift(db, eventId, '2024-06-01T16:00:00.000Z', '2024-06-01T17:00:00.000Z');
insertSignup(db, shiftId, 'Clock Volunteer', 'clock.volunteer@example.invalid', 0, null);
const broken = insertEvent(db, 'broken', 'Not/AZone');
const brokenShift = insertShift(db, broken, '2024-06-01T16:00:00.000Z', '2024-06-01T17:00:00.000Z');
insertSignup(db, brokenShift, 'Broken Volunteer', 'broken.volunteer@example.invalid', 0, null);
expect(runDueRetention(db, BEFORE)).toMatchObject({ ran: false });
expect(signup(db, shiftId).name).toBe('Clock Volunteer');
const errors: string[] = [];
const write = console.error;
console.error = (message?: unknown) => {
errors.push(String(message));
};
let due: ReturnType<typeof runDueRetention>;
try {
due = runDueRetention(db, NOW);
} finally {
console.error = write;
}
expect(due.ran).toBe(true);
expect(due.result.signups).toBe(1);
expect(signup(db, brokenShift).name).toBe('Broken Volunteer');
expect(errors.join(' ')).toContain('not valid');
expect(errors.join(' ')).not.toContain('@');
expect(runDueRetention(db, NOW).ran).toBe(false);
const fall = await openDb();
const fallEvent = insertEvent(fall, 'pantry', 'America/Chicago');
const fallShift = insertShift(fall, fallEvent, '2024-06-01T16:00:00.000Z', '2024-06-01T17:00:00.000Z');
insertSignup(fall, fallShift, 'Fall Volunteer', 'fall.volunteer@example.invalid', 0, null);
const firstHour = localUtc('2026-11-01', 1, 0, 'earlier');
const secondHour = localUtc('2026-11-01', 1, 30, 'later');
expect(runDueRetention(fall, firstHour).ran).toBe(true);
expect(runDueRetention(fall, secondHour).ran).toBe(false);
expect(fall.prepare(`SELECT COUNT(*) AS n FROM job_runs WHERE job = 'retention'`).get()).toEqual({ n: 1 });
});
it('runs the daily cleanup on the first check after 1:00 AM', async () => {
const db = await openDb();
const eventId = insertEvent(db, 'pantry', 'America/Chicago');
const shiftId = insertShift(db, eventId, '2024-06-01T16:00:00.000Z', '2024-06-01T17:00:00.000Z');
insertSignup(db, shiftId, 'Runner Volunteer', 'runner.volunteer@example.invalid', 0, null);
const runner = startRetentionRunner(db, () => NOW);
expect(signup(db, shiftId).name).toBeNull();
runner.stop();
});
});
function localUtc(date: string, hour: number, minute: number, disambiguation: 'earlier' | 'later'): string {
const [year, month, day] = date.split('-').map(Number);
const zoned = Temporal.ZonedDateTime.from(
{ timeZone: 'America/Chicago', year, month, day, hour, minute, second: 0, millisecond: 0 },
{ disambiguation },
);
return formatUtc(zoned.toInstant());
}
async function openDb() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-retention-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
db.prepare(
`INSERT INTO coordinators (email, name, role, active, created_at) VALUES ('coordinator@example.invalid', 'Coordinator', 'admin', 1, ?)`,
).run(NOW);
return db;
}
function insertEvent(db: Awaited<ReturnType<typeof openDb>>, slug: string, tz: string): number {
return Number(
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES (?, ?, '', 'Sioux Center, Iowa', ?, 1, ?)`,
).run(slug, slug, tz, NOW).lastInsertRowid,
);
}
function insertShift(db: Awaited<ReturnType<typeof openDb>>, eventId: number, starts: string, ends: string): number {
return Number(
db.prepare(
`INSERT INTO shifts (
event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled, manually_modified, version
) VALUES (?, 'Sorting', ?, ?, 4, '', 0, 1, 1)`,
).run(eventId, starts, ends).lastInsertRowid,
);
}
function insertSignup(
db: Awaited<ReturnType<typeof openDb>>,
shiftId: number,
name: string,
email: string,
isMinor: number,
attended: number | null,
): number {
return Number(
db.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, phone, is_minor, guardian_name, guardian_email,
group_size, notes, status, manage_token_hash, token_expires_at, reminders_off,
attended, created_at, updated_at, anonymized_at
) VALUES (?, ?, ?, ?, '555-0100', ?, ?, ?, 1, 'Bring a pen', 'confirmed', ?, ?, 0, ?, ?, ?, NULL)`,
).run(
shiftId,
name,
email,
email.toLowerCase(),
isMinor,
isMinor ? 'Guardian Pat' : null,
isMinor ? 'guardian.pat@example.invalid' : null,
`hash-${email}`,
'2026-06-20T15:00:00.000Z',
attended,
NOW,
NOW,
).lastInsertRowid,
);
}
function insertOutbox(
db: Awaited<ReturnType<typeof openDb>>,
row: {
dedupe: string;
signupId: number | null;
shiftId: number | null;
kind: string;
to: string;
status: string;
createdAt: string;
sentAt: string | null;
},
): void {
db.prepare(
`INSERT INTO outbox (
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
headers_json, send_after, attempts, status, created_at, sent_at
) VALUES (?, ?, ?, ?, ?, 'Subject line', 'Body with a private link', '<p>Body</p>', ?, ?, 1, ?, ?, ?)`,
).run(
row.dedupe,
row.signupId,
row.shiftId,
row.kind,
row.to,
JSON.stringify({ 'Reply-To': row.to }),
row.createdAt,
row.status,
row.createdAt,
row.sentAt,
);
}
function signup(db: Awaited<ReturnType<typeof openDb>>, shiftId: number) {
return db.prepare('SELECT * FROM signups WHERE shift_id = ?').get(shiftId) as {
name: string | null;
email: string | null;
email_norm: string | null;
phone: string | null;
is_minor: number;
guardian_name: string | null;
guardian_email: string | null;
notes: string | null;
manage_token_hash: string | null;
status: string;
attended: number | null;
anonymized_at: string | null;
};
}
+74
View File
@@ -0,0 +1,74 @@
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { runSeedCli, SEED_EMAIL_DOMAIN, seedDevelopment } from '../src/dev/seed.js';
import { localToUtc, weekdayIndex } from '../src/time.js';
import { devEnv, productionEnv } from './env.js';
const dirs: string[] = [];
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
describe('development seed', () => {
it('refuses production before creating a database', async () => {
await expect(runSeedCli({ NODE_ENV: 'production' })).rejects.toThrow(/Refusing to seed/);
const config = loadConfig(productionEnv('/tmp/hope-should-not-matter'));
expect(() => seedDevelopment({} as never, config)).toThrow(/Refusing to seed/);
});
it('inserts one event, one template, one-off shifts, and fake signups', async () => {
const dataDir = path.join(mkdtempSync(path.join(tmpdir(), 'hope-volunteer-')), 'data');
dirs.push(path.dirname(dataDir));
const config = loadConfig(devEnv({ DATA_DIR: dataDir }));
const db = await openAppDatabase(config);
try {
const result = seedDevelopment(db, config, { today: '2026-10-14' });
expect(result.slug).toBe('weekly-pantry');
expect(result.shiftIds).toHaveLength(3);
expect(result.signupIds).toHaveLength(3);
const template = db
.prepare('SELECT weekday, starts_on, start_local, end_local, capacity FROM shift_templates')
.get();
expect(template).toEqual({
weekday: weekdayIndex('2026-10-14', 'America/Chicago'),
starts_on: '2026-10-14',
start_local: '09:00',
end_local: '12:00',
capacity: 6,
});
const shifts = db
.prepare('SELECT role, template_id, starts_at_utc, capacity FROM shifts ORDER BY starts_at_utc, role')
.all() as { role: string; template_id: number | null; starts_at_utc: string; capacity: number }[];
expect(shifts.map((shift) => shift.role)).toEqual(['Sorting', 'Distribution', 'Intake']);
expect(shifts.every((shift) => shift.template_id === null)).toBe(true);
expect(shifts[0]?.starts_at_utc).toBe(localToUtc('2026-10-15', '09:00', 'America/Chicago'));
const signups = db
.prepare('SELECT email, email_norm, group_size, is_minor, guardian_email, status FROM signups ORDER BY email')
.all() as {
email: string;
email_norm: string;
group_size: number;
is_minor: number;
guardian_email: string | null;
status: string;
}[];
expect(signups).toHaveLength(3);
for (const signup of signups) {
expect(signup.email.endsWith(`@${SEED_EMAIL_DOMAIN}`)).toBe(true);
expect(signup.group_size).toBe(1);
}
const minor = signups.find((signup) => signup.is_minor === 1);
expect(minor?.guardian_email).toBe(`pat.fake@${SEED_EMAIL_DOMAIN}`);
expect(signups.some((signup) => signup.status === 'cancelled')).toBe(true);
expect(db.prepare('SELECT COUNT(*) AS n FROM coordinators').get()).toEqual({ n: 0 });
expect(() => seedDevelopment(db, config, { today: '2026-10-14' })).toThrow(/already has events/);
} finally {
db.close();
}
});
});
+246
View File
@@ -0,0 +1,246 @@
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 { queueDueReminders } from '../src/reminders.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const ORIGIN = 'http://127.0.0.1:3000';
const MAIL = {
baseUrl: ORIGIN,
basePath: '',
from: 'Hope Food Pantry <volunteer@example.invalid>',
replyTo: 'volunteer@example.invalid',
};
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('coordinator settings', () => {
it('asks a signed-out visitor to sign in', async () => {
const { app } = await buildApp();
const response = await app.request('/admin/settings');
expect(response.status).toBe(303);
expect(response.headers.get('location')).toBe('/login');
});
it('shows the defaults, then saves reminder times, reply-to, retention, and privacy wording', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const first = await app.request('/admin/settings', { headers: { cookie } });
const firstHtml = await first.text();
expect(first.status).toBe(200);
expect(firstHtml).toContain('value="48"');
expect(firstHtml).toContain('value="2"');
expect(firstHtml).toContain('value="volunteer@example.invalid"');
expect(firstHtml).toContain('value="24"');
expect(firstHtml).toContain('A spreadsheet already downloaded is left as it is.');
expect(firstHtml).toContain('does not by itself make it an approved privacy policy');
const rejected = await postSettings(app, cookie, validFields({ reminder_far: '12', reminder_near: '12' }));
expect(rejected.status).toBe(400);
expect(await rejected.text()).toContain('The two reminder times have to be different.');
expect(count(db, "SELECT COUNT(*) AS n FROM settings")).toBe(0);
const named = await postSettings(app, cookie, validFields({ reply_to: 'Hope <pantry@example.invalid>' }));
expect(named.status).toBe(400);
expect(await named.text()).toContain('Enter an email address without a display name.');
const huge = await postSettings(app, cookie, validFields({ privacy_text: 'a'.repeat(8001) }));
expect(huge.status).toBe(400);
expect(await huge.text()).toContain('Keep the privacy wording under 8,000 characters.');
const stale = await app.request('/admin/settings', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ csrf: 'wrong', ...validFields() }),
});
expect(stale.status).toBe(403);
const saved = await postSettings(
app,
cookie,
validFields({
reminder_far: '3',
reminder_near: '24',
reply_to: 'Pantry@Example.invalid',
retention_months: '12',
privacy_text: 'We keep names.\n\n<script>alert(1)</script>',
}),
);
expect(saved.status).toBe(303);
expect(saved.headers.get('location')).toBe('/admin/settings?notice=settings-saved');
const page = await app.request('/admin/settings?notice=settings-saved', { headers: { cookie } });
const html = await page.text();
expect(html).toContain('Settings saved.');
expect(html).toContain('value="24"');
expect(html).toContain('value="3"');
expect(html).toContain('value="pantry@example.invalid"');
expect(html).toContain('value="12"');
expect(html).toContain('We keep names.');
expect(html).toContain('&lt;script&gt;');
expect(html).not.toContain('<script>');
const privacy = await app.request('/privacy');
const privacyHtml = await privacy.text();
expect(privacyHtml).toContain('We keep names.');
expect(privacyHtml).toContain('&lt;script&gt;alert(1)&lt;/script&gt;');
expect(privacyHtml).not.toContain('<script>');
expect(privacyHtml).not.toContain('does not have an approved privacy notice yet');
const audit = db.prepare("SELECT detail_json AS detail_json FROM audit WHERE action = 'settings.update'").all() as { detail_json: string }[];
expect(audit).toHaveLength(1);
expect(audit[0]?.detail_json).toContain('"reminderEarlier":24');
expect(audit[0]?.detail_json).toContain('"reminderCloser":3');
expect(audit[0]?.detail_json).toContain('"retentionMonths":12');
expect(audit[0]?.detail_json).toContain('"replyChanged":1');
expect(audit[0]?.detail_json).toContain('"privacyChanged":1');
expect(audit[0]?.detail_json).not.toContain('@');
expect(audit[0]?.detail_json).not.toContain('We keep names');
const again = await postSettings(
app,
cookie,
validFields({
reminder_far: '24',
reminder_near: '3',
reply_to: 'pantry@example.invalid',
retention_months: '12',
privacy_text: 'We keep names.\n\n<script>alert(1)</script>',
}),
);
expect(again.status).toBe(303);
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'settings.update'")).toBe(1);
await postLogin(app, 'coordinator@example.invalid');
const letter = db
.prepare("SELECT headers_json AS headers_json FROM outbox WHERE kind = 'magic_link' AND status = 'pending' ORDER BY id DESC LIMIT 1")
.get() as { headers_json: string };
expect(JSON.parse(letter.headers_json)).toMatchObject({ 'Reply-To': 'pantry@example.invalid' });
const shiftId = insertShift(db);
insertSignup(db, shiftId);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(1);
expect(queueDueReminders(db, MAIL, 'dev-only-change-me-not-for-production-use', NOW)).toEqual({ queued: 1, suppressed: 0 });
expect(db.prepare('SELECT kind FROM reminders_sent').get()).toEqual({ kind: '24h' });
const reminder = db.prepare("SELECT headers_json AS headers_json FROM outbox WHERE kind = 'reminder'").get() as { headers_json: string };
expect(JSON.parse(reminder.headers_json)['Reply-To']).toBe('pantry@example.invalid');
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(1);
});
});
async function buildApp() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-settings-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
bootstrapAdmin(db, config.bootstrapAdminEmail, NOW);
const app = createApp(config, db, {
now: NOW,
clientIp: () => '203.0.113.10',
verifyTurnstile: async () => ({ ok: true }),
});
return { app, db };
}
async function signIn(app: Awaited<ReturnType<typeof buildApp>>['app'], db: Awaited<ReturnType<typeof buildApp>>['db']) {
await postLogin(app, 'coordinator@example.invalid');
const token = magicToken(db);
const page = await app.request(`/login/link/${token}`);
const signedIn = await postLink(app, token, field(await page.text(), 'proof'));
return cookieHeader(signedIn);
}
function postLogin(app: Awaited<ReturnType<typeof buildApp>>['app'], email: string) {
return app.request('/login', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ email, company_website: '', 'cf-turnstile-response': 'token' }),
});
}
function postLink(app: Awaited<ReturnType<typeof buildApp>>['app'], token: string, proof: string) {
return app.request(`/login/link/${token}`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ proof }),
});
}
async function postSettings(app: Awaited<ReturnType<typeof buildApp>>['app'], cookie: string, fields: Record<string, string>) {
const current = await app.request('/admin/settings', { headers: { cookie } });
const csrf = field(await current.text(), 'csrf');
return app.request('/admin/settings', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ csrf, ...fields }),
});
}
function validFields(overrides: Record<string, string> = {}): Record<string, string> {
return {
reminder_far: '48',
reminder_near: '2',
reply_to: 'volunteer@example.invalid',
retention_months: '24',
privacy_text: '',
...overrides,
};
}
function insertShift(db: Awaited<ReturnType<typeof buildApp>>['db']): number {
const eventId = Number(
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES ('weekly', 'Weekly pantry', '', 'Sioux Center, Iowa', 'America/Chicago', 1, ?)`,
).run(NOW).lastInsertRowid,
);
return Number(
db.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, 'Sorting', '2026-10-15T14:00:00.000Z', '2026-10-15T17:00:00.000Z', 4, '', 0)`,
).run(eventId).lastInsertRowid,
);
}
function insertSignup(db: Awaited<ReturnType<typeof buildApp>>['db'], shiftId: number): void {
db.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, is_minor, group_size, status, reminders_off, created_at, updated_at
) VALUES (?, 'Ada', 'ada@example.invalid', 'ada@example.invalid', 0, 1, 'confirmed', 0, ?, ?)`,
).run(shiftId, NOW, NOW);
}
function magicToken(db: Awaited<ReturnType<typeof buildApp>>['db']): string {
const row = db
.prepare("SELECT body_text AS body_text FROM outbox WHERE kind = 'magic_link' AND status = 'pending' ORDER BY id DESC LIMIT 1")
.get() as { body_text: string } | undefined;
const token = /\/login\/link\/([A-Za-z0-9_-]+)/.exec(row?.body_text ?? '')?.[1];
if (!token) throw new Error('The sign-in link was not queued.');
return token;
}
function cookieHeader(response: Response): string {
const match = /hope_session=([^;]+)/.exec(response.headers.get('set-cookie') ?? '');
if (!match?.[1]) throw new Error('The session cookie was not set.');
return `hope_session=${match[1]}`;
}
function field(html: string, name: string): string {
const tag = new RegExp(`<input\\b[^>]*\\bname="${name}"[^>]*>`).exec(html)?.[0] ?? '';
return /value="([^"]*)"/.exec(tag)?.[1] ?? '';
}
function count(db: Awaited<ReturnType<typeof buildApp>>['db'], sql: string): number {
return Number((db.prepare(sql).get() as { n: number }).n);
}
+25
View File
@@ -0,0 +1,25 @@
// Spawned with `node --import tsx`. Those .ts specifiers are intentional.
// tsconfig excludes this file because tsc does not allow that import style.
import { openDatabaseFile } from '../src/db.ts';
import { reserveSignup, type ReserveInput } from '../src/signup.ts';
const data = JSON.parse(process.env.HOPE_RACE ?? '') as { databaseFile: string; input: ReserveInput };
const db = openDatabaseFile(data.databaseFile);
try {
const result = reserveSignup(db, data.input);
process.stdout.write(JSON.stringify({
ok: result.ok,
reason: result.ok ? null : result.reason,
replay: result.ok ? result.replay : false,
}));
} catch (err) {
process.stdout.write(JSON.stringify({
ok: false,
reason: 'error',
replay: false,
message: err instanceof Error ? err.message : String(err),
}));
process.exitCode = 1;
} finally {
db.close();
}
+464
View File
@@ -0,0 +1,464 @@
import { spawn } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { Temporal } from '@js-temporal/polyfill';
import { afterEach, describe, expect, it } from 'vitest';
import { createApp } from '../src/app.js';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { issueFormToken, MIN_FILL_MS } from '../src/form-token.js';
import { SIGNUP_EMAIL_LIMIT, SIGNUP_GUARDIAN_LIMIT, SIGNUP_IP_LIMIT } from '../src/rate-limit.js';
import type { ReserveInput } from '../src/signup.js';
import { verifyTurnstile, type TurnstileVerdict } from '../src/turnstile.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const NOW_MS = Temporal.Instant.from(NOW).epochMilliseconds;
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('capacity-safe signup', () => {
it('saves one person, shows a private confirmation link, and does not send mail', async () => {
const { app, shiftId, db } = await buildApp();
const response = await postSignup(app, shiftId, { name: 'Pat Review', email: ' Pat.Review@Example.invalid ', phone: '712-555-0199', notes: '<script>alert(1)</script>' });
expect(response.status).toBe(303);
const cookie = response.headers.get('set-cookie') ?? '';
expect(cookie).toContain('HttpOnly');
expect(cookie).not.toContain('Pat.Review');
expect(cookie).not.toContain('pat.review@example.invalid');
const confirmed = await app.request(locationOf(response), { headers: { cookie: cookiePair(cookie) } });
const confirmedHtml = await confirmed.text();
expect(confirmed.status).toBe(200);
expect(confirmedHtml).toContain('Pat Review');
expect(confirmedHtml).toContain('A confirmation email is queued');
expect(confirmedHtml).toContain('where you can cancel it');
const managePath = confirmedHtml.match(/href="(\/m\/[^"]+)"/)?.[1];
expect(managePath).toBeTruthy();
expect(cookie).not.toContain(managePath?.slice(3) ?? 'missing-token');
const manage = await app.request(managePath ?? '/m/missing');
const manageHtml = await manage.text();
expect(manage.status).toBe(200);
expect(manageHtml).toContain('Pat Review');
expect(manageHtml).toContain('pat.review@example.invalid');
expect(manageHtml).toContain('712-555-0199');
expect(manageHtml).toContain('&lt;script&gt;alert(1)&lt;/script&gt;');
expect(manageHtml).toContain('Cancel this signup');
expect(manageHtml).toContain('name="cancel_token"');
expect(manageHtml).not.toContain('challenges.cloudflare.com');
expect(db.prepare("SELECT status FROM signups").get()).toEqual({ status: 'confirmed' });
expect(manage.headers.get('cache-control')).toBe('no-store');
const again = await postSignup(app, shiftId, { name: 'Pat Review', email: 'pat.review@example.invalid' }, { ip: '203.0.113.21' });
expect(again.status).toBe(409);
const againHtml = await again.text();
expect(againHtml).toContain('That person is already signed up for this shift.');
expect(againHtml).not.toContain('already registered');
expect(againHtml).not.toContain('duplicate');
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE status = 'confirmed'").get()).toEqual({ n: 1 });
});
it('lets another person use an email that is already on the shift', async () => {
const { app, shiftId, db } = await buildApp({ capacity: 2 });
expect((await postSignup(app, shiftId, { name: 'Pat Review', email: 'home@example.invalid' }, { ip: '203.0.113.91' })).status).toBe(303);
const second = await postSignup(app, shiftId, { name: 'Sam Review', email: 'Home@Example.invalid' }, { ip: '203.0.113.92' });
expect(second.status).toBe(303);
const people = db.prepare("SELECT name, email_norm FROM signups WHERE status = 'confirmed' ORDER BY id").all();
expect(people).toEqual([
{ name: 'Pat Review', email_norm: 'home@example.invalid' },
{ name: 'Sam Review', email_norm: 'home@example.invalid' },
]);
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND to_email = 'home@example.invalid'").get()).toEqual({ n: 2 });
const again = await postSignup(app, shiftId, { name: 'sam review', email: 'home@example.invalid' }, { ip: '203.0.113.93' });
expect(again.status).toBe(409);
expect(await again.text()).toContain('That person is already signed up for this shift.');
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE status = 'confirmed'").get()).toEqual({ n: 2 });
});
it('keeps dots and plus-tags distinct and folds case into one address', async () => {
const { app, shiftId, db } = await buildApp({ capacity: 4 });
expect((await postSignup(app, shiftId, { email: 'a.b@example.invalid' }, { ip: '203.0.113.31' })).status).toBe(303);
expect((await postSignup(app, shiftId, { email: 'ab@example.invalid' }, { ip: '203.0.113.32' })).status).toBe(303);
expect((await postSignup(app, shiftId, { email: 'a+tag@example.invalid' }, { ip: '203.0.113.33' })).status).toBe(303);
expect((await postSignup(app, shiftId, { email: 'ADA@Example.invalid' }, { ip: '203.0.113.34' })).status).toBe(303);
expect((await postSignup(app, shiftId, { email: ' ada@example.invalid ' }, { ip: '203.0.113.35' })).status).toBe(409);
const emails = db.prepare("SELECT email_norm FROM signups WHERE status = 'confirmed' ORDER BY id").all() as { email_norm: string }[];
expect(emails.map((row) => row.email_norm)).toEqual([
'a.b@example.invalid',
'ab@example.invalid',
'a+tag@example.invalid',
'ada@example.invalid',
]);
});
it('requires a guardian for a minor and ignores guardian fields for an adult', async () => {
const { app, shiftId, db } = await buildApp({ capacity: 2 });
const missing = await postSignup(app, shiftId, { under18: true, email: 'minor@example.invalid' }, { ip: '203.0.113.41' });
expect(missing.status).toBe(400);
const missingHtml = await missing.text();
expect(missingHtml).toContain('Enter the guardian name.');
expect(missingHtml).toMatch(/id="signup-under-18"[^>]*\schecked/);
expect(db.prepare('SELECT COUNT(*) AS n FROM signups').get()).toEqual({ n: 0 });
const minor = await postSignup(
app,
shiftId,
{
name: 'Minor Pat',
email: 'minor@example.invalid',
under18: true,
guardianName: 'Guardian Pat',
guardianEmail: 'Guardian.Pat@Example.invalid',
},
{ ip: '203.0.113.42' },
);
expect(minor.status).toBe(303);
const adult = await postSignup(
app,
shiftId,
{ email: 'adult@example.invalid', guardianName: 'Should Not Store', guardianEmail: 'nope@example.invalid' },
{ ip: '203.0.113.43' },
);
expect(adult.status).toBe(303);
const stored = db.prepare('SELECT email_norm, is_minor, guardian_name, guardian_email, group_size FROM signups ORDER BY id').all();
expect(stored).toEqual([
{ email_norm: 'minor@example.invalid', is_minor: 1, guardian_name: 'Guardian Pat', guardian_email: 'guardian.pat@example.invalid', group_size: 1 },
{ email_norm: 'adult@example.invalid', is_minor: 0, guardian_name: null, guardian_email: null, group_size: 1 },
]);
});
it('rejects a fast, tampered, honeypot, cross-site, or unverified submit without taking a spot', async () => {
const { app, shiftId, db, config } = await buildApp();
const fast = await postSignup(app, shiftId, {}, { issuedAt: NOW_MS - 1000, ip: '203.0.113.51' });
expect(fast.status).toBe(400);
expect(await fast.text()).toContain('wait a few seconds');
const honeypot = await postSignup(app, shiftId, { company: 'https://spam.example' }, { ip: '203.0.113.52' });
expect(honeypot.status).toBe(409);
expect(await honeypot.text()).not.toContain('honeypot');
const crossSite = await postSignup(app, shiftId, {}, { origin: 'https://evil.example', ip: '203.0.113.53' });
expect(crossSite.status).toBe(403);
const opaqueCrossSite = await postSignup(app, shiftId, {}, { origin: 'null', site: 'cross-site', ip: '203.0.113.57' });
expect(opaqueCrossSite.status).toBe(403);
const opaqueSameOrigin = await postSignup(app, shiftId, { email: 'same-origin@example.invalid' }, { origin: 'null', site: 'same-origin', ip: '203.0.113.58' });
expect(opaqueSameOrigin.status).toBe(303);
const blocked = await buildApp({ verify: async () => ({ ok: false, reason: 'rejected' }) });
const rejected = await postSignup(blocked.app, blocked.shiftId, {}, { ip: '203.0.113.54' });
expect(rejected.status).toBe(400);
expect(await rejected.text()).toContain('check did not finish');
const down = await buildApp({ verify: async () => ({ ok: false, reason: 'unavailable' }) });
expect((await postSignup(down.app, down.shiftId, {}, { ip: '203.0.113.55' })).status).toBe(503);
const tampered = issueFormToken(config.sessionSecret, { shiftId, issuedAt: NOW_MS - 5000, operationId: 'abcdefghijklmnop' });
const bad = await postSignup(app, shiftId, {}, { token: `${tampered.slice(0, -1)}x`, ip: '203.0.113.56' });
expect(bad.status).toBe(400);
expect(db.prepare('SELECT COUNT(*) AS n FROM signups').get()).toEqual({ n: 1 });
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation'").get()).toEqual({ n: 1 });
void MIN_FILL_MS;
});
it('limits signup attempts by IP and by email without storing the raw address', async () => {
const { app, db } = await buildApp({ capacity: 8 });
const shifts = [1, 2, 3, 4].map(() => insertExtraShift(db, { capacity: 8 }));
for (let index = 0; index < SIGNUP_IP_LIMIT; index += 1) {
const response = await postSignup(app, shifts[0] ?? 0, { email: `ip-${index}@example.invalid` }, { ip: '198.51.100.10' });
expect(response.status).toBe(303);
}
const blockedIp = await postSignup(app, shifts[0] ?? 0, { email: 'ip-extra@example.invalid' }, { ip: '198.51.100.10', forwardedFor: '203.0.113.250' });
expect(blockedIp.status).toBe(429);
expect(Number(blockedIp.headers.get('retry-after'))).toBeGreaterThan(0);
const otherIp = await postSignup(app, shifts[0] ?? 0, { email: 'other-ip@example.invalid' }, { ip: '198.51.100.11' });
expect(otherIp.status).toBe(303);
for (let index = 0; index < SIGNUP_EMAIL_LIMIT; index += 1) {
const shift = shifts[index + 1] ?? 0;
const response = await postSignup(app, shift, { email: 'daily@example.invalid' }, { ip: `198.51.100.${20 + index}` });
expect(response.status).toBe(303);
}
const blockedEmail = await postSignup(app, shifts[0] ?? 0, { email: 'daily@example.invalid' }, { ip: '198.51.100.40' });
expect(blockedEmail.status).toBe(429);
const keys = db.prepare('SELECT key FROM rate_hits').all() as { key: string }[];
expect(JSON.stringify(keys)).not.toContain('daily@example.invalid');
expect(JSON.stringify(keys)).not.toContain('198.51.100.10');
});
it('limits signups that mail one guardian, even from different volunteer addresses', async () => {
const { app, db } = await buildApp({ capacity: 8 });
const shiftId = insertExtraShift(db, { capacity: 8 });
const minor = (index: number) => ({
name: `Minor ${index}`,
email: `minor-${index}@example.invalid`,
under18: true,
guardianName: 'Guardian Pat',
guardianEmail: 'target@example.invalid',
});
for (let index = 0; index < SIGNUP_GUARDIAN_LIMIT; index += 1) {
const response = await postSignup(app, shiftId, minor(index), { ip: `198.51.100.${120 + index}` });
expect(response.status).toBe(303);
}
const blocked = await postSignup(app, shiftId, minor(99), { ip: '198.51.100.140' });
expect(blocked.status).toBe(429);
expect(Number(blocked.headers.get('retry-after'))).toBeGreaterThan(0);
expect(JSON.stringify(db.prepare('SELECT key FROM rate_hits').all())).not.toContain('target@example.invalid');
const sameAddress = await postSignup(
app,
shiftId,
{ name: 'Own Guardian', email: 'family@example.invalid', under18: true, guardianName: 'Parent', guardianEmail: 'family@example.invalid' },
{ ip: '198.51.100.141' },
);
expect(sameAddress.status).toBe(303);
});
it('does not let a cross-site signup post use up the network allowance', async () => {
const { app, shiftId } = await buildApp({ capacity: 2 });
for (let index = 0; index < SIGNUP_IP_LIMIT; index += 1) {
const rejected = await postSignup(app, shiftId, { email: `cross-${index}@example.invalid` }, {
origin: 'https://evil.example',
ip: '198.51.100.77',
});
expect(rejected.status).toBe(403);
}
const allowed = await postSignup(app, shiftId, { email: 'still-open@example.invalid' }, { ip: '198.51.100.77' });
expect(allowed.status).toBe(303);
});
it('stops at capacity and lets a repeated submit reuse the same reservation', async () => {
const { app, shiftId, db } = await buildApp({ capacity: 1 });
const token = issueFormToken('dev-only-change-me-not-for-production-use', {
shiftId,
issuedAt: NOW_MS - 10_000,
operationId: 'repeat-operation-01',
});
const first = await postSignup(app, shiftId, { email: 'only@example.invalid' }, { token, ip: '203.0.113.61' });
const second = await postSignup(app, shiftId, { email: 'only@example.invalid' }, { token, ip: '203.0.113.62' });
expect(first.status).toBe(303);
expect(second.status).toBe(303);
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE status = 'confirmed'").get()).toEqual({ n: 1 });
const third = await postSignup(app, shiftId, { email: 'someone@example.invalid' }, { ip: '203.0.113.63' });
expect(third.status).toBe(409);
expect(await third.text()).toContain('This shift is full.');
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND status = 'pending'").get()).toEqual({ n: 1 });
});
it('does not count a cancelled signup toward capacity and closes ended shifts', async () => {
const { app, db, shiftId } = await buildApp({ capacity: 1 });
db.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, is_minor, group_size, status, reminders_off, created_at, updated_at
) VALUES (?, 'Old Person', 'old@example.invalid', 'old@example.invalid', 0, 1, 'cancelled', 0, ?, ?)`,
).run(shiftId, NOW, NOW);
expect((await postSignup(app, shiftId, { email: 'new@example.invalid' }, { ip: '203.0.113.71' })).status).toBe(303);
const ended = insertExtraShift(db, {
starts: '2026-10-14T14:00:00.000Z',
ends: '2026-10-14T17:00:00.000Z',
});
const closed = await postSignup(app, ended, { email: 'late@example.invalid' }, { ip: '203.0.113.72' });
expect(closed.status).toBe(400);
expect(await closed.text()).toContain('This shift is closed.');
});
it('gives exactly three spots to twenty concurrent reservations', async () => {
const { db, databaseFile, shiftId } = await buildApp({ capacity: 3 });
const results = await Promise.all(
Array.from({ length: 20 }, (_, index) =>
race(databaseFile, {
shiftId,
name: `Person ${index}`,
email: `person-${index}@example.invalid`,
phone: null,
notes: null,
isMinor: false,
guardianName: null,
guardianEmail: null,
operationId: `operation-${index}-abcdef`,
now: NOW,
mail: {
baseUrl: 'http://127.0.0.1:3000',
basePath: '',
from: 'Hope Food Pantry <volunteer@example.invalid>',
replyTo: 'volunteer@example.invalid',
},
}),
),
);
const wins = results.filter((result) => result.ok && !result.replay);
expect(wins).toHaveLength(3);
expect(results.filter((result) => !result.ok && result.reason !== 'full')).toEqual([]);
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE status = 'confirmed'").get()).toEqual({ n: 3 });
expect(db.prepare("SELECT COALESCE(SUM(group_size), 0) AS n FROM signups WHERE status = 'confirmed'").get()).toEqual({ n: 3 });
}, 30_000);
it('treats an invalid or expired manage link as unavailable', async () => {
const { app, db, shiftId } = await buildApp();
const saved = await postSignup(app, shiftId, { email: 'link@example.invalid' }, { ip: '203.0.113.81' });
const confirmed = await app.request(locationOf(saved), { headers: { cookie: cookiePair(saved.headers.get('set-cookie') ?? '') } });
const managePath = (await confirmed.text()).match(/href="(\/m\/[^"]+)"/)?.[1] ?? '';
db.prepare("UPDATE signups SET token_expires_at = '2026-10-14T18:00:00.000Z' WHERE email_norm = 'link@example.invalid'").run();
expect((await app.request(managePath)).status).toBe(404);
expect((await app.request('/m/not-a-real-token')).status).toBe(404);
const missing = await app.request('/m/not-a-real-token');
expect(await missing.text()).toContain('That page is not available');
expect(db.prepare("SELECT status FROM signups WHERE email_norm = 'link@example.invalid'").get()).toEqual({ status: 'confirmed' });
});
});
describe('Turnstile siteverify', () => {
it('accepts the matching host and action, and fails closed otherwise', async () => {
const ok = await verifyTurnstile({
secret: 'secret-key',
token: 'widget-token',
remoteIp: '203.0.113.9',
expectedHostname: '127.0.0.1',
expectedAction: 'signup',
fetchImpl: async (_url, init) => {
expect(String(init?.body)).toContain('secret=secret-key');
expect(String(init?.body)).toContain('response=widget-token');
return jsonResponse({ success: true, hostname: '127.0.0.1', action: 'signup' });
},
});
expect(ok).toEqual({ ok: true });
expect(await verifyTurnstile(check(jsonResponse({ success: true, hostname: 'evil.example', action: 'signup' })))).toEqual({ ok: false, reason: 'rejected' });
expect(await verifyTurnstile(check(jsonResponse({ success: true, hostname: '127.0.0.1', action: 'login' })))).toEqual({ ok: false, reason: 'rejected' });
expect(await verifyTurnstile(check(jsonResponse({ success: true, hostname: 'example.com', metadata: { result_with_testing_key: true } }), '1x0000000000000000000000000000000AA'))).toEqual({ ok: true });
expect(await verifyTurnstile(check(jsonResponse({ success: true, hostname: 'example.com', metadata: { result_with_testing_key: true } })))).toEqual({ ok: false, reason: 'rejected' });
expect(await verifyTurnstile(check(jsonResponse({ success: false, 'error-codes': ['timeout-or-duplicate'] })))).toEqual({ ok: false, reason: 'duplicate' });
expect(await verifyTurnstile(check(Promise.reject(new Error('network'))))).toEqual({ ok: false, reason: 'unavailable' });
});
});
async function buildApp(options?: { capacity?: number; verify?: (input: unknown) => Promise<TurnstileVerdict> }) {
const root = mkdtempSync(path.join(tmpdir(), 'hope-signup-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
const shiftId = insertExtraShift(db, { capacity: options?.capacity ?? 3 });
const app = createApp(config, db, {
now: NOW,
clientIp: (c) => c.req.header('x-test-ip') ?? null,
verifyTurnstile: options?.verify ?? (async () => ({ ok: true })),
});
return { app, db, config, shiftId, databaseFile: config.databaseFile };
}
function insertExtraShift(
db: import('better-sqlite3').Database,
options?: { capacity?: number; starts?: string; ends?: string; cancelled?: number },
): number {
const event = db.prepare("SELECT id FROM events WHERE slug = 'weekly-pantry'").get() as { id: number } | undefined;
const eventId = event?.id ?? Number(
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES ('weekly-pantry', 'Weekly pantry', 'Bring a hat.', 'Sioux Center, Iowa', 'America/Chicago', 1, ?)`,
).run(NOW).lastInsertRowid,
);
const result = db
.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, 'Sorting', ?, ?, ?, '', ?)`,
)
.run(
eventId,
options?.starts ?? '2026-10-15T14:00:00.000Z',
options?.ends ?? '2026-10-15T17:00:00.000Z',
options?.capacity ?? 3,
options?.cancelled ?? 0,
);
return Number(result.lastInsertRowid);
}
async function postSignup(
app: ReturnType<typeof createApp>,
shiftId: number,
fields: Partial<{ name: string; email: string; phone: string; notes: string; under18: boolean; guardianName: string; guardianEmail: string; company: string }>,
options?: { token?: string; issuedAt?: number; ip?: string; origin?: string; forwardedFor?: string; site?: string },
) {
const secret = 'dev-only-change-me-not-for-production-use';
const token = options?.token ?? issueFormToken(secret, {
shiftId,
issuedAt: options?.issuedAt ?? NOW_MS - 10_000,
operationId: randomBytes(16).toString('hex'),
});
const body = new URLSearchParams({
form_token: token,
name: fields.name ?? 'Pat Review',
email: fields.email ?? 'pat.review@example.invalid',
phone: fields.phone ?? '',
notes: fields.notes ?? '',
guardianName: fields.guardianName ?? '',
guardianEmail: fields.guardianEmail ?? '',
company_website: fields.company ?? '',
'cf-turnstile-response': 'widget-token',
});
if (fields.under18) body.set('under18', 'yes');
return app.request(`/s/${shiftId}`, {
method: 'POST',
headers: {
origin: options?.origin ?? 'http://127.0.0.1:3000',
'content-type': 'application/x-www-form-urlencoded',
'x-test-ip': options?.ip ?? '203.0.113.10',
...(options?.site ? { 'sec-fetch-site': options.site } : {}),
...(options?.forwardedFor ? { 'x-forwarded-for': options.forwardedFor } : {}),
},
body,
});
}
function locationOf(response: Response): string {
return response.headers.get('location') ?? '';
}
function cookiePair(setCookie: string): string {
return setCookie.split(';')[0] ?? '';
}
function check(result: Promise<Response> | Response, secret = 'secret-key'): Parameters<typeof verifyTurnstile>[0] {
return {
secret,
token: 'widget-token',
remoteIp: '203.0.113.9',
expectedHostname: '127.0.0.1',
expectedAction: 'signup',
fetchImpl: async () => result,
};
}
function jsonResponse(body: unknown): Response {
return new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' } });
}
function race(databaseFile: string, input: ReserveInput): Promise<{ ok: boolean; reason: string | null; replay: boolean; message?: string }> {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, ['--import', 'tsx', fileURLToPath(new URL('./signup-race-worker.ts', import.meta.url))], {
env: { ...process.env, HOPE_RACE: JSON.stringify({ databaseFile, input }) },
});
let out = '';
let err = '';
child.stdout.on('data', (chunk: Buffer) => {
out += chunk.toString();
});
child.stderr.on('data', (chunk: Buffer) => {
err += chunk.toString();
});
child.on('error', reject);
child.on('exit', (code) => {
if (out.trim() === '') {
reject(new Error(err || `Signup process exited ${code ?? 'unknown'}.`));
return;
}
resolve(JSON.parse(out));
});
});
}
+216
View File
@@ -0,0 +1,216 @@
import { randomBytes } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import type Database from 'better-sqlite3';
import { afterEach, describe, expect, it } from 'vitest';
import { createApp } from '../src/app.js';
import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { deliverDueMail } from '../src/mail/deliver.js';
import { SWITCH_IP_LIMIT, SWITCH_RECIPIENT_LIMIT } from '../src/rate-limit.js';
import { reserveSignup } from '../src/signup.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const dirs: string[] = [];
const databases = new Set<Database.Database>();
afterEach(() => {
for (const db of databases) db.close();
databases.clear();
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
describe('public switch limits', () => {
it('stops the repeated-switch mail attack despite new tokens, ids, IPs, and a reopened database', async () => {
const f = await fixture();
// A shared volunteer/guardian mailbox must count only once per switch.
let link = f.signup('target@example.invalid', 'target@example.invalid');
let app = f.app();
let accepted = 0;
const mailer = { send: async () => { accepted++; return { result: 'sent' as const, providerId: 'mock' }; } };
await deliverDueMail(f.db, mailer, NOW);
for (let i = 0; i < SWITCH_RECIPIENT_LIMIT; i++) {
const response = await switchTo(app, link, f.shifts[(i + 1) % 2]!, `203.0.113.${i + 1}`);
expect(response.status).toBe(303);
link = nextLink(response);
await deliverDueMail(f.db, mailer, NOW);
}
const before = records(f.db);
// Close and reopen the file, rather than relying on an in-memory counter.
f.db.close();
databases.delete(f.db);
const reopened = await openAppDatabase(f.config);
databases.add(reopened);
app = createApp(f.config, reopened, { now: NOW, clientIp: (c) => c.req.header('x-test-ip') ?? null });
for (let i = SWITCH_RECIPIENT_LIMIT; i < 12; i++) {
const response = await switchTo(app, link, f.shifts[0]!, `203.0.113.${i + 1}`);
expect(response.status).toBe(429);
expect(response.headers.get('retry-after')).toBe('39600'); // Midnight in America/Chicago.
expect(response.headers.get('cache-control')).toBe('no-store');
expect(await response.text()).toContain('You are still signed up for this shift.');
expect(records(reopened)).toEqual(before);
await deliverDueMail(reopened, mailer, NOW);
}
expect(accepted).toBe(1 + SWITCH_RECIPIENT_LIMIT);
expect(before.signups).toHaveLength(1 + SWITCH_RECIPIENT_LIMIT);
expect(JSON.stringify(reopened.prepare('SELECT * FROM rate_hits').all())).not.toMatch(/target@|203\.0\.113/);
const tomorrow = createApp(f.config, reopened, { now: '2026-10-15T05:00:00.000Z', clientIp: () => '203.0.113.1' });
expect((await switchTo(tomorrow, link, f.shifts[0]!)).status).toBe(303);
});
it('shares guardian limits across children, IPs, and recipient roles without charging blocked co-recipients', async () => {
const f = await fixture();
const app = f.app();
for (let i = 0; i < SWITCH_RECIPIENT_LIMIT; i++) {
const link = f.signup(`child${i}@example.invalid`, 'guardian@example.invalid');
expect((await switchTo(app, link, f.shifts[1]!, `203.0.113.${i + 1}`)).status).toBe(303);
}
const blocked = f.signup('new-child@example.invalid', 'guardian@example.invalid');
const before = records(f.db);
expect((await switchTo(app, blocked, f.shifts[1]!, '203.0.113.99')).status).toBe(429);
expect(records(f.db)).toEqual(before);
const reversed = f.signup('guardian@example.invalid', 'other@example.invalid');
expect((await switchTo(app, reversed, f.shifts[1]!, '203.0.113.98')).status).toBe(429);
// Rejection must not spend this child's allowance on otherwise valid links.
let ownLink = f.signup('new-child@example.invalid', null, 'Another person');
for (let i = 0; i < SWITCH_RECIPIENT_LIMIT; i++) {
const response = await switchTo(app, ownLink, f.shifts[(i + 1) % 2]!, '203.0.113.97');
expect(response.status).toBe(303);
ownLink = nextLink(response);
}
});
it('limits one IP even when recipients change, then permits a retry after the window', async () => {
const f = await fixture();
const app = f.app();
for (let i = 0; i < SWITCH_IP_LIMIT; i++) {
const link = f.signup(`person${i}@example.invalid`);
expect((await switchTo(app, link, f.shifts[1]!, '203.0.113.1')).status).toBe(303);
}
const link = f.signup('next@example.invalid');
const before = records(f.db);
const limited = await switchTo(app, link, f.shifts[1]!, '203.0.113.1');
expect(limited.status).toBe(429);
expect(limited.headers.get('retry-after')).toBe('600');
expect(records(f.db)).toEqual(before);
const later = f.app('2026-10-14T18:10:00.000Z');
expect((await switchTo(later, link, f.shifts[1]!, '203.0.113.1')).status).toBe(303);
});
it('does not charge recipients for invalid origin or forged proofs', async () => {
const f = await fixture();
const app = f.app();
const link = f.signup('proof@example.invalid');
const page = await (await app.request(link)).text();
for (const origin of ['https://invalid.example', f.config.baseUrl]) {
const response = await app.request(`${link}/switch`, {
method: 'POST', headers: { origin },
body: new URLSearchParams({ switch_token: 'forged', form_token: field(page, 'form_token'), destination: String(f.shifts[1]) }),
});
expect(response.status).toBe(origin === f.config.baseUrl ? 400 : 403);
}
expect(f.db.prepare('SELECT COUNT(*) AS n FROM rate_hits').get()).toEqual({ n: 0 });
});
it('does not overshoot a shared recipient limit under concurrent requests', async () => {
const f = await fixture();
const app = f.app();
const requests = Array.from({ length: SWITCH_RECIPIENT_LIMIT + 1 }, (_, i) => {
const link = f.signup(`parallel${i}@example.invalid`, 'shared@example.invalid');
return switchTo(app, link, f.shifts[1]!, `203.0.113.${i + 1}`);
});
const responses = await Promise.all(requests);
expect(responses.filter((r) => r.status === 303)).toHaveLength(SWITCH_RECIPIENT_LIMIT);
expect(responses.filter((r) => r.status === 429)).toHaveLength(1);
expect(f.db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action='signup.switch'").get()).toEqual({ n: SWITCH_RECIPIENT_LIMIT });
});
it('keeps replays idempotent and cancellation available after reaching the switch limit', async () => {
const f = await fixture();
const app = f.app();
let link = f.signup('cancel@example.invalid');
for (let i = 0; i < SWITCH_RECIPIENT_LIMIT; i++) {
const page = await (await app.request(link)).text();
const request = () => postSwitch(app, link, page, f.shifts[(i + 1) % 2]!, '203.0.113.1');
const response = await request();
expect(response.status).toBe(303);
const before = records(f.db);
const rates = f.db.prepare('SELECT * FROM rate_hits ORDER BY key').all();
expect((await request()).status).toBe(200);
expect(records(f.db)).toEqual(before);
expect(f.db.prepare('SELECT * FROM rate_hits ORDER BY key').all()).toEqual(rates);
link = nextLink(response);
}
expect((await switchTo(app, link, f.shifts[0]!)).status).toBe(429);
const page = await (await app.request(link)).text();
const cancel = await app.request(link, {
method: 'POST', headers: { origin: f.config.baseUrl },
body: new URLSearchParams({ cancel_token: field(page, 'cancel_token') }),
});
expect(cancel.status).toBe(303);
expect(f.db.prepare("SELECT COUNT(*) AS n FROM signups WHERE status='confirmed'").get()).toEqual({ n: 0 });
});
});
async function fixture() {
const dir = mkdtempSync(path.join(tmpdir(), 'hope-switch-limit-'));
dirs.push(dir);
const config = loadConfig(devEnv({ DATA_DIR: dir }));
const db = await openAppDatabase(config);
databases.add(db);
const eventId = db.prepare(`INSERT INTO events (slug,title,description,location,tz,published,created_at)
VALUES ('weekly-pantry','Pantry','','Iowa','America/Chicago',1,?)`).run(NOW).lastInsertRowid;
const shifts = [0, 1].map((i) => Number(db.prepare(`INSERT INTO shifts
(event_id,role,starts_at_utc,ends_at_utc,capacity,notes,cancelled)
VALUES (?,?, '2026-10-16T14:00:00.000Z','2026-10-16T17:00:00.000Z',100,'',0)`)
.run(eventId, `Role ${i}`).lastInsertRowid));
const mail = { baseUrl: config.baseUrl, basePath: config.basePath, from: config.mail.from, replyTo: config.mail.replyTo };
return {
db, config, shifts,
app: (now = NOW) => createApp(config, db, { now, clientIp: (c) => c.req.header('x-test-ip') ?? null }),
signup: (email: string, guardianEmail: string | null = null, name = 'Test Person') => {
const result = reserveSignup(db, {
shiftId: shifts[0]!, name, email, guardianEmail, isMinor: guardianEmail !== null,
guardianName: guardianEmail ? 'Guardian' : null, phone: null, notes: null,
operationId: randomBytes(16).toString('hex'), now: NOW, mail,
});
if (!result.ok || !result.manageToken) throw new Error('Fixture signup failed');
return `/m/${result.manageToken}`;
},
};
}
function records(db: Database.Database) {
return {
signups: db.prepare('SELECT * FROM signups ORDER BY id').all(),
outbox: db.prepare('SELECT * FROM outbox ORDER BY id').all(),
audit: db.prepare('SELECT * FROM audit ORDER BY id').all(),
};
}
function field(html: string, name: string): string {
const input = new RegExp(`<input\\b[^>]*\\bname="${name}"[^>]*>`).exec(html)?.[0] ?? '';
return /value="([^"]*)"/.exec(input)?.[1] ?? '';
}
function nextLink(response: Response): string {
const location = response.headers.get('location');
if (!location) throw new Error('Missing management redirect');
return location.split('?')[0]!;
}
async function switchTo(app: ReturnType<typeof createApp>, link: string, destination: number, ip = '203.0.113.1') {
const page = await (await app.request(link)).text();
return postSwitch(app, link, page, destination, ip);
}
function postSwitch(app: ReturnType<typeof createApp>, link: string, page: string, destination: number, ip: string) {
return app.request(`${link}/switch`, {
method: 'POST',
headers: { origin: 'http://127.0.0.1:3000', 'x-test-ip': ip, 'x-forwarded-for': '198.51.100.99' },
body: new URLSearchParams({
switch_token: field(page, 'switch_token'), form_token: field(page, 'form_token'), destination: String(destination),
}),
});
}
+87
View File
@@ -0,0 +1,87 @@
import { createHash } from 'node:crypto';
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { syncBrand } from '../scripts/sync-brand.mjs';
const dirs: string[] = [];
function makeDir(): string {
const dir = mkdtempSync(path.join(tmpdir(), 'hope-brand-'));
dirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
describe('syncBrand', () => {
it('keeps the bundled tokens when the source is missing', () => {
const dest = makeDir();
const tokens = path.join(dest, 'tokens.css');
writeFileSync(tokens, 'keep-me\n');
writeFileSync(path.join(dest, 'keep.txt'), 'unrelated\n');
const result = syncBrand({
source: path.join(dest, 'missing-brand'),
dest,
syncedAt: '2026-10-14T12:00:00.000Z',
});
expect(result.copied).toBe(false);
expect(result.warnings[0]).toMatch(/not found/);
expect(readFileSync(tokens, 'utf8')).toBe('keep-me\n');
expect(readFileSync(path.join(dest, 'keep.txt'), 'utf8')).toBe('unrelated\n');
});
it('copies tokens and font bytes without prepending text to the font', () => {
const source = makeDir();
const dest = makeDir();
mkdirSync(path.join(source, 'fonts'), { recursive: true });
writeFileSync(
path.join(source, 'tokens.css'),
'/* License: keep this */\n:root { --hope-ink:#222; }\n',
);
const font = Buffer.from([0, 1, 2, 3, 255, 10]);
writeFileSync(path.join(source, 'fonts', 'Lexend.woff2'), font);
writeFileSync(path.join(source, 'OFL.txt'), 'SIL Open Font License\n');
writeFileSync(path.join(dest, 'keep.txt'), 'unrelated\n');
const once = syncBrand({ source, dest, syncedAt: '2026-10-14T12:00:00.000Z' });
expect(once.copied).toBe(true);
const css = readFileSync(path.join(dest, 'tokens.css'), 'utf8');
expect(css).toContain('Source: ');
expect(css).toContain('Synced: 2026-10-14T12:00:00.000Z');
expect(css).toContain('/* License: keep this */');
expect(css.match(/Hope Volunteer brand tokens/g)).toHaveLength(1);
const copied = readFileSync(path.join(dest, 'fonts', 'Lexend.woff2'));
expect(Buffer.compare(copied, font)).toBe(0);
expect(copied.subarray(0, 2).toString()).not.toBe('/*');
expect(readFileSync(path.join(dest, 'OFL.txt'), 'utf8')).toContain('SIL Open Font License');
expect(readFileSync(path.join(dest, 'keep.txt'), 'utf8')).toBe('unrelated\n');
const manifest = JSON.parse(readFileSync(path.join(dest, 'fonts.manifest.json'), 'utf8')) as {
fonts: { file: string; sha256: string }[];
};
expect(manifest.fonts[0]?.sha256).toBe(createHash('sha256').update(font).digest('hex'));
syncBrand({ source, dest, syncedAt: '2026-10-15T12:00:00.000Z' });
const twice = readFileSync(path.join(dest, 'tokens.css'), 'utf8');
expect(twice.match(/Hope Volunteer brand tokens/g)).toHaveLength(1);
expect(twice).toContain('Synced: 2026-10-15T12:00:00.000Z');
});
});
describe('bundled brand', () => {
it('uses the specification tokens and does not call Google Fonts', () => {
const root = path.resolve(import.meta.dirname, '..');
const tokens = readFileSync(path.join(root, 'public/brand/tokens.css'), 'utf8');
const app = readFileSync(path.join(root, 'public/css/app.css'), 'utf8');
expect(tokens).toContain('--hope-ink:#222');
expect(tokens).toContain('--hope-yellow:#f9e194');
expect(tokens).toContain('--font-body:"Lexend",system-ui,sans-serif');
expect(tokens).not.toContain('fonts.googleapis.com');
expect(app).toContain('var(--hope-ink)');
expect(app).toContain('var(--font-body)');
expect(app).not.toContain('fonts.googleapis.com');
});
});
+234
View File
@@ -0,0 +1,234 @@
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { createTemplate, endTemplate, updateTemplate } from '../src/admin/store.js';
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 { expandTemplates } from '../src/recurrence.js';
import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z';
const ORIGIN = 'http://127.0.0.1:3000';
const ZONE = 'America/Chicago';
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('weekly template editing', () => {
it('keeps generated shifts when a template changes or ends', async () => {
const db = await openDb();
const eventId = insertEvent(db);
const created = createTemplate(db, 1, eventId, templateInput({ weekday: 3, role: 'Sorting' }), NOW);
expect(created.ok).toBe(true);
if (!created.ok) return;
expandTemplates(db, NOW, { eventId, coordinatorId: 1 });
const before = shiftRows(db);
const updated = updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 3, role: 'Intake', capacity: 9 }), NOW);
expect(updated.ok).toBe(true);
expandTemplates(db, NOW, { eventId, coordinatorId: 1 });
expect(shiftRows(db)).toEqual(before);
const template = db.prepare('SELECT role, capacity, revision, active FROM shift_templates WHERE id = ?').get(created.id) as {
role: string;
capacity: number;
revision: number;
active: number;
};
expect(template).toEqual({ role: 'Intake', capacity: 9, revision: 2, active: 1 });
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'template.update'")).toBe(1);
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(0);
const ended = endTemplate(db, 1, eventId, created.id, NOW);
expect(ended.ok).toBe(true);
expandTemplates(db, NOW, { eventId, coordinatorId: 1 });
expect(shiftRows(db)).toEqual(before);
expect((db.prepare('SELECT active FROM shift_templates WHERE id = ?').get(created.id) as { active: number }).active).toBe(0);
expect(updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 3, role: 'Sorting' }), NOW).ok).toBe(false);
});
it('rejects an overnight template and an end date before the first date', async () => {
const db = await openDb();
const eventId = insertEvent(db);
const overnight = createTemplate(db, 1, eventId, templateInput({ weekday: 5, start: '22:00', end: '02:00' }), NOW);
expect(overnight.ok).toBe(false);
const backwards = createTemplate(db, 1, eventId, templateInput({ weekday: 5, startsOn: '2026-10-20', endsOn: '2026-10-14' }), NOW);
expect(backwards.ok).toBe(false);
expect(count(db, 'SELECT COUNT(*) AS n FROM shift_templates')).toBe(0);
});
it('adds only the new weekday and refuses a stale form', async () => {
const { app, db } = await buildApp();
const eventId = insertEvent(db);
const cookie = await signIn(app, db);
const stale = await postTemplate(app, eventId, cookie, { csrf: 'nope' });
expect(stale.status).toBe(403);
expect(count(db, 'SELECT COUNT(*) AS n FROM shift_templates')).toBe(0);
const saved = await postTemplate(app, eventId, cookie, { weekday: '3', role: 'Sorting' });
expect(saved.status).toBe(303);
expect(saved.headers.get('location')).toBe(`/admin/events/${eventId}?notice=template-saved`);
const generated = await postGenerate(app, eventId, cookie);
expect(generated.status).toBe(303);
const wednesdays = count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Sorting'");
expect(wednesdays).toBe(9);
const friday = await postTemplate(app, eventId, cookie, { weekday: '5', role: 'Intake', capacity: '4' });
expect(friday.headers.get('location')).toBe(`/admin/events/${eventId}?notice=template-saved`);
await postGenerate(app, eventId, cookie);
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Sorting'")).toBe(wednesdays);
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Intake' AND capacity = 4")).toBe(8);
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE template_revision = 1")).toBe(wednesdays + 8);
const templateId = (
db.prepare("SELECT id AS id FROM shift_templates WHERE role = 'Intake'").get() as { id: number }
).id;
const edited = await postTemplate(app, eventId, cookie, { weekday: '5', role: 'Packing', capacity: '4', templateId });
expect(edited.headers.get('location')).toBe(`/admin/events/${eventId}?notice=template-saved`);
expect((db.prepare('SELECT revision, role FROM shift_templates WHERE id = ?').get(templateId) as { revision: number; role: string })).toEqual({
revision: 2,
role: 'Packing',
});
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Intake'")).toBe(8);
const ended = await postEnd(app, eventId, templateId, cookie);
expect(ended.headers.get('location')).toBe(`/admin/events/${eventId}?notice=template-ended`);
const page = await app.request(`/admin/events/${eventId}?notice=template-ended`, { headers: { cookie } });
const html = await page.text();
expect(html).toContain('This weekly template has ended. Shifts already on the schedule stay.');
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Intake'")).toBe(8);
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(1);
});
});
function templateInput(overrides: Partial<{ weekday: number; role: string; capacity: number; start: string; end: string; startsOn: string; endsOn: string | null }>) {
return {
role: overrides.role ?? 'Sorting',
weekday: overrides.weekday ?? 3,
start: overrides.start ?? '09:00',
end: overrides.end ?? '12:00',
capacity: overrides.capacity ?? 6,
startsOn: overrides.startsOn ?? '2026-10-14',
endsOn: overrides.endsOn === undefined ? null : overrides.endsOn,
};
}
function shiftRows(db: Awaited<ReturnType<typeof openDb>>) {
return db
.prepare(
`SELECT occurrence_date, role, capacity, template_revision, cancelled
FROM shifts ORDER BY occurrence_date`,
)
.all();
}
async function openDb() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-template-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
bootstrapAdmin(db, config.bootstrapAdminEmail, NOW);
return db;
}
async function buildApp() {
const root = mkdtempSync(path.join(tmpdir(), 'hope-template-'));
dirs.push(root);
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
const db = await openAppDatabase(config);
databases.push(db);
bootstrapAdmin(db, config.bootstrapAdminEmail, NOW);
const app = createApp(config, db, {
now: NOW,
clientIp: () => '203.0.113.10',
verifyTurnstile: async () => ({ ok: true }),
});
return { app, db };
}
function insertEvent(db: Awaited<ReturnType<typeof openDb>>): number {
const saved = db
.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES ('weekly', 'Weekly pantry', '', 'Sioux Center, Iowa', ?, 1, ?)`,
)
.run(ZONE, NOW);
return Number(saved.lastInsertRowid);
}
async function signIn(app: Awaited<ReturnType<typeof buildApp>>['app'], db: Awaited<ReturnType<typeof openDb>>) {
await app.request('/login', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ email: 'coordinator@example.invalid', company_website: '', 'cf-turnstile-response': 'token' }),
});
const queued = db.prepare("SELECT body_text AS body_text FROM outbox WHERE kind = 'magic_link'").get() as { body_text: string };
const token = /\/login\/link\/([A-Za-z0-9_-]+)/.exec(queued.body_text)?.[1] ?? '';
const page = await app.request(`/login/link/${token}`);
const proof = /name="proof"[^>]*value="([^"]*)"/.exec(await page.text())?.[1] ?? '';
const signedIn = await app.request(`/login/link/${token}`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ proof }),
});
const cookie = /hope_session=([^;]+)/.exec(signedIn.headers.get('set-cookie') ?? '')?.[1] ?? '';
return `hope_session=${cookie}`;
}
async function csrfFor(app: Awaited<ReturnType<typeof buildApp>>['app'], eventId: number, cookie: string) {
const current = await app.request(`/admin/events/${eventId}`, { headers: { cookie } });
return /name="csrf"[^>]*value="([^"]*)"/.exec(await current.text())?.[1] ?? '';
}
async function postTemplate(
app: Awaited<ReturnType<typeof buildApp>>['app'],
eventId: number,
cookie: string,
fields: { csrf?: string; weekday?: string; role?: string; capacity?: string; templateId?: number },
) {
const csrf = fields.csrf ?? (await csrfFor(app, eventId, cookie));
const pathName = fields.templateId ? `/admin/events/${eventId}/templates/${fields.templateId}` : `/admin/events/${eventId}/templates`;
return app.request(pathName, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({
csrf,
role: fields.role ?? 'Sorting',
weekday: fields.weekday ?? '3',
start: '09:00',
end: '12:00',
capacity: fields.capacity ?? '6',
startsOn: '2026-10-14',
endsOn: '',
}),
});
}
async function postGenerate(app: Awaited<ReturnType<typeof buildApp>>['app'], eventId: number, cookie: string) {
const csrf = await csrfFor(app, eventId, cookie);
return app.request(`/admin/events/${eventId}/generate`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ csrf }),
});
}
async function postEnd(app: Awaited<ReturnType<typeof buildApp>>['app'], eventId: number, templateId: number, cookie: string) {
const csrf = await csrfFor(app, eventId, cookie);
return app.request(`/admin/events/${eventId}/templates/${templateId}/end`, {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({ csrf }),
});
}
function count(db: Awaited<ReturnType<typeof openDb>>, sql: string): number {
return Number((db.prepare(sql).get() as { n: number }).n);
}
+59
View File
@@ -0,0 +1,59 @@
import { describe, expect, it } from 'vitest';
import {
addLocalDays,
formatInstantInZone,
localShiftToUtc,
localToUtc,
LocalTimeError,
weekdayIndex,
} from '../src/time.js';
const ZONE = 'America/Chicago';
describe('local time conversion', () => {
it('keeps a 9:00 local shift at 9:00 on both sides of daylight saving time', () => {
const winter = localToUtc('2026-01-15', '09:00', ZONE);
const summer = localToUtc('2026-07-15', '09:00', ZONE);
expect(winter).toBe('2026-01-15T15:00:00.000Z');
expect(summer).toBe('2026-07-15T14:00:00.000Z');
expect(formatInstantInZone(winter, ZONE).time24).toBe('09:00');
expect(formatInstantInZone(summer, ZONE).time24).toBe('09:00');
expect(formatInstantInZone(winter, ZONE).timeLabel).toBe('9:00 AM');
expect(formatInstantInZone(summer, ZONE).timeLabel).toBe('9:00 AM');
expect(formatInstantInZone(winter, ZONE).abbreviation).toBe('CST');
expect(formatInstantInZone(summer, ZONE).abbreviation).toBe('CDT');
expect(formatInstantInZone(winter, ZONE).label).toContain('9:00 AM CST');
});
it('converts the 2026 March and November boundaries without moving 9:00', () => {
expect(localToUtc('2026-03-07', '09:00', ZONE)).toBe('2026-03-07T15:00:00.000Z');
expect(localToUtc('2026-03-08', '09:00', ZONE)).toBe('2026-03-08T14:00:00.000Z');
expect(localToUtc('2026-03-09', '09:00', ZONE)).toBe('2026-03-09T14:00:00.000Z');
expect(localToUtc('2026-10-31', '09:00', ZONE)).toBe('2026-10-31T14:00:00.000Z');
expect(localToUtc('2026-11-01', '09:00', ZONE)).toBe('2026-11-01T15:00:00.000Z');
expect(localToUtc('2026-11-02', '09:00', ZONE)).toBe('2026-11-02T15:00:00.000Z');
expect(formatInstantInZone('2026-03-08T14:00:00.000Z', ZONE).time24).toBe('09:00');
expect(formatInstantInZone('2026-11-01T15:00:00.000Z', ZONE).time24).toBe('09:00');
});
it('rejects a local time that does not exist or happens twice', () => {
expect(() => localToUtc('2026-03-08', '02:30', ZONE)).toThrow(LocalTimeError);
expect(() => localToUtc('2026-03-08', '02:30', ZONE)).toThrow(/does not exist/);
expect(() => localToUtc('2026-11-01', '01:30', ZONE)).toThrow(/happens twice/);
});
it('rejects an impossible calendar date and a reversed shift', () => {
expect(() => localToUtc('2026-02-31', '09:00', ZONE)).toThrow(/not a real calendar date/);
expect(() => localShiftToUtc('2026-10-20', '12:00', '09:00', ZONE)).toThrow(/same day/);
expect(() => localShiftToUtc('2026-10-20', '09:00', '09:00', ZONE)).toThrow(/same day/);
const shift = localShiftToUtc('2026-10-20', '09:00', '12:00', ZONE);
expect(shift.endsAtUtc > shift.startsAtUtc).toBe(true);
});
it('counts weekdays with Sunday as 0 and adds calendar days', () => {
expect(weekdayIndex('2026-03-08', ZONE)).toBe(0);
expect(weekdayIndex('2026-01-15', ZONE)).toBe(4);
expect(addLocalDays('2026-01-31', 1)).toBe('2026-02-01');
expect(addLocalDays('2026-03-08', 1)).toBe('2026-03-09');
});
});
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from 'vitest';
import { loadConfig } from '../src/config.js';
import { absoluteUrl, appPath, cookiePath } from '../src/url.js';
import { devEnv } from './env.js';
describe('URL helper', () => {
const root = loadConfig(devEnv({ BASE_PATH: '' }));
const mounted = loadConfig(devEnv({ BASE_PATH: '/volunteer' }));
it('serves health, assets, and mail links at the root', () => {
expect(absoluteUrl(root, '/healthz')).toBe('http://127.0.0.1:3000/healthz');
expect(absoluteUrl(root, '/css/app.css')).toBe('http://127.0.0.1:3000/css/app.css');
expect(absoluteUrl(root, '/brand/tokens.css')).toBe('http://127.0.0.1:3000/brand/tokens.css');
expect(absoluteUrl(root, '/m/abc')).toBe('http://127.0.0.1:3000/m/abc');
expect(cookiePath(root)).toBe('/');
});
it('prefixes the same paths when the app is mounted at /volunteer', () => {
expect(appPath(mounted, '/')).toBe('/volunteer');
expect(appPath(mounted, '/healthz')).toBe('/volunteer/healthz');
expect(absoluteUrl(mounted, '/healthz')).toBe('http://127.0.0.1:3000/volunteer/healthz');
expect(absoluteUrl(mounted, '/css/app.css')).toBe('http://127.0.0.1:3000/volunteer/css/app.css');
expect(absoluteUrl(mounted, '/e/weekly-pantry')).toBe('http://127.0.0.1:3000/volunteer/e/weekly-pantry');
expect(absoluteUrl(mounted, '/m/abc')).toBe('http://127.0.0.1:3000/volunteer/m/abc');
expect(cookiePath(mounted)).toBe('/volunteer');
});
it('rejects a path that would skip the prefix helper', () => {
expect(() => appPath(root, 'healthz')).toThrow(/start with/);
});
});