feat: require phone and drop under-18 signup

Phone is required on public and coordinator forms, and the under-18
guardian flow, mail copies, and export columns are removed.
This commit is contained in:
blake committed 2026-10-26 13:30:30 -05:00
1 parent 7cfb984d63
commit 58da832bac
27 files changed
+225 -562

No files matched your search

+13 -32
View File
@@ -384,9 +384,9 @@ describe('coordinator screens', () => {
const html = await page.text();
expect(html).toContain('Add a walk-in');
expect(html).toContain('src="/js/enhance.js?v=');
expect(html).toContain('data-under-18');
expect(html).toContain('data-guardian');
expect(html).not.toMatch(/id="walkin-under-18"[^>]*\schecked/);
expect(html).not.toContain('data-under-18');
expect(html).not.toContain('data-guardian');
expect(html).not.toContain('They are under 18');
expect(html).not.toContain('cf-turnstile');
const body = walkInBody(html, {
name: 'Dee Example',
@@ -420,26 +420,16 @@ describe('coordinator screens', () => {
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 () => {
it('keeps a walk-in off a full, closed, or ended shift', 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);
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND status = 'pending'")).toBe(1);
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');
@@ -558,9 +548,6 @@ describe('coordinator screens', () => {
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');
@@ -600,8 +587,8 @@ describe('coordinator screens', () => {
notes: string;
reminders_off: number;
is_minor: number;
guardian_name: string;
guardian_email: string;
guardian_name: string | null;
guardian_email: string | null;
shift_id: number;
};
expect(created).toMatchObject({
@@ -610,15 +597,15 @@ describe('coordinator screens', () => {
phone: '712-555-0199',
notes: 'Blue shirt',
reminders_off: 1,
is_minor: 1,
guardian_name: 'Pat Example',
guardian_email: 'pat@example.invalid',
is_minor: 0,
guardian_name: null,
guardian_email: null,
shift_id: destinationId,
});
expect(shiftVersions(db)).toEqual(versions);
expect(counted(db, signupId, 'confirmation', 'cancelled')).toBe(2);
expect(counted(db, signupId, 'confirmation', 'cancelled')).toBe(1);
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 = 'changed' AND status = 'pending'")).toBe(1);
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;
@@ -848,9 +835,6 @@ function reserve(db: Awaited<ReturnType<typeof buildApp>>['db'], shiftId: number
email,
phone: '712-555-0100',
notes: 'Bring gloves',
isMinor: false,
guardianName: null,
guardianEmail: null,
operationId,
now: NOW,
mail: MAIL,
@@ -999,11 +983,8 @@ function walkInBody(html: string, fields: Record<string, string>) {
form_token: field(html, 'form_token'),
name: fields.name ?? '',
email: fields.email ?? '',
phone: fields.phone ?? '',
phone: fields.phone ?? '712-555-0100',
notes: fields.notes ?? '',
guardianName: fields.guardianName ?? '',
guardianEmail: fields.guardianEmail ?? '',
...(fields.under18 ? { under18: fields.under18 } : {}),
});
}
+1 -3
View File
@@ -371,10 +371,8 @@ async function postSignup(
first_name: fields.name.slice(0, fields.name.indexOf(' ')),
last_name: fields.name.slice(fields.name.indexOf(' ') + 1),
email: fields.email,
phone: '',
phone: '712-555-0100',
notes: '',
guardianName: '',
guardianEmail: '',
company_website: '',
'cf-turnstile-response': 'widget-token',
});
+53 -50
View File
@@ -41,43 +41,49 @@ afterEach(() => {
});
describe('contact spreadsheet', () => {
it('keeps two emails for one name, ignores address, and skips a bad email', async () => {
it('keeps two emails for one name, ignores address, and skips a bad email or blank phone', async () => {
const db = await openDb();
const imported = importContactCsv(db, null, PEOPLE, NOW);
expect(imported.ok).toBe(true);
if (!imported.ok) return;
expect(imported.result.added).toBe(3);
expect(imported.result.skipped).toBe(1);
expect(imported.result.skips).toEqual([{ line: 5, code: 'e' }]);
expect(contactImportSentence(imported.result)).toBe('Saved 3 new contacts. Skipped 1 row.');
expect(imported.result.added).toBe(2);
expect(imported.result.skipped).toBe(2);
expect(imported.result.skips).toEqual([
{ line: 3, code: 'm' },
{ line: 5, code: 'e' },
]);
expect(contactImportSentence(imported.result)).toBe('Saved 2 new contacts. Skipped 2 rows.');
const rows = db
.prepare('SELECT first_name, last_name, email, phone FROM contacts ORDER BY id')
.all() as { first_name: string; last_name: string; email: string; phone: string | null }[];
expect(rows).toEqual([
{ first_name: 'Kristi', last_name: 'Anderson', email: 'kristi@example.invalid', phone: '712441076' },
{ first_name: 'Kara', last_name: 'Acevedo', email: 'kara@example.invalid', phone: null },
{ first_name: 'Kara', last_name: 'Acevedo', email: 'kara.other@example.invalid', phone: '712-555-0100' },
]);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(0);
const audit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.import'`).get() as { detail_json: string };
expect(JSON.parse(audit.detail_json)).toEqual({ added: 3, changed: 0, unchanged: 0, skipped: 1 });
expect(JSON.parse(audit.detail_json)).toEqual({ added: 2, changed: 0, unchanged: 0, skipped: 2 });
expect(audit.detail_json).not.toContain('@');
});
it('keeps two names that share an email and updates only the matching name', async () => {
const db = await openDb();
importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,One,ada@example.invalid,111\n', NOW);
const renamed = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ADA@example.invalid,\n', NOW);
const renamed = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ADA@example.invalid,222\n', NOW);
expect(renamed.ok && renamed.result.added).toBe(1);
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([
{ first_name: 'Ada', last_name: 'One', phone: '111' },
{ first_name: 'Ada', last_name: 'Two', phone: null },
{ first_name: 'Ada', last_name: 'Two', phone: '222' },
]);
const replaced = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nada,two,ada@example.invalid,(712) 555-0100\n', NOW);
expect(replaced.ok && replaced.result.changed).toBe(1);
expect(db.prepare('SELECT phone FROM contacts ORDER BY id').all()).toEqual([{ phone: '111' }, { phone: '712-555-0100' }]);
const same = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,\n', NOW);
const blankPhone = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,\n', NOW);
expect(blankPhone.ok && blankPhone.result.skipped).toBe(1);
expect(blankPhone.ok && blankPhone.result.skips).toEqual([{ line: 2, code: 'm' }]);
expect(db.prepare("SELECT phone FROM contacts WHERE last_name = 'Two'").get()).toEqual({ phone: '712-555-0100' });
const same = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,712-555-0100\n', NOW);
expect(same.ok && same.result.unchanged).toBe(1);
expect(db.prepare("SELECT phone FROM contacts WHERE last_name = 'Two'").get()).toEqual({ phone: '712-555-0100' });
const shaped = importContactCsv(
@@ -128,17 +134,21 @@ describe('contact spreadsheet', () => {
error: CONTACT_CSV_COLUMNS,
});
expect(importContactCsv(db, null, ' ', NOW)).toEqual({ ok: false, error: CONTACT_CSV_EMPTY });
expect(importContactCsv(db, null, 'First Name,Last Name,Email\n"Ada,One,ada@example.invalid\n', NOW)).toEqual({
expect(importContactCsv(db, null, 'First Name,Last Name,Email\nAda,One,ada@example.invalid\n', NOW)).toEqual({
ok: false,
error: CONTACT_CSV_COLUMNS,
});
expect(importContactCsv(db, null, 'First Name,Last Name,Email,Phone\n"Ada,One,ada@example.invalid,555\n', NOW)).toEqual({
ok: false,
error: CONTACT_CSV_READ,
});
expect(importContactCsv(db, null, 'First Name,Last Name,Email\0\n', NOW)).toEqual({ ok: false, error: CONTACT_CSV_BINARY });
expect(importContactCsv(db, null, `First Name,Last Name,Email\n${'x'.repeat(64 * 1024)}`, NOW)).toEqual({
expect(importContactCsv(db, null, 'First Name,Last Name,Email,Phone\0\n', NOW)).toEqual({ ok: false, error: CONTACT_CSV_BINARY });
expect(importContactCsv(db, null, `First Name,Last Name,Email,Phone\n${'x'.repeat(64 * 1024)}`, NOW)).toEqual({
ok: false,
error: CONTACT_CSV_LIMIT,
});
const lines = ['First Name,Last Name,Email'];
for (let i = 0; i < 2001; i += 1) lines.push(`A,B,a${i}@b.c`);
const lines = ['First Name,Last Name,Email,Phone'];
for (let i = 0; i < 2001; i += 1) lines.push(`A,B,a${i}@b.c,555`);
expect(importContactCsv(db, null, lines.join('\n'), NOW)).toEqual({ ok: false, error: CONTACT_CSV_LARGE });
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(0);
});
@@ -182,10 +192,10 @@ describe('contact pages', () => {
it('shows the next page of contacts and keeps the search', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const lines = ['First Name,Last Name,Email'];
const lines = ['First Name,Last Name,Email,Phone'];
for (let i = 0; i <= CONTACT_LIST_PAGE; i += 1) {
const name = String(i).padStart(2, '0');
lines.push(`Ada,N${name},n${name}@example.invalid`);
lines.push(`Ada,N${name},n${name}@example.invalid,712-555-${name}00`);
}
const imported = await postFile(app, cookie, lines.join('\n'));
expect(imported.status).toBe(303);
@@ -232,7 +242,8 @@ describe('contact pages', () => {
expect(imported.status).toBe(303);
const page = await app.request(imported.headers.get('location') ?? '', { headers: { cookie } });
const html = await page.text();
expect(html).toContain('Saved 3 new contacts. Skipped 1 row.');
expect(html).toContain('Saved 2 new contacts. Skipped 2 rows.');
expect(html).toContain('Row 3 was skipped because the phone is missing.');
expect(html).toContain('Row 5 was skipped because the email is not an address.');
expect(html).toContain('Kristi Anderson');
expect(html).toContain('kara.other@example.invalid');
@@ -266,7 +277,7 @@ describe('contact pages', () => {
const exportAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.export'`).get() as {
detail_json: string;
};
expect(exportAudit.detail_json).toBe('{"rows":3}');
expect(exportAudit.detail_json).toBe('{"rows":2}');
const hidden = await app.request('/admin/contacts/export', { method: 'POST' });
expect(hidden.status).toBe(303);
@@ -400,19 +411,11 @@ describe('contact pages', () => {
expect(personHtml).not.toContain('Finished');
expect(personHtml).not.toContain('Packing');
expect(personHtml).toContain('Add to this shift');
expect(personHtml).toContain('They are under 18');
expect(personHtml).not.toContain('They are under 18');
const beforeMail = count(db, `SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation'`);
expect(beforeMail).toBe(0);
const minor = await postContactShift(app, cookie, contactId, openId, personHtml, { under18: 'yes' });
expect(minor.status).toBe(400);
const minorHtml = await minor.text();
expect(minorHtml).toContain('Enter the guardian name.');
expect(minorHtml).toContain(`<option value="${openId}" selected="">`);
expect(count(db, `SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid'`)).toBe(0);
expect(count(db, `SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation'`)).toBe(0);
const stale = await postContactShift(app, cookie, contactId, openId, personHtml.replace(/name="form_token" value="[^"]*"/, 'name="form_token" value="nope"'), {});
expect(stale.status).toBe(400);
expect(await stale.text()).toContain('This form is out of date. Submit it again.');
@@ -437,29 +440,25 @@ describe('contact pages', () => {
const walkInAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'signup.walkin'`).get() as { detail_json: string };
expect(walkInAudit.detail_json).not.toContain('@');
const minorFile = await postFile(app, cookie, 'First Name,Last Name,Email\nBea,Minor,bea@example.invalid\n');
expect(minorFile.status).toBe(303);
const beaFile = await postFile(app, cookie, 'First Name,Last Name,Email,Phone\nBea,Example,bea@example.invalid,712-555-0102\n');
expect(beaFile.status).toBe(303);
const beaId = (db.prepare(`SELECT id AS id FROM contacts WHERE email = 'bea@example.invalid'`).get() as { id: number }).id;
const beaPage = await app.request(`/admin/contacts/${beaId}`, { headers: { cookie } });
const beaHtml = await beaPage.text();
expect(beaPage.status).toBe(200);
expect(beaHtml).toContain(`<option value="${unpublishedId}">`);
const beaAdded = await postContactShift(app, cookie, beaId, unpublishedId, beaHtml, {
under18: 'yes',
guardianName: 'Pat Minor',
guardianEmail: 'pat@example.invalid',
});
const beaAdded = await postContactShift(app, cookie, beaId, unpublishedId, beaHtml, {});
expect(beaAdded.status).toBe(303);
const beaSignup = db.prepare(
`SELECT is_minor AS is_minor, guardian_name AS guardian_name, guardian_email AS guardian_email
FROM signups WHERE email_norm = 'bea@example.invalid'`,
).get() as { is_minor: number; guardian_name: string; guardian_email: string };
expect(beaSignup).toEqual({ is_minor: 1, guardian_name: 'Pat Minor', guardian_email: 'pat@example.invalid' });
).get() as { is_minor: number; guardian_name: string | null; guardian_email: string | null };
expect(beaSignup).toEqual({ is_minor: 0, guardian_name: null, guardian_email: null });
expect(count(db, `SELECT COUNT(*) AS n FROM contacts`)).toBe(2);
const mailed = db
.prepare(`SELECT to_email AS to_email FROM outbox WHERE kind = 'confirmation' ORDER BY to_email`)
.all() as Array<{ to_email: string }>;
expect(mailed.map((row) => row.to_email)).toEqual(['ada@example.invalid', 'bea@example.invalid', 'pat@example.invalid']);
expect(mailed.map((row) => row.to_email)).toEqual(['ada@example.invalid', 'bea@example.invalid']);
const againPage = await app.request(`/admin/contacts/${contactId}`, { headers: { cookie } });
const againPageHtml = await againPage.text();
@@ -495,7 +494,7 @@ describe('contact pages', () => {
const manualAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.manual'`).get() as { detail_json: string };
expect(manualAudit.detail_json).not.toContain('@');
const same = await postManual(app, cookie, { firstName: 'Ada', lastName: 'Example', email: 'ada@example.invalid', phone: '' });
const same = await postManual(app, cookie, { firstName: 'Ada', lastName: 'Example', email: 'ada@example.invalid', phone: '712-555-0100' });
expect(same.headers.get('location')).toBe('/admin/contacts?notice=contact-matched');
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '712-555-0100' });
@@ -504,18 +503,24 @@ describe('contact pages', () => {
expect(changed.headers.get('location')).toBe('/admin/contacts?notice=contact-updated');
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '712-555-0199' });
const other = await postManual(app, cookie, { firstName: 'Ada', lastName: 'Other', email: 'ada@example.invalid', phone: '' });
const other = await postManual(app, cookie, { firstName: 'Ada', lastName: 'Other', email: 'ada@example.invalid', phone: '712-555-0111' });
expect(other.headers.get('location')).toBe('/admin/contacts?notice=contact-saved');
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([
{ first_name: 'Ada', last_name: 'Example', phone: '712-555-0199' },
{ first_name: 'Ada', last_name: 'Other', phone: null },
{ first_name: 'Ada', last_name: 'Other', phone: '712-555-0111' },
]);
const blankPhone = await postManual(app, cookie, { firstName: 'Sam', lastName: 'Example', email: 'sam@example.invalid', phone: '' });
expect(blankPhone.status).toBe(400);
expect(await blankPhone.text()).toContain('Enter a phone number.');
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(2);
const invalid = await postManual(app, cookie, { firstName: '', lastName: 'Example', email: 'not-an-email', phone: '' });
expect(invalid.status).toBe(400);
const invalidHtml = await invalid.text();
expect(invalidHtml).toContain('Enter a first name.');
expect(invalidHtml).toContain('Enter an email address.');
expect(invalidHtml).toContain('Enter a phone number.');
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(2);
expect(await (await app.request('/')).text()).not.toContain('ada@example.invalid');
});
@@ -639,8 +644,9 @@ describe('contact pages', () => {
email: 'patrick@example.invalid',
phone: '',
});
expect(cleared.status).toBe(303);
expect(db.prepare('SELECT phone FROM contacts WHERE id = ?').get(contactId)).toEqual({ phone: null });
expect(cleared.status).toBe(400);
expect(await cleared.text()).toContain('Enter a phone number.');
expect(db.prepare('SELECT phone FROM contacts WHERE id = ?').get(contactId)).toEqual({ phone: '712-555-0199' });
expect(db.prepare(`SELECT phone AS phone FROM signups WHERE email_norm = 'pat@example.invalid'`).get()).toEqual({
phone: '712-555-0199',
});
@@ -658,17 +664,17 @@ describe('contact pages', () => {
expect(db.prepare('SELECT first_name, email, phone FROM contacts WHERE id = ?').get(contactId)).toEqual({
first_name: 'Pat',
email: 'patrick@example.invalid',
phone: null,
phone: '712-555-0199',
});
const missing = await postCorrect(app, cookie, 999, {
firstName: 'Pat',
lastName: 'Review',
email: 'patrick@example.invalid',
phone: '',
phone: '712-555-0199',
});
expect(missing.status).toBe(404);
expect(count(db, `SELECT COUNT(*) AS n FROM audit WHERE action = 'contacts.correct'`)).toBe(3);
expect(count(db, `SELECT COUNT(*) AS n FROM audit WHERE action = 'contacts.correct'`)).toBe(2);
});
});
@@ -809,7 +815,7 @@ async function postContactShift(
contactId: number,
shiftId: number,
html: string,
fields: { under18?: string; guardianName?: string; guardianEmail?: string; notes?: string },
fields: { notes?: string },
) {
const csrf = /name="csrf" value="([^"]*)"/.exec(html)?.[1] ?? '';
const formToken = /name="form_token" value="([^"]*)"/.exec(html)?.[1] ?? '';
@@ -821,9 +827,6 @@ async function postContactShift(
form_token: formToken,
shift: String(shiftId),
notes: fields.notes ?? '',
under18: fields.under18 ?? '',
guardianName: fields.guardianName ?? '',
guardianEmail: fields.guardianEmail ?? '',
}),
});
}
+9 -16
View File
@@ -36,7 +36,6 @@ afterEach(() => {
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',
@@ -49,22 +48,21 @@ describe('transactional mail', () => {
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 () => {
it('queues one confirmation 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' }));
const saved = reserveSignup(db, reservation(shiftId, { email: 'pat@example.invalid', name: 'Pat Review' }));
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' },
{ to_email: 'pat@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' }));
const same = reserveSignup(db, reservation(shiftId, { email: 'pat@example.invalid', name: 'Pat Review', operationId: 'same-operation' }));
expect(same.ok && same.replay).toBe(true);
expect(db.prepare('SELECT COUNT(*) AS n FROM outbox').get()).toEqual({ n: 2 });
expect(db.prepare('SELECT COUNT(*) AS n FROM outbox').get()).toEqual({ n: 1 });
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 });
const other = reserveSignup(db, reservation(shiftId, { email: 'other@example.invalid', operationId: 'other-operation' }));
expect(other.ok).toBe(true);
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE to_email = 'other@example.invalid'").get()).toEqual({ n: 1 });
});
it('sends the queued letter once and does not send it again', async () => {
@@ -181,10 +179,8 @@ describe('transactional mail', () => {
first_name: 'Listed',
last_name: 'Person',
email: 'listed@example.invalid',
phone: '',
phone: '712-555-0100',
notes: '',
guardianName: '',
guardianEmail: '',
company_website: '',
'cf-turnstile-response': 'widget-token',
});
@@ -340,9 +336,6 @@ function reservation(shiftId: number, overrides: Partial<ReserveInput> = {}): Re
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,
+1 -3
View File
@@ -173,10 +173,8 @@ async function postSignup(
first_name: fields.name.slice(0, fields.name.indexOf(' ')),
last_name: fields.name.slice(fields.name.indexOf(' ') + 1),
email: fields.email,
phone: '',
phone: '712-555-0100',
notes: '',
guardianName: '',
guardianEmail: '',
company_website: '',
'cf-turnstile-response': 'widget-token',
});
+5 -5
View File
@@ -117,13 +117,13 @@ describe('public pages', () => {
expect(shiftHtml).toContain('name="last_name"');
expect(shiftHtml).toContain('First name');
expect(shiftHtml).toContain('Last name');
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/);
expect(shiftHtml).not.toContain('data-under-18');
expect(shiftHtml).not.toContain('data-guardian');
expect(shiftHtml).not.toContain('I am under 18');
const css = await (await app.request('/css/app.css')).text();
expect(css).toContain('.signup-form:not(:has([data-under-18]:checked)) [data-guardian]');
expect(css).not.toContain('data-under-18');
expect(css).not.toContain('data-guardian');
expect(shiftHtml).not.toContain('SECRET-SHIFT-NOTE');
expect(shiftHtml).not.toContain('Secret Person');
-3
View File
@@ -245,9 +245,6 @@ function reservation(shiftId: number, overrides: Partial<ReserveInput> = {}): Re
email: 'pat.review@example.invalid',
phone: null,
notes: null,
isMinor: false,
guardianName: null,
guardianEmail: null,
operationId: 'reminder-operation',
now: NOW,
mail: MAIL,
+2 -2
View File
@@ -61,9 +61,9 @@ describe('development seed', () => {
for (const signup of signups) {
expect(signup.email.endsWith(`@${SEED_EMAIL_DOMAIN}`)).toBe(true);
expect(signup.group_size).toBe(1);
expect(signup.is_minor).toBe(0);
expect(signup.guardian_email).toBeNull();
}
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/);
+18 -70
View File
@@ -10,7 +10,7 @@ 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 { SIGNUP_EMAIL_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';
@@ -26,7 +26,7 @@ afterEach(() => {
});
describe('capacity-safe signup', () => {
it('requires a first name and a last name', async () => {
it('requires a first name, a last name, and a phone number', async () => {
const { app, shiftId } = await buildApp();
const missingLast = await postSignup(app, shiftId, { firstName: 'Pat', lastName: '', email: 'pat.only@example.invalid' }, { ip: '203.0.113.11' });
expect(missingLast.status).toBe(400);
@@ -36,6 +36,14 @@ describe('capacity-safe signup', () => {
const missingFirst = await postSignup(app, shiftId, { firstName: ' ', lastName: 'Review', email: 'review.only@example.invalid' }, { ip: '203.0.113.12' });
expect(missingFirst.status).toBe(400);
expect(await missingFirst.text()).toContain('Enter your first name.');
const missingPhone = await postSignup(
app,
shiftId,
{ firstName: 'Pat', lastName: 'Review', email: 'pat.phone@example.invalid', phone: '' },
{ ip: '203.0.113.13' },
);
expect(missingPhone.status).toBe(400);
expect(await missingPhone.text()).toContain('Enter your phone number.');
});
it('saves one person, shows a private confirmation link, and does not send mail', async () => {
@@ -131,39 +139,16 @@ describe('capacity-safe signup', () => {
]);
});
it('requires a guardian for a minor and ignores guardian fields for an adult', async () => {
it('stores new signups as adults with null guardian fields', 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 first = await postSignup(app, shiftId, { email: 'one@example.invalid' }, { ip: '203.0.113.41' });
expect(first.status).toBe(303);
const second = await postSignup(app, shiftId, { email: 'two@example.invalid' }, { ip: '203.0.113.42' });
expect(second.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 },
{ email_norm: 'one@example.invalid', is_minor: 0, guardian_name: null, guardian_email: null, group_size: 1 },
{ email_norm: 'two@example.invalid', is_minor: 0, guardian_name: null, guardian_email: null, group_size: 1 },
]);
});
@@ -225,34 +210,6 @@ describe('capacity-safe signup', () => {
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) {
@@ -311,9 +268,6 @@ describe('capacity-safe signup', () => {
email: `person-${index}@example.invalid`,
phone: null,
notes: null,
isMinor: false,
guardianName: null,
guardianEmail: null,
operationId: `operation-${index}-abcdef`,
now: NOW,
mail: {
@@ -421,9 +375,6 @@ async function postSignup(
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 },
@@ -441,14 +392,11 @@ async function postSignup(
first_name: fields.firstName ?? (splitAt === -1 ? postedName : postedName.slice(0, splitAt)),
last_name: fields.lastName ?? (splitAt === -1 ? '' : postedName.slice(splitAt + 1).trim()),
email: fields.email ?? 'pat.review@example.invalid',
phone: fields.phone ?? '',
phone: fields.phone ?? '712-555-0100',
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: {
+9 -13
View File
@@ -24,8 +24,7 @@ afterEach(() => {
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 link = f.signup('target@example.invalid');
let app = f.app();
let accepted = 0;
const mailer = { send: async () => { accepted++; return { result: 'sent' as const, providerId: 'mock' }; } };
@@ -59,21 +58,19 @@ describe('public switch limits', () => {
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 () => {
it('shares recipient limits across different people at the same email 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');
const link = f.signup('shared@example.invalid', `Person ${i}`);
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 blocked = f.signup('shared@example.invalid', 'Blocked Person');
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');
// Rejection must not spend this person's allowance on an otherwise valid link.
let ownLink = f.signup('other@example.invalid', 'Other 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);
@@ -117,7 +114,7 @@ describe('public switch limits', () => {
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');
const link = f.signup('shared@example.invalid', `Parallel ${i}`);
return switchTo(app, link, f.shifts[1]!, `203.0.113.${i + 1}`);
});
const responses = await Promise.all(requests);
@@ -169,10 +166,9 @@ async function fixture() {
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') => {
signup: (email: string, name = 'Test Person') => {
const result = reserveSignup(db, {
shiftId: shifts[0]!, name, email, guardianEmail, isMinor: guardianEmail !== null,
guardianName: guardianEmail ? 'Guardian' : null, phone: null, notes: null,
shiftId: shifts[0]!, name, email, phone: null, notes: null,
operationId: randomBytes(16).toString('hex'), now: NOW, mail,
});
if (!result.ok || !result.manageToken) throw new Error('Fixture signup failed');