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:
1 parent
7cfb984d63
commit
58da832bac
27 files changed
+207
-544
No files matched your search
@@ -46,8 +46,8 @@ The core tables for later steps are already in `migrations/001_init.sql`. Behavi
|
||||
Do not treat this repository as an approved privacy policy or an approved operating setup.
|
||||
|
||||
- [ ] **D1.** SMTP2GO is the email provider. The pantry verifies the sender and the reply-to.
|
||||
- [ ] **D2.** Whether a group signup is essential. A shared email can already sign up more than one person on the same shift. Each person takes one spot and gets their own confirmation and private link. The same person, matched by name and email, cannot take a second spot on that shift. `group_size` stays 1. Group signup still needs its own decision: who the reservation is for, how minors work, what happens when the count changes, and who receives mail.
|
||||
- [ ] **D3.** The pantry approves privacy wording, minor and guardian requirements, and retention periods, including copies and exports.
|
||||
- [ ] **D2.** Whether a group signup is essential. A shared email can already sign up more than one person on the same shift. Each person takes one spot and gets their own confirmation and private link. The same person, matched by name and email, cannot take a second spot on that shift. `group_size` stays 1. Group signup still needs its own decision: who the reservation is for, what happens when the count changes, and who receives mail.
|
||||
- [ ] **D3.** The pantry approves privacy wording and retention periods, including copies and exports.
|
||||
- [ ] **D4.** The pantry confirms the coordinator list, who owns the administrator account, and the recovery contact.
|
||||
- [ ] **D5.** Configure production Turnstile keys and the allowed hostname.
|
||||
- [ ] **D6.** The host owner confirms the offsite backup destination, who owns it, the recovery target, and a restore test.
|
||||
@@ -73,7 +73,7 @@ npm run seed
|
||||
|
||||
Open `/` for the weekly pantry schedule. `/e/weekly-pantry` is the same seeded event. `/privacy` is the unapproved privacy notice. `/healthz` returns `{"ok":true,"database":"ok"}` and nothing else. Volunteer names, emails, and notes are not on the public list. A shift shows how many spots are filled, such as 3/5 spots filled. A shift with space left uses a soft green label. A full shift uses a soft red label.
|
||||
|
||||
An open shift has a signup form. It asks for one person. Another person can use the same email and takes another spot. The same person cannot take a second spot. It asks for a parent or guardian when the volunteer is under 18. The form needs JavaScript because of the Turnstile check. Wait a few seconds after the page loads before submitting. The confirmation page shows a private link and says a confirmation email is on the way. That page works without JavaScript. Cancel this signup there to open the spot again. A cancellation email is queued, and a confirmation that has not been sent yet is dropped. That person can sign up again once the cancellation is saved. Someone else can use the email while the first signup is still confirmed. A cancelled signup stays on that private page until the link expires. A private link controls only that signup. Use the separate link for each signup.
|
||||
An open shift has a signup form. It asks for one person. Another person can use the same email and takes another spot. The same person cannot take a second spot. The form needs JavaScript because of the Turnstile check. Wait a few seconds after the page loads before submitting. The confirmation page shows a private link and says a confirmation email is on the way. That page works without JavaScript. Cancel this signup there to open the spot again. A cancellation email is queued, and a confirmation that has not been sent yet is dropped. That person can sign up again once the cancellation is saved. Someone else can use the email while the first signup is still confirmed. A cancelled signup stays on that private page until the link expires. A private link controls only that signup. Use the separate link for each signup.
|
||||
|
||||
With `MAIL_DRIVER=console`, the development server tries to send queued mail every 30 seconds and prints each accepted message in its terminal. That is not delivery to a real inbox. `sent` means the driver accepted the message. A lost result is marked uncertain and is not sent again. SMTP2GO is the mail provider. Set `MAIL_DRIVER=smtp2go` and `SMTP2GO_API_KEY` to send through it. Postmark and SES remain available.
|
||||
|
||||
@@ -89,9 +89,9 @@ On a confirmed signup, **Attended** and **No-show** record whether that person c
|
||||
|
||||
On the private signup page, **Switch to** does the same thing for the volunteer. The next page has the new link. A full, cancelled, ended, or unpublished shift is not offered. A switch is rejected if that name and email already occupy the destination shift. The destination list does not reveal which other shifts match those details. If the switch cannot be saved, the original signup stays.
|
||||
|
||||
Public switching permits 10 validated attempts per IP per 10-minute window and 5 per recipient per local calendar day (`DEFAULT_TZ`). Volunteer and guardian addresses share the same recipient counter; a shared address is counted once. These HMAC-keyed counters live in SQLite and survive link changes, new signup IDs, and restarts. A blocked request returns HTTP 429 with `Retry-After`, leaves the signup unchanged, and queues no email. Invalid origins, invalid proofs, and completed replays do not spend recipient allowances. Valid attempts that fail because a destination is full or unavailable still count. Viewing or cancelling a signup remains available when switching is limited. Coordinator roster moves use their authenticated workflow and are not subject to these public switch limits.
|
||||
Public switching permits 10 validated attempts per IP per 10-minute window and 5 per recipient per local calendar day (`DEFAULT_TZ`). These HMAC-keyed counters live in SQLite and survive link changes, new signup IDs, and restarts. A blocked request returns HTTP 429 with `Retry-After`, leaves the signup unchanged, and queues no email. Invalid origins, invalid proofs, and completed replays do not spend recipient allowances. Valid attempts that fail because a destination is full or unavailable still count. Viewing or cancelling a signup remains available when switching is limited. Coordinator roster moves use their authenticated workflow and are not subject to these public switch limits.
|
||||
|
||||
**Management link scope:** names and email addresses entered in a public form are unverified. Each private link authorizes only its own signup, including links from confirmation cookies, email, and guardian copies. Cross-signup listing, cancellation, and switching are disabled, and the old `/m/:token/also/...` routes return 404. This also applies to existing links. A future multi-signup view must verify identity separately.
|
||||
**Management link scope:** names and email addresses entered in a public form are unverified. Each private link authorizes only its own signup, including links from confirmation cookies and email. Cross-signup listing, cancellation, and switching are disabled, and the old `/m/:token/also/...` routes return 404. This also applies to existing links. A future multi-signup view must verify identity separately.
|
||||
|
||||
**Add weekly shifts**, on a coordinator event page, fills the next eight weeks from that event's active weekly templates. Starting the app does the same thing for every event. A shift that is already on that date stays as it is, including a cancelled one, so the template cannot recreate it. A 9:00 shift stays 9:00 when daylight saving time changes. A local time that does not exist, or that happens twice, is skipped.
|
||||
|
||||
@@ -103,13 +103,13 @@ A reminder is queued at each saved time before a confirmed signup, while the shi
|
||||
|
||||
**Download this roster**, on a shift, and **Download this event**, on an event, save a spreadsheet of the signups. **Download this date range**, on the coordinator page, uses each event's local shift date. The file includes cancelled signups and attendance. A cell that would be a spreadsheet formula is saved as text. The download is not cached. A copy on a coordinator's computer is outside this app, and the app does not delete it later.
|
||||
|
||||
**Contacts**, on the coordinator page, keeps a list of people. A confirmed signup is saved on this list. The name is split at the last space. A signup name with no space is saved with a hyphen as the last name. A different name is a separate contact, even when the email matches. The same name and email updates that contact. Cancelling the signup does not remove the contact. Saving someone here does not sign them up for a shift. **Import this list** reads a spreadsheet with First Name, Last Name, Email, and Phone, including the SignUpGenius people export. An Address column is ignored. The same name and email updates that person. A different name stays a separate person, even when the email matches. A different email stays a separate person, even when the name matches. A blank phone does not erase a phone already saved. Names are capitalized. A word that already mixes upper and lower case stays as written. A phone number with ten digits is saved with dashes, like 712-555-0100. A leading 1 is left off. Email addresses are stored in lowercase. Importing does not take a spot and does not send email. **Download contacts** saves that list. A cell that would be a spreadsheet formula is saved as text. A downloaded copy stays on the coordinator's computer. The signup retention job does not clear this list. The list is the contacts table in `app.db`. The list shows 20 people. **See more** shows the next 20 on this page, without returning to the top, and keeps a search. **Choose a name**, then choose the shift from **Shift**. That takes one spot and queues a confirmation email. A full, cancelled, or ended shift is not in that list, and a shift they are already on is not in that list. A shift that is not on the public list can still be chosen. **Correct this contact**, on that page, saves a corrected name, email, or phone on the same person. A phone typo can be replaced. A hyphen saved as the last name can be replaced with the real last name. Changing the name does not create a second person, even when the email stays the same. A blank phone removes the saved number. It does not change a signup, take a spot, or send email. **Remove** deletes that person from the list only. On an open shift, **Saved contact** fills a walk-in. The walk-in still takes one spot and queues a confirmation email. **Add a contact** saves one person who has not signed up. It does not take a spot and does not send email. The same name and email updates that person. A different name is saved separately, even with the same email. Typing a walk-in who is not on the list saves them here too.
|
||||
**Contacts**, on the coordinator page, keeps a list of people. A confirmed signup is saved on this list. The name is split at the last space. A signup name with no space is saved with a hyphen as the last name. A different name is a separate contact, even when the email matches. The same name and email updates that contact. Cancelling the signup does not remove the contact. Saving someone here does not sign them up for a shift. **Import this list** reads a spreadsheet with First Name, Last Name, Email, and Phone, including the SignUpGenius people export. An Address column is ignored. The same name and email updates that person. A different name stays a separate person, even when the email matches. A different email stays a separate person, even when the name matches. A row without a phone is skipped. Names are capitalized. A word that already mixes upper and lower case stays as written. A phone number with ten digits is saved with dashes, like 712-555-0100. A leading 1 is left off. Email addresses are stored in lowercase. Importing does not take a spot and does not send email. **Download contacts** saves that list. A cell that would be a spreadsheet formula is saved as text. A downloaded copy stays on the coordinator's computer. The signup retention job does not clear this list. The list is the contacts table in `app.db`. The list shows 20 people. **See more** shows the next 20 on this page, without returning to the top, and keeps a search. **Choose a name**, then choose the shift from **Shift**. That takes one spot and queues a confirmation email. A full, cancelled, or ended shift is not in that list, and a shift they are already on is not in that list. A shift that is not on the public list can still be chosen. **Correct this contact**, on that page, saves a corrected name, email, or phone on the same person. A phone typo can be replaced. A hyphen saved as the last name can be replaced with the real last name. Changing the name does not create a second person, even when the email stays the same. Phone is required. It does not change a signup, take a spot, or send email. **Remove** deletes that person from the list only. On an open shift, **Saved contact** fills a walk-in. The walk-in still takes one spot and queues a confirmation email. **Add a contact** saves one person who has not signed up. It does not take a spot and does not send email. The same name and email updates that person. A different name is saved separately, even with the same email. Typing a walk-in who is not on the list saves them here too.
|
||||
|
||||
**Settings**, on the coordinator page, saves the two reminder times, the reply-to address, the privacy-page wording, and how many months to keep a signup after the shift ends. The defaults are 48 hours, 2 hours, the reply-to address from the server configuration, a blank privacy notice, and 24 months. The two reminder times have to be different whole hours from 1 to 336. The month count is a whole number from 1 to 120. A blank privacy notice leaves the public page saying a notice is not approved yet. Saved wording is shown on `/privacy` as written. Saving it does not by itself make that wording an approved privacy policy. New mail uses the saved reply-to address. Mail already queued keeps the address it was given. The sending address stays in the server configuration.
|
||||
|
||||
Around 1:00 AM in an event's time zone, the app adds any missing shifts from that event's active weekly templates. It does this once for that local date. If 1:00 happens twice when the clocks change, the second hour does not add them again. If 1:00 does not exist that day, the fill runs once the local clock is past 1:00. A restart later that day still fills the date if it was missed. A date that already has a shift, including a cancelled one, stays as it is. Starting the app, and **Add weekly shifts**, still fill the schedule as well.
|
||||
|
||||
After 1:00 AM Central Time, once that local date, the app removes the name, email, phone, guardian, notes, and private link from each signup whose shift ended more than the saved number of months ago. The default is 24. The shift, the signup status, and attendance stay, so the count remains. The minor answer is cleared. A spreadsheet downloaded from an old shift leaves those personal cells blank. This changes the live database. It does not change a spreadsheet already on a coordinator's computer, a message already in someone's inbox, or an older database backup. Clearing a value does not promise that the old bytes are immediately gone from the disk. The contact list is separate. Clearing an old signup does not remove that person from the contact list.
|
||||
After 1:00 AM Central Time, once that local date, the app removes the name, email, phone, notes, and private link from each signup whose shift ended more than the saved number of months ago. The default is 24. The shift, the signup status, and attendance stay, so the count remains. Legacy guardian columns, when present, are cleared too. A spreadsheet downloaded from an old shift leaves those personal cells blank. This changes the live database. It does not change a spreadsheet already on a coordinator's computer, a message already in someone's inbox, or an older database backup. Clearing a value does not promise that the old bytes are immediately gone from the disk. The contact list is separate. Clearing an old signup does not remove that person from the contact list.
|
||||
|
||||
Finished mail loses its recipient, subject, and body 30 days after it was sent, cancelled, or given up on. Mail that is still waiting after 30 days is cancelled and cleared, so it is not sent late. Mail for a signup is cleared in the same cleanup that removes that signup's details. A sign-in message is cleared once its link is used or expired. Every hour, the app clears those sign-in messages, finished mail past 30 days, expired sign-in sessions, used or expired sign-in links, and rate-limit counters older than about two days. Audit notes older than 24 months are deleted. Those notes are counts and ids. Starting the app runs this cleanup before it accepts requests. If 1:00 AM happens twice when the clocks change, the second hour does not run it again. A restart after 1:00 AM still runs it when that date was missed.
|
||||
|
||||
@@ -156,7 +156,7 @@ SQLite runs in WAL mode with foreign keys on. Migrations in `migrations/` are ap
|
||||
|
||||
There is no cascade delete. A shift that still has signups cannot be deleted out from under the roster. A coordinator cancels a signup or a shift first. Removing a cancelled person, then an empty finished shift, is a separate step. Removing an ended template leaves its shifts in place. An event can be removed only when it is off the public list and nothing remains on it.
|
||||
|
||||
Confirmed signups have a partial unique index on shift, normalized email, and name, without regard to case. Normalization of the email is trim, Unicode normalize, and lowercase. Dots and plus-tags stay. A different person can use that email and takes their own spot. Anonymized rows clear the name and email, so they do not collide with that index. A minor who is not anonymized needs a guardian name and email. `group_size` cannot be anything but 1.
|
||||
Confirmed signups have a partial unique index on shift, normalized email, and name, without regard to case. Normalization of the email is trim, Unicode normalize, and lowercase. Dots and plus-tags stay. A different person can use that email and takes their own spot. Anonymized rows clear the name and email, so they do not collide with that index. New signups always store `is_minor` as 0 with null guardian fields; legacy columns remain for older rows. `group_size` cannot be anything but 1.
|
||||
|
||||
`reminders_sent.queued_at` means the reminder was queued. `sent_at` means a provider accepted it. Queueing mail is not delivery. A closer reminder that replaces an older overdue one is stored as not sent.
|
||||
|
||||
|
||||
@@ -1003,11 +1003,6 @@ article.shift-card {
|
||||
background: var(--hope-blue-75);
|
||||
}
|
||||
|
||||
/* Parent or guardian stays closed until Under 18 is checked, on every signup form. */
|
||||
.signup-form:not(:has([data-under-18]:checked)) [data-guardian] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.signup-form legend {
|
||||
padding: 0 0.35rem;
|
||||
}
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
bindCalendar();
|
||||
document.querySelectorAll('[data-contact]').forEach(bindContact);
|
||||
document.querySelectorAll('[data-see-more]').forEach(bindSeeMore);
|
||||
var boxes = document.querySelectorAll('[data-under-18]');
|
||||
for (var i = 0; i < boxes.length; i += 1) bind(boxes[i]);
|
||||
|
||||
function bindNav() {
|
||||
var header = document.querySelector('.header');
|
||||
@@ -94,18 +92,4 @@
|
||||
var input = form.elements[name];
|
||||
if (input && 'value' in input) input.value = value;
|
||||
}
|
||||
|
||||
function bind(box) {
|
||||
var form = box.form;
|
||||
if (!form) return;
|
||||
var guardian = form.querySelector('[data-guardian]');
|
||||
if (!guardian) return;
|
||||
var inputs = guardian.querySelectorAll('input');
|
||||
var sync = function () {
|
||||
var on = box.checked;
|
||||
for (var j = 0; j < inputs.length; j += 1) inputs[j].required = on;
|
||||
};
|
||||
box.addEventListener('change', sync);
|
||||
sync();
|
||||
}
|
||||
})();
|
||||
@@ -556,9 +556,6 @@ async function submitAddContactToShift(c: Context, services: AdminServices): Pro
|
||||
email: parsed.draft.emailNorm,
|
||||
phone: parsed.draft.phone,
|
||||
notes: parsed.draft.notes,
|
||||
isMinor: parsed.draft.isMinor,
|
||||
guardianName: parsed.draft.guardianName,
|
||||
guardianEmail: parsed.draft.guardianEmail,
|
||||
operationId: token.claims.operationId,
|
||||
now: services.now(),
|
||||
mail: mailIdentity(services.db, services.config),
|
||||
@@ -1224,9 +1221,6 @@ async function submitWalkIn(c: Context, services: AdminServices): Promise<Respon
|
||||
email: parsed.draft.emailNorm,
|
||||
phone: parsed.draft.phone,
|
||||
notes: parsed.draft.notes,
|
||||
isMinor: parsed.draft.isMinor,
|
||||
guardianName: parsed.draft.guardianName,
|
||||
guardianEmail: parsed.draft.guardianEmail,
|
||||
operationId: token.claims.operationId,
|
||||
now: services.now(),
|
||||
mail: mailIdentity(services.db, services.config),
|
||||
@@ -1571,9 +1565,6 @@ function signupValuesFrom(body: Record<string, unknown>): SignupValues {
|
||||
email: textField(body, 'email'),
|
||||
phone: textField(body, 'phone'),
|
||||
notes: textField(body, 'notes'),
|
||||
under18: textField(body, 'under18') === 'yes',
|
||||
guardianName: textField(body, 'guardianName'),
|
||||
guardianEmail: textField(body, 'guardianEmail'),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+20
-34
@@ -42,7 +42,7 @@ const SHIFT_PEOPLE_BODY = 'Remove everyone on this roster first.';
|
||||
const SHIFT_WAIT_BODY = 'Cancel this shift, or wait until it has ended, before removing it.';
|
||||
const SHIFT_WEEKLY_NOTE =
|
||||
'This date came from a weekly template that is still active. Add weekly shifts can put this date back. End that template first if the date should stay gone.';
|
||||
const PERSON_DELETE_BODY = 'This deletes their name, email, phone, guardian details, and notes from the roster. It does not send email.';
|
||||
const PERSON_DELETE_BODY = 'This deletes their name, email, phone, and notes from the roster. It does not send email.';
|
||||
const PERSON_WAIT_BODY = 'Cancel this signup before removing it.';
|
||||
const PERSON_CANCEL_BODY = 'Cancelling a signup emails them. Their old private link stops working, and the email includes a new one.';
|
||||
const SHIFT_CANCEL_EMPTY = 'No one is signed up. Cancelling closes the shift and does not send email.';
|
||||
@@ -341,7 +341,7 @@ export function SettingsPage(props: {
|
||||
<label>
|
||||
Keep signups for, months
|
||||
<input name="retention_months" type="number" min="1" max="120" required value={props.values.retentionMonths} />
|
||||
<span class="hint">The default is 24, counted after the shift ends. After 1:00 AM Central Time, signups older than this lose their name, email, phone, guardian, and notes in this app. A spreadsheet already downloaded is left as it is.</span>
|
||||
<span class="hint">The default is 24, counted after the shift ends. After 1:00 AM Central Time, signups older than this lose their name, email, phone, and notes in this app. A spreadsheet already downloaded is left as it is.</span>
|
||||
{errors.retentionMonths ? <span class="error">{errors.retentionMonths}</span> : null}
|
||||
</label>
|
||||
<label>
|
||||
@@ -406,18 +406,18 @@ export function ContactsPage(props: {
|
||||
<form method="post" action={appPath(props.config, '/admin/contacts/new')} class="signup-form desk-download">
|
||||
<input type="hidden" name="csrf" value={props.csrf} />
|
||||
<h2>Add a contact</h2>
|
||||
<p>This saves one person. It does not sign them up and does not send email. The same name and email updates that person. A different name is saved separately, even with the same email. A blank phone does not erase a phone already saved. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100.</p>
|
||||
<p>This saves one person. It does not sign them up and does not send email. The same name and email updates that person. A different name is saved separately, even with the same email. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100.</p>
|
||||
<WalkInField id="contact-first" label="First name" name="first_name" type="text" value={manual.values.firstName} error={manual.errors.firstName} />
|
||||
<WalkInField id="contact-last" label="Last name" name="last_name" type="text" value={manual.values.lastName} error={manual.errors.lastName} />
|
||||
<WalkInField id="contact-email" label="Email" name="email" type="email" value={manual.values.email} error={manual.errors.email} />
|
||||
<WalkInField id="contact-phone" label="Phone (optional)" name="phone" type="tel" value={manual.values.phone} error={manual.errors.phone} hint="We will not text them" />
|
||||
<WalkInField id="contact-phone" label="Phone" name="phone" type="tel" value={manual.values.phone} error={manual.errors.phone} required />
|
||||
<button type="submit">Save this contact</button>
|
||||
</form>
|
||||
<form method="post" action={appPath(props.config, '/admin/contacts/import')} class="signup-form desk-download" enctype="multipart/form-data">
|
||||
<input type="hidden" name="csrf" value={props.csrf} />
|
||||
<h2>Import a contact list</h2>
|
||||
<p>
|
||||
Use a spreadsheet with First Name, Last Name, Email, and Phone. The SignUpGenius people export works. Address is ignored. The same name and email updates that person. A different name stays a separate person, even when the email matches. A different email stays a separate person, even when the name matches. A blank phone does not erase a phone already saved. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100. Email addresses are stored in lowercase. The file has to be under 64 KB.
|
||||
Use a spreadsheet with First Name, Last Name, Email, and Phone. The SignUpGenius people export works. Address is ignored. The same name and email updates that person. A different name stays a separate person, even when the email matches. A different email stays a separate person, even when the name matches. A row without a phone is skipped. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100. Email addresses are stored in lowercase. The file has to be under 64 KB.
|
||||
</p>
|
||||
{props.importError ? <p class="error">{props.importError}</p> : null}
|
||||
<label>
|
||||
@@ -521,19 +521,19 @@ export function ContactPage(props: {
|
||||
<input type="hidden" name="csrf" value={props.csrf} />
|
||||
<h2>Correct this contact</h2>
|
||||
<p>
|
||||
This changes the saved person. A different name stays this contact and does not create a second person. It does not change a signup, take a spot, or send email. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100. A blank phone removes the saved number.
|
||||
This changes the saved person. A different name stays this contact and does not create a second person. It does not change a signup, take a spot, or send email. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100.
|
||||
</p>
|
||||
<WalkInField id="correct-first" label="First name" name="first_name" type="text" value={correction.values.firstName} error={correction.errors.firstName} />
|
||||
<WalkInField id="correct-last" label="Last name" name="last_name" type="text" value={correction.values.lastName} error={correction.errors.lastName} />
|
||||
<WalkInField id="correct-email" label="Email" name="email" type="email" value={correction.values.email} error={correction.errors.email} />
|
||||
<WalkInField
|
||||
id="correct-phone"
|
||||
label="Phone (optional)"
|
||||
label="Phone"
|
||||
name="phone"
|
||||
type="tel"
|
||||
value={correction.values.phone}
|
||||
error={correction.errors.phone}
|
||||
hint="We will not text them"
|
||||
required
|
||||
/>
|
||||
<button type="submit">Save this correction</button>
|
||||
</form>
|
||||
@@ -568,15 +568,6 @@ export function ContactPage(props: {
|
||||
</textarea>
|
||||
{errors.notes ? <span class="field-error">{errors.notes}</span> : null}
|
||||
</label>
|
||||
<label class="check" for="add-under-18">
|
||||
<input id="add-under-18" name="under18" type="checkbox" value="yes" data-under-18="" checked={values.under18 ? true : undefined} />
|
||||
They are under 18
|
||||
</label>
|
||||
<fieldset data-guardian="">
|
||||
<legend>Parent or guardian</legend>
|
||||
<WalkInField id="add-guardianName" label="Guardian name" name="guardianName" type="text" value={values.guardianName} error={errors.guardianName} />
|
||||
<WalkInField id="add-guardianEmail" label="Guardian email" name="guardianEmail" type="email" value={values.guardianEmail} error={errors.guardianEmail} />
|
||||
</fieldset>
|
||||
<button type="submit">Add to this shift</button>
|
||||
</form>
|
||||
) : (
|
||||
@@ -1559,7 +1550,7 @@ function WalkInForm(props: { config: AppConfig; csrf: string; shiftId: number; f
|
||||
) : null}
|
||||
<WalkInField id="walkin-name" label="Name" name="name" type="text" value={values.name} error={errors.name} />
|
||||
<WalkInField id="walkin-email" label="Email" name="email" type="email" value={values.email} error={errors.email} />
|
||||
<WalkInField id="walkin-phone" label="Phone (optional)" name="phone" type="tel" value={values.phone} error={errors.phone} hint="We will not text you" />
|
||||
<WalkInField id="walkin-phone" label="Phone" name="phone" type="tel" value={values.phone} error={errors.phone} required />
|
||||
<label for="walkin-notes">
|
||||
Notes (optional)
|
||||
<textarea id="walkin-notes" name="notes" aria-invalid={errors.notes ? 'true' : undefined} aria-describedby={errors.notes ? 'walkin-notes-error' : undefined}>
|
||||
@@ -1571,21 +1562,21 @@ function WalkInForm(props: { config: AppConfig; csrf: string; shiftId: number; f
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
<label class="check" for="walkin-under-18">
|
||||
<input id="walkin-under-18" name="under18" type="checkbox" value="yes" data-under-18="" checked={values.under18 ? true : undefined} />
|
||||
They are under 18
|
||||
</label>
|
||||
<fieldset data-guardian="">
|
||||
<legend>Parent or guardian</legend>
|
||||
<WalkInField id="walkin-guardianName" label="Guardian name" name="guardianName" type="text" value={values.guardianName} error={errors.guardianName} />
|
||||
<WalkInField id="walkin-guardianEmail" label="Guardian email" name="guardianEmail" type="email" value={values.guardianEmail} error={errors.guardianEmail} />
|
||||
</fieldset>
|
||||
<button type="submit">Add to this shift</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function WalkInField(props: { id: string; label: string; name: string; type: 'text' | 'email' | 'tel'; value: string; error?: string; hint?: string }) {
|
||||
function WalkInField(props: {
|
||||
id: string;
|
||||
label: string;
|
||||
name: string;
|
||||
type: 'text' | 'email' | 'tel';
|
||||
value: string;
|
||||
error?: string;
|
||||
hint?: string;
|
||||
required?: boolean;
|
||||
}) {
|
||||
const errorId = `${props.id}-error`;
|
||||
const hintId = `${props.id}-hint`;
|
||||
const describedBy = [props.hint ? hintId : '', props.error ? errorId : ''].filter(Boolean).join(' ') || undefined;
|
||||
@@ -1598,6 +1589,7 @@ function WalkInField(props: { id: string; label: string; name: string; type: 'te
|
||||
type={props.type}
|
||||
value={props.value}
|
||||
autocomplete="off"
|
||||
required={props.required ? true : undefined}
|
||||
aria-invalid={props.error ? 'true' : undefined}
|
||||
aria-describedby={describedBy}
|
||||
/>
|
||||
@@ -1631,12 +1623,6 @@ function Roster(props: { config: AppConfig; csrf: string; people: RosterPerson[]
|
||||
</p>
|
||||
<p>{person.email}</p>
|
||||
{person.phone ? <p>{person.phone}</p> : null}
|
||||
{person.minor ? <p>Under 18</p> : null}
|
||||
{person.guardianName || person.guardianEmail ? (
|
||||
<p>
|
||||
Guardian: {person.guardianName} {person.guardianEmail}
|
||||
</p>
|
||||
) : null}
|
||||
{person.notes ? <p>Note: {person.notes}</p> : null}
|
||||
<p>{person.status === 'confirmed' ? 'Confirmed' : 'Cancelled'}</p>
|
||||
{person.status === 'cancelled' ? (
|
||||
|
||||
+4
-17
@@ -85,9 +85,6 @@ export type RosterPerson = {
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string | null;
|
||||
minor: boolean;
|
||||
guardianName: string | null;
|
||||
guardianEmail: string | null;
|
||||
notes: string | null;
|
||||
status: 'confirmed' | 'cancelled';
|
||||
attendance: 'attended' | 'no-show' | null;
|
||||
@@ -294,7 +291,7 @@ export function getAdminShift(db: Database.Database, id: number): AdminShift | n
|
||||
if (!row) return null;
|
||||
const people = db
|
||||
.prepare(
|
||||
`SELECT id, name, email, phone, is_minor, guardian_name, guardian_email, notes, status, attended
|
||||
`SELECT id, name, email, phone, notes, status, attended
|
||||
FROM signups
|
||||
WHERE shift_id = ? AND anonymized_at IS NULL AND name IS NOT NULL AND email IS NOT NULL
|
||||
ORDER BY CASE status WHEN 'confirmed' THEN 0 ELSE 1 END, id`,
|
||||
@@ -304,9 +301,6 @@ export function getAdminShift(db: Database.Database, id: number): AdminShift | n
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string | null;
|
||||
is_minor: number;
|
||||
guardian_name: string | null;
|
||||
guardian_email: string | null;
|
||||
notes: string | null;
|
||||
status: string;
|
||||
attended: number | null;
|
||||
@@ -324,9 +318,6 @@ export function getAdminShift(db: Database.Database, id: number): AdminShift | n
|
||||
name: person.name,
|
||||
email: person.email,
|
||||
phone: person.phone,
|
||||
minor: person.is_minor === 1,
|
||||
guardianName: person.guardian_name,
|
||||
guardianEmail: person.guardian_email,
|
||||
notes: person.notes,
|
||||
status: person.status,
|
||||
attendance: person.attended === 1 ? 'attended' : person.attended === 0 ? 'no-show' : null,
|
||||
@@ -1286,7 +1277,6 @@ function relocate(
|
||||
token: issued.token,
|
||||
volunteerName: source.name,
|
||||
volunteerEmail: source.email_norm,
|
||||
guardianEmail: source.is_minor === 1 ? source.guardian_email : null,
|
||||
shift: shift.facts,
|
||||
mail,
|
||||
now,
|
||||
@@ -1419,7 +1409,7 @@ function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail
|
||||
if (!shift) return 0;
|
||||
const people = db
|
||||
.prepare(
|
||||
`SELECT id, name, email_norm, guardian_email, shift_id, status
|
||||
`SELECT id, name, email_norm, shift_id, status
|
||||
FROM signups
|
||||
WHERE shift_id = ? AND status = 'confirmed' AND anonymized_at IS NULL AND name IS NOT NULL AND email_norm IS NOT NULL`,
|
||||
)
|
||||
@@ -1435,7 +1425,6 @@ function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail
|
||||
token,
|
||||
volunteerName: person.name,
|
||||
volunteerEmail: person.email_norm,
|
||||
guardianEmail: person.guardian_email,
|
||||
shift: shift.facts,
|
||||
mail,
|
||||
now,
|
||||
@@ -1448,7 +1437,7 @@ function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail
|
||||
function cancelConfirmedOnShift(db: Database.Database, shiftId: number, now: string, mail: MailIdentity): number {
|
||||
const people = db
|
||||
.prepare(
|
||||
`SELECT id, name, email_norm, guardian_email, shift_id, status
|
||||
`SELECT id, name, email_norm, shift_id, status
|
||||
FROM signups
|
||||
WHERE shift_id = ? AND status = 'confirmed' AND anonymized_at IS NULL AND name IS NOT NULL AND email_norm IS NOT NULL`,
|
||||
)
|
||||
@@ -1481,7 +1470,6 @@ function cancelConfirmedPerson(db: Database.Database, person: PersonRow, now: st
|
||||
token: issued.token,
|
||||
volunteerName: person.name,
|
||||
volunteerEmail: person.email_norm,
|
||||
guardianEmail: person.guardian_email,
|
||||
shift: shift.facts,
|
||||
mail,
|
||||
now,
|
||||
@@ -1546,7 +1534,7 @@ function mailShift(db: Database.Database, shiftId: number): { version: number; e
|
||||
function loadPerson(db: Database.Database, signupId: number): PersonRow | null {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT id, name, email_norm, guardian_email, shift_id, status
|
||||
`SELECT id, name, email_norm, shift_id, status
|
||||
FROM signups
|
||||
WHERE id = ? AND anonymized_at IS NULL`,
|
||||
)
|
||||
@@ -1692,7 +1680,6 @@ type PersonRow = {
|
||||
id: number;
|
||||
name: string | null;
|
||||
email_norm: string | null;
|
||||
guardian_email: string | null;
|
||||
shift_id: number;
|
||||
status: string;
|
||||
};
|
||||
|
||||
+19
-14
@@ -16,13 +16,13 @@ const MAX_SKIPS = 30;
|
||||
const CONTROL = /[\u0000-\u001F\u007F]/;
|
||||
|
||||
export const CONTACT_CSV_EMPTY = 'Choose a spreadsheet to import.';
|
||||
export const CONTACT_CSV_COLUMNS = 'This spreadsheet needs First Name, Last Name, and Email columns.';
|
||||
export const CONTACT_CSV_COLUMNS = 'This spreadsheet needs First Name, Last Name, Email, and Phone columns.';
|
||||
export const CONTACT_CSV_READ = 'This spreadsheet could not be read.';
|
||||
export const CONTACT_CSV_LARGE = 'This spreadsheet has more than 2000 people.';
|
||||
export const CONTACT_CSV_BINARY = 'Save the spreadsheet as CSV.';
|
||||
export const CONTACT_CSV_LIMIT = 'This spreadsheet has to be under 64 KB.';
|
||||
|
||||
export type ContactSkipCode = 'e' | 'n' | 'p' | 'l' | 'c';
|
||||
export type ContactSkipCode = 'e' | 'n' | 'p' | 'm' | 'l' | 'c';
|
||||
|
||||
export type ContactSkip = { line: number; code: ContactSkipCode };
|
||||
|
||||
@@ -71,6 +71,7 @@ const SKIP_REASON: Record<ContactSkipCode, string> = {
|
||||
e: 'the email is not an address',
|
||||
n: 'the name is missing',
|
||||
p: 'the phone is too long',
|
||||
m: 'the phone is missing',
|
||||
l: 'the name is too long',
|
||||
c: 'a field has a line break',
|
||||
};
|
||||
@@ -108,7 +109,7 @@ export function parseContactSkips(value: string | undefined): ContactSkip[] {
|
||||
if (!value) return [];
|
||||
const skips: ContactSkip[] = [];
|
||||
for (const part of value.split('.')) {
|
||||
const match = /^(\d+)([enplc])$/.exec(part);
|
||||
const match = /^(\d+)([enplcm])$/.exec(part);
|
||||
if (!match) continue;
|
||||
const line = Number(match[1]);
|
||||
const code = match[2];
|
||||
@@ -224,7 +225,7 @@ export function removeContact(db: Database.Database, coordinatorId: number, id:
|
||||
/**
|
||||
* Saves the person from a confirmed signup.
|
||||
* The same name and email updates that contact. A different name is a new contact, even with the same email.
|
||||
* A blank phone does not erase a phone already saved.
|
||||
* A blank phone does not erase a phone already saved (legacy or cleared records).
|
||||
*/
|
||||
export function rememberSignupContact(
|
||||
db: Database.Database,
|
||||
@@ -267,7 +268,7 @@ export function saveManualContact(
|
||||
|
||||
/**
|
||||
* Replaces the name, email, and phone on one saved contact.
|
||||
* A different name stays this contact. A blank phone removes the saved number.
|
||||
* A different name stays this contact. Phone is required.
|
||||
*/
|
||||
export function correctContact(
|
||||
db: Database.Database,
|
||||
@@ -346,7 +347,7 @@ function columnIndex(cells: string[]): { first: number; last: number; email: num
|
||||
const last = names.indexOf('last name');
|
||||
const email = names.indexOf('email');
|
||||
const phone = names.indexOf('phone');
|
||||
if (first < 0 || last < 0 || email < 0) return null;
|
||||
if (first < 0 || last < 0 || email < 0 || phone < 0) return null;
|
||||
return { first, last, email, phone };
|
||||
}
|
||||
|
||||
@@ -382,7 +383,8 @@ function manualContact(values: ContactManualValues): { ok: true; person: ReadyCo
|
||||
if (firstName && lastName && !errors.firstName && !errors.lastName && `${firstName} ${lastName}`.length > MAX_NAME) {
|
||||
errors.lastName = `Use ${MAX_NAME} characters or fewer for the full name.`;
|
||||
}
|
||||
if (CONTROL.test(phoneRaw)) errors.phone = 'Enter a phone number without line breaks.';
|
||||
if (!phoneRaw || !phone) errors.phone = 'Enter a phone number.';
|
||||
else if (CONTROL.test(phoneRaw)) errors.phone = 'Enter a phone number without line breaks.';
|
||||
else if (phoneRaw.length > MAX_PHONE || phone.length > MAX_PHONE) errors.phone = `Use ${MAX_PHONE} characters or fewer.`;
|
||||
let email = '';
|
||||
const emailRaw = values.email.normalize('NFC').trim();
|
||||
@@ -396,8 +398,8 @@ function manualContact(values: ContactManualValues): { ok: true; person: ReadyCo
|
||||
errors.email = err instanceof EmailAddressError ? err.message : 'Enter an email address.';
|
||||
}
|
||||
}
|
||||
if (Object.keys(errors).length > 0 || !email) return { ok: false, errors };
|
||||
return { ok: true, person: { firstName, lastName, email, phone: phone.length === 0 ? null : phone } };
|
||||
if (Object.keys(errors).length > 0 || !email || !phone) return { ok: false, errors };
|
||||
return { ok: true, person: { firstName, lastName, email, phone } };
|
||||
}
|
||||
|
||||
function findContact(
|
||||
@@ -453,16 +455,19 @@ function parsePerson(cells: string[], columns: { first: number; last: number; em
|
||||
const last = capitalizeName(lastName);
|
||||
if (!first || !last) return { code: 'n' };
|
||||
if (first.length > MAX_NAME || last.length > MAX_NAME || `${first} ${last}`.length > MAX_NAME) return { code: 'l' };
|
||||
const phone = phoneRaw.length === 0 ? '' : formatPhone(phoneRaw);
|
||||
if (phoneRaw.length > MAX_PHONE || phone.length > MAX_PHONE) return { code: 'p' };
|
||||
let email = '';
|
||||
try {
|
||||
const email = normalizeEmail(emailRaw);
|
||||
email = normalizeEmail(emailRaw);
|
||||
if (email.length > MAX_EMAIL) return { code: 'e' };
|
||||
return { firstName: first, lastName: last, email, phone: phone.length === 0 ? null : phone };
|
||||
} catch (err) {
|
||||
if (err instanceof EmailAddressError) return { code: 'e' };
|
||||
throw err;
|
||||
}
|
||||
if (!phoneRaw) return { code: 'm' };
|
||||
const phone = formatPhone(phoneRaw);
|
||||
if (!phone) return { code: 'm' };
|
||||
if (phoneRaw.length > MAX_PHONE || phone.length > MAX_PHONE) return { code: 'p' };
|
||||
return { firstName: first, lastName: last, email, phone };
|
||||
}
|
||||
|
||||
function cellAt(cells: string[], index: number): string {
|
||||
@@ -533,5 +538,5 @@ function parseCsv(text: string): { line: number; cells: string[] }[] {
|
||||
}
|
||||
|
||||
function isSkipCode(value: string): value is ContactSkipCode {
|
||||
return value === 'e' || value === 'n' || value === 'p' || value === 'l' || value === 'c';
|
||||
return value === 'e' || value === 'n' || value === 'p' || value === 'm' || value === 'l' || value === 'c';
|
||||
}
|
||||
+2
-14
@@ -122,19 +122,13 @@ function insertFakeSignups(db: Database.Database, shiftId: number, createdAt: st
|
||||
name: 'Fake Volunteer Ada',
|
||||
email: `ada.fake@${SEED_EMAIL_DOMAIN}`,
|
||||
phone: '712-555-0101',
|
||||
isMinor: 0,
|
||||
guardianName: null,
|
||||
guardianEmail: null,
|
||||
notes: 'Fake note for development.',
|
||||
status: 'confirmed',
|
||||
},
|
||||
{
|
||||
name: 'Fake Volunteer Ben',
|
||||
email: `ben.fake@${SEED_EMAIL_DOMAIN}`,
|
||||
phone: null,
|
||||
isMinor: 1,
|
||||
guardianName: 'Fake Guardian Pat',
|
||||
guardianEmail: `pat.fake@${SEED_EMAIL_DOMAIN}`,
|
||||
phone: '712-555-0102',
|
||||
notes: null,
|
||||
status: 'confirmed',
|
||||
},
|
||||
@@ -142,9 +136,6 @@ function insertFakeSignups(db: Database.Database, shiftId: number, createdAt: st
|
||||
name: 'Fake Volunteer Cam',
|
||||
email: `cam.fake@${SEED_EMAIL_DOMAIN}`,
|
||||
phone: null,
|
||||
isMinor: 0,
|
||||
guardianName: null,
|
||||
guardianEmail: null,
|
||||
notes: null,
|
||||
status: 'cancelled',
|
||||
},
|
||||
@@ -154,7 +145,7 @@ function insertFakeSignups(db: Database.Database, shiftId: number, createdAt: st
|
||||
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 (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, NULL, NULL, 0, NULL, ?, ?, NULL)`,
|
||||
) VALUES (?, ?, ?, ?, ?, 0, NULL, NULL, 1, ?, ?, NULL, NULL, 0, NULL, ?, ?, NULL)`,
|
||||
);
|
||||
return people.map((person) =>
|
||||
insertId(
|
||||
@@ -164,9 +155,6 @@ function insertFakeSignups(db: Database.Database, shiftId: number, createdAt: st
|
||||
person.email,
|
||||
normalizeEmail(person.email),
|
||||
person.phone,
|
||||
person.isMinor,
|
||||
person.guardianName,
|
||||
person.guardianEmail,
|
||||
person.notes,
|
||||
person.status,
|
||||
createdAt,
|
||||
|
||||
@@ -16,9 +16,6 @@ const COLUMNS = [
|
||||
'Email',
|
||||
'Phone',
|
||||
'Group size',
|
||||
'Minor',
|
||||
'Guardian name',
|
||||
'Guardian email',
|
||||
'Notes',
|
||||
'Status',
|
||||
'Attended',
|
||||
@@ -35,9 +32,6 @@ type RosterRecord = {
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
group_size: number;
|
||||
is_minor: number;
|
||||
guardian_name: string | null;
|
||||
guardian_email: string | null;
|
||||
notes: string | null;
|
||||
status: string;
|
||||
attended: number | null;
|
||||
@@ -46,7 +40,6 @@ type RosterRecord = {
|
||||
|
||||
const ROSTER_SQL = `SELECT s.starts_at_utc AS starts_at_utc, s.ends_at_utc AS ends_at_utc, e.tz AS tz, s.role AS role,
|
||||
su.name AS name, su.email AS email, su.phone AS phone, su.group_size AS group_size,
|
||||
su.is_minor AS is_minor, su.guardian_name AS guardian_name, su.guardian_email AS guardian_email,
|
||||
su.notes AS notes, su.status AS status, su.attended AS attended, su.anonymized_at AS anonymized_at
|
||||
FROM signups su
|
||||
JOIN shifts s ON s.id = su.shift_id
|
||||
@@ -136,9 +129,6 @@ function present(row: RosterRecord): string[] {
|
||||
row.email ?? '',
|
||||
row.phone ?? '',
|
||||
String(row.group_size),
|
||||
row.anonymized_at ? '' : row.is_minor === 1 ? 'Yes' : 'No',
|
||||
row.guardian_name ?? '',
|
||||
row.guardian_email ?? '',
|
||||
row.notes ?? '',
|
||||
row.status === 'cancelled' ? 'Cancelled' : 'Confirmed',
|
||||
row.attended === 1 ? 'Attended' : row.attended === 0 ? 'No-show' : '',
|
||||
|
||||
+7
-19
@@ -10,7 +10,6 @@ export type QueuedSignup = {
|
||||
token: string;
|
||||
volunteerName: string;
|
||||
volunteerEmail: string;
|
||||
guardianEmail: string | null;
|
||||
shift: MailShift;
|
||||
mail: MailIdentity;
|
||||
now: string;
|
||||
@@ -19,8 +18,7 @@ export type QueuedSignup = {
|
||||
|
||||
/** Inserts one row per recipient. The same logical message does not get a second row. */
|
||||
export function queueConfirmation(db: Database.Database, input: QueuedSignup): void {
|
||||
queue(db, 'confirmation', input, (audience) => renderConfirmation({
|
||||
audience,
|
||||
queue(db, 'confirmation', input, () => renderConfirmation({
|
||||
volunteerName: input.volunteerName,
|
||||
shift: input.shift,
|
||||
manageUrl: manageUrl(input),
|
||||
@@ -29,8 +27,7 @@ export function queueConfirmation(db: Database.Database, input: QueuedSignup): v
|
||||
}
|
||||
|
||||
export function queueCancellation(db: Database.Database, input: QueuedSignup): void {
|
||||
queue(db, 'cancelled', input, (audience) => renderCancellation({
|
||||
audience,
|
||||
queue(db, 'cancelled', input, () => renderCancellation({
|
||||
volunteerName: input.volunteerName,
|
||||
shift: input.shift,
|
||||
manageUrl: manageUrl(input),
|
||||
@@ -40,9 +37,8 @@ export function queueCancellation(db: Database.Database, input: QueuedSignup): v
|
||||
}
|
||||
|
||||
export function queueChanged(db: Database.Database, input: QueuedSignup, reason: 'edit' | 'move' | 'switch' = 'edit'): void {
|
||||
queue(db, 'changed', input, (audience) => {
|
||||
queue(db, 'changed', input, () => {
|
||||
const letter = {
|
||||
audience,
|
||||
volunteerName: input.volunteerName,
|
||||
shift: input.shift,
|
||||
manageUrl: manageUrl(input),
|
||||
@@ -110,11 +106,9 @@ function queue(
|
||||
db: Database.Database,
|
||||
kind: 'confirmation' | 'cancelled' | 'changed',
|
||||
input: QueuedSignup,
|
||||
render: (audience: 'volunteer' | 'guardian') => { subject: string; text: string; html: string },
|
||||
render: () => { subject: string; text: string; html: string },
|
||||
): void {
|
||||
for (const recipient of recipients(input.volunteerEmail, input.guardianEmail)) {
|
||||
const audience = recipient === input.volunteerEmail ? 'volunteer' : 'guardian';
|
||||
const rendered = render(audience);
|
||||
const rendered = render();
|
||||
db.prepare(
|
||||
`INSERT INTO outbox (
|
||||
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||
@@ -122,11 +116,11 @@ function queue(
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'pending', ?)
|
||||
ON CONFLICT (dedupe_key) DO NOTHING`,
|
||||
).run(
|
||||
`${kind}:v${input.shiftVersion}:${input.signupId}:${recipient}`,
|
||||
`${kind}:v${input.shiftVersion}:${input.signupId}:${input.volunteerEmail}`,
|
||||
input.signupId,
|
||||
input.shiftId,
|
||||
kind,
|
||||
recipient,
|
||||
input.volunteerEmail,
|
||||
rendered.subject,
|
||||
rendered.text,
|
||||
rendered.html,
|
||||
@@ -134,12 +128,6 @@ function queue(
|
||||
input.now,
|
||||
input.now,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function recipients(volunteerEmail: string, guardianEmail: string | null): string[] {
|
||||
if (!guardianEmail || guardianEmail === volunteerEmail) return [volunteerEmail];
|
||||
return [volunteerEmail, guardianEmail];
|
||||
}
|
||||
|
||||
function manageUrl(input: QueuedSignup): string {
|
||||
|
||||
+13
-46
@@ -19,7 +19,6 @@ export type RenderedMail = {
|
||||
* ink and blue from public/brand/tokens.css.
|
||||
*/
|
||||
export function renderConfirmation(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
@@ -27,14 +26,10 @@ export function renderConfirmation(input: {
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = input.audience === 'guardian' ? `${name} is signed up for ${role}` : `You're signed up for ${role}`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `${name} is signed up for ${role}. You are listed as the parent or guardian.`
|
||||
: `You are signed up for ${role}.`;
|
||||
return render({
|
||||
subject,
|
||||
hello,
|
||||
greeting: input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`,
|
||||
subject: `You're signed up for ${role}`,
|
||||
hello: `You are signed up for ${role}.`,
|
||||
greeting: `Hello ${name},`,
|
||||
shift: input.shift,
|
||||
linkLabel: 'Open this signup',
|
||||
linkNote: 'You can cancel or switch this signup from that link. Use the separate link for each signup.',
|
||||
@@ -44,7 +39,6 @@ export function renderConfirmation(input: {
|
||||
}
|
||||
|
||||
export function renderCancellation(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
@@ -53,16 +47,10 @@ export function renderCancellation(input: {
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = input.audience === 'guardian'
|
||||
? `${name}'s signup for ${role} is cancelled`
|
||||
: `Your signup for ${role} is cancelled`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `${name}'s signup for ${role} is cancelled. The spot is open for someone else.`
|
||||
: `Your signup for ${role} is cancelled. The spot is open for someone else.`;
|
||||
return render({
|
||||
subject,
|
||||
hello,
|
||||
greeting: input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`,
|
||||
subject: `Your signup for ${role} is cancelled`,
|
||||
hello: `Your signup for ${role} is cancelled. The spot is open for someone else.`,
|
||||
greeting: `Hello ${name},`,
|
||||
shift: input.shift,
|
||||
linkLabel: 'Open this signup',
|
||||
linkNote: input.linkNote ?? 'That link opens the cancelled signup.',
|
||||
@@ -72,55 +60,37 @@ export function renderCancellation(input: {
|
||||
}
|
||||
|
||||
export function renderChanged(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = input.audience === 'guardian' ? `${name}'s ${role} shift has changed` : `Your ${role} shift has changed`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `The time or place for ${name}'s ${role} shift has changed.`
|
||||
: `The time or place for your ${role} shift has changed.`;
|
||||
return changedLetter(input, subject, hello);
|
||||
return changedLetter(input, `Your ${role} shift has changed`, `The time or place for your ${role} shift has changed.`);
|
||||
}
|
||||
|
||||
export function renderMoved(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = input.audience === 'guardian' ? `${name}'s signup was moved to ${role}` : `Your signup was moved to ${role}`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `A coordinator moved ${name}'s signup to a different shift.`
|
||||
: 'A coordinator moved your signup to a different shift.';
|
||||
return changedLetter(input, subject, hello);
|
||||
return changedLetter(input, `Your signup was moved to ${role}`, 'A coordinator moved your signup to a different shift.');
|
||||
}
|
||||
|
||||
export function renderSwitched(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = input.audience === 'guardian' ? `${name}'s signup was switched to ${role}` : `Your signup was switched to ${role}`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `${name} switched this signup to a different shift.`
|
||||
: 'You switched this signup to a different shift.';
|
||||
return changedLetter(input, subject, hello);
|
||||
return changedLetter(input, `Your signup was switched to ${role}`, 'You switched this signup to a different shift.');
|
||||
}
|
||||
|
||||
function changedLetter(
|
||||
input: { audience: 'volunteer' | 'guardian'; volunteerName: string; shift: MailShift; manageUrl: string; replyTo: string },
|
||||
input: { volunteerName: string; shift: MailShift; manageUrl: string; replyTo: string },
|
||||
subject: string,
|
||||
hello: string,
|
||||
): RenderedMail {
|
||||
@@ -128,7 +98,7 @@ function changedLetter(
|
||||
return render({
|
||||
subject,
|
||||
hello,
|
||||
greeting: input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`,
|
||||
greeting: `Hello ${name},`,
|
||||
shift: input.shift,
|
||||
linkLabel: 'Open this signup',
|
||||
linkNote: 'This link replaces the earlier one. The previous link no longer works.',
|
||||
@@ -138,7 +108,6 @@ function changedLetter(
|
||||
}
|
||||
|
||||
export function renderReminder(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
unsubscribeUrl: string;
|
||||
@@ -147,12 +116,10 @@ export function renderReminder(input: {
|
||||
const role = singleLine(input.shift.role);
|
||||
const name = singleLine(input.volunteerName);
|
||||
const subject = `Reminder: ${role}`;
|
||||
const hello = input.audience === 'guardian'
|
||||
? `${name} is still signed up for ${role}. You are listed as the parent or guardian.`
|
||||
: `You are still signed up for ${role}.`;
|
||||
const hello = `You are still signed up for ${role}.`;
|
||||
const cancelNote = 'To cancel, use the link in your confirmation email.';
|
||||
const stopNote = `To stop reminder emails for this signup, open ${input.unsubscribeUrl}. The pantry reads mail sent to ${input.replyTo}. Stopping reminders does not cancel the signup. Confirmation, change, and cancellation emails still arrive.`;
|
||||
const greeting = input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`;
|
||||
const greeting = `Hello ${name},`;
|
||||
const when = input.shift.whenLabel;
|
||||
const place = input.shift.location.trim();
|
||||
const lines = [
|
||||
|
||||
+3
-37
@@ -353,15 +353,6 @@ export function ManagePage(props: {
|
||||
<dd>{signup.phone}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
{signup.isMinor ? (
|
||||
<div>
|
||||
<dt>Guardian</dt>
|
||||
<dd>
|
||||
{signup.guardianName}
|
||||
{signup.guardianEmail ? ` (${signup.guardianEmail})` : ''}
|
||||
</dd>
|
||||
</div>
|
||||
) : null}
|
||||
{signup.notes ? (
|
||||
<div>
|
||||
<dt>Notes</dt>
|
||||
@@ -713,7 +704,7 @@ function SignupForm(props: { config: AppConfig; shiftId: number; form: SignupFor
|
||||
return (
|
||||
<form class="signup-form" method="post" action={appPath(props.config, `/s/${props.shiftId}`)}>
|
||||
<h2>Sign up</h2>
|
||||
<p>Each signup is for one person and takes one spot. Another person can use the same email address. If you are under 18, add a parent or guardian.</p>
|
||||
<p>Each signup is for one person and takes one spot. Another person can use the same email address.</p>
|
||||
<noscript>
|
||||
<p class="error">Signing up needs JavaScript for the abuse check. The pantry has not published a contact method for help with signup.</p>
|
||||
</noscript>
|
||||
@@ -761,13 +752,13 @@ function SignupForm(props: { config: AppConfig; shiftId: number; form: SignupFor
|
||||
<Field id="signup-email" label="Email" name="email" type="email" value={form.values.email} error={errors.email} autoComplete="email" />
|
||||
<Field
|
||||
id="signup-phone"
|
||||
label="Phone (optional)"
|
||||
label="Phone"
|
||||
name="phone"
|
||||
type="tel"
|
||||
value={form.values.phone}
|
||||
error={errors.phone}
|
||||
autoComplete="tel"
|
||||
hint="We will not text you"
|
||||
required
|
||||
/>
|
||||
<label for="signup-notes">
|
||||
Notes (optional)
|
||||
@@ -780,31 +771,6 @@ function SignupForm(props: { config: AppConfig; shiftId: number; form: SignupFor
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
<label class="check" for="signup-under-18">
|
||||
<input id="signup-under-18" name="under18" type="checkbox" value="yes" data-under-18="" checked={form.values.under18 ? true : undefined} />
|
||||
I am under 18
|
||||
</label>
|
||||
<fieldset data-guardian="">
|
||||
<legend>Parent or guardian</legend>
|
||||
<Field
|
||||
id="signup-guardianName"
|
||||
label="Guardian name"
|
||||
name="guardianName"
|
||||
type="text"
|
||||
value={form.values.guardianName}
|
||||
error={errors.guardianName}
|
||||
autoComplete="name"
|
||||
/>
|
||||
<Field
|
||||
id="signup-guardianEmail"
|
||||
label="Guardian email"
|
||||
name="guardianEmail"
|
||||
type="email"
|
||||
value={form.values.guardianEmail}
|
||||
error={errors.guardianEmail}
|
||||
autoComplete="email"
|
||||
/>
|
||||
</fieldset>
|
||||
<div class="cf-turnstile" data-sitekey={form.siteKey} data-action="signup" />
|
||||
<p id="signup-turnstile-hint">This check confirms the signup came from a browser.</p>
|
||||
<button type="submit">Sign up</button>
|
||||
|
||||
+2
-23
@@ -8,8 +8,6 @@ import { formatUtc } from './time.js';
|
||||
export const SIGNUP_IP_LIMIT = 5;
|
||||
export const SIGNUP_IP_WINDOW_MS = 10 * 60 * 1000;
|
||||
export const SIGNUP_EMAIL_LIMIT = 3;
|
||||
/** A guardian can have several children signed up, so this allowance is a little wider. */
|
||||
export const SIGNUP_GUARDIAN_LIMIT = 5;
|
||||
export const SWITCH_IP_LIMIT = 10;
|
||||
export const SWITCH_RECIPIENT_LIMIT = 5;
|
||||
export const MANAGE_TOKEN_LIMIT = 20;
|
||||
@@ -30,8 +28,8 @@ export type RateDecision = { limited: false } | { limited: true; retryAfter: num
|
||||
|
||||
/**
|
||||
* Counts validated public switch attempts, not the rotating signup id or token.
|
||||
* Both recipient roles share one daily allowance. Check and charge every bucket
|
||||
* atomically so a blocked recipient cannot consume another person's allowance.
|
||||
* Check and charge every bucket atomically so a blocked recipient cannot consume
|
||||
* another person's allowance.
|
||||
*/
|
||||
export function recordSwitchAttempt(
|
||||
db: Database.Database,
|
||||
@@ -144,25 +142,6 @@ export function recordSignupEmail(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts signups that mail a guardian address. Without it, someone could rotate
|
||||
* volunteer addresses and keep sending mail to one guardian.
|
||||
*/
|
||||
export function recordSignupGuardian(
|
||||
db: Database.Database,
|
||||
secret: string,
|
||||
now: string,
|
||||
timeZone: string,
|
||||
guardianEmailNorm: string,
|
||||
): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'signup-guardian',
|
||||
id: guardianEmailNorm,
|
||||
limit: SIGNUP_GUARDIAN_LIMIT,
|
||||
window: dayWindow(now, timeZone),
|
||||
});
|
||||
}
|
||||
|
||||
function record(
|
||||
db: Database.Database,
|
||||
secret: string,
|
||||
|
||||
+5
-13
@@ -14,7 +14,6 @@ type DueSignup = {
|
||||
id: number;
|
||||
name: string;
|
||||
email_norm: string;
|
||||
guardian_email: string | null;
|
||||
version: number;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
@@ -38,7 +37,7 @@ export function queueDueReminders(db: Database.Database, mail: MailIdentity, sec
|
||||
const activeMail = { ...mail, replyTo: readReplyTo(db, mail.replyTo) };
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT su.id AS id, su.name AS name, su.email_norm AS email_norm, su.guardian_email AS guardian_email,
|
||||
`SELECT su.id AS id, su.name AS name, su.email_norm AS email_norm,
|
||||
su.shift_id AS shift_id, s.version AS version, s.starts_at_utc AS starts_at_utc,
|
||||
s.ends_at_utc AS ends_at_utc, s.role AS role,
|
||||
e.title AS title, e.location AS location, e.tz AS tz
|
||||
@@ -129,7 +128,7 @@ function insertReminder(
|
||||
): boolean {
|
||||
const unsubscribeUrl = absoluteUrl(mail, `/u/${issueReminderOffToken(secret, row.id)}`);
|
||||
const headers = reminderHeaders(mail, unsubscribeUrl);
|
||||
const volunteerId = insertOutbox(db, row, kind, row.email_norm, 'volunteer', mail, headers, unsubscribeUrl, now, mode);
|
||||
const volunteerId = insertOutbox(db, row, kind, mail, headers, unsubscribeUrl, now, mode);
|
||||
if (volunteerId === null) return false;
|
||||
const saved = db
|
||||
.prepare(
|
||||
@@ -138,19 +137,13 @@ function insertReminder(
|
||||
ON CONFLICT (signup_id, kind, shift_version) DO NOTHING`,
|
||||
)
|
||||
.run(row.id, kind, row.version, volunteerId, now);
|
||||
if (saved.changes !== 1) return false;
|
||||
if (mode === 'pending' && row.guardian_email && row.guardian_email !== row.email_norm) {
|
||||
insertOutbox(db, row, kind, row.guardian_email, 'guardian', mail, headers, unsubscribeUrl, now, 'pending');
|
||||
}
|
||||
return true;
|
||||
return saved.changes === 1;
|
||||
}
|
||||
|
||||
function insertOutbox(
|
||||
db: Database.Database,
|
||||
row: DueSignup,
|
||||
kind: string,
|
||||
recipient: string,
|
||||
audience: 'volunteer' | 'guardian',
|
||||
mail: MailIdentity,
|
||||
headers: Record<string, string>,
|
||||
unsubscribeUrl: string,
|
||||
@@ -159,7 +152,6 @@ function insertOutbox(
|
||||
): number | null {
|
||||
const rendered = mode === 'pending'
|
||||
? renderReminder({
|
||||
audience,
|
||||
volunteerName: row.name,
|
||||
shift: shiftFacts(row),
|
||||
unsubscribeUrl,
|
||||
@@ -175,10 +167,10 @@ function insertOutbox(
|
||||
ON CONFLICT (dedupe_key) DO NOTHING`,
|
||||
)
|
||||
.run(
|
||||
`reminder:v${row.version}:${row.id}:${kind}:${recipient}`,
|
||||
`reminder:v${row.version}:${row.id}:${kind}:${row.email_norm}`,
|
||||
row.id,
|
||||
row.shift_id,
|
||||
recipient,
|
||||
row.email_norm,
|
||||
rendered.subject,
|
||||
rendered.text,
|
||||
rendered.html,
|
||||
|
||||
+7
-43
@@ -13,25 +13,18 @@ export type SignupValues = {
|
||||
email: string;
|
||||
phone: string;
|
||||
notes: string;
|
||||
under18: boolean;
|
||||
guardianName: string;
|
||||
guardianEmail: string;
|
||||
};
|
||||
|
||||
export type SignupErrors = Partial<
|
||||
Record<'name' | 'firstName' | 'lastName' | 'email' | 'phone' | 'notes' | 'guardianName' | 'guardianEmail' | 'form', string>
|
||||
Record<'name' | 'firstName' | 'lastName' | 'email' | 'phone' | 'notes' | 'form', string>
|
||||
>;
|
||||
|
||||
export type SignupDraft = {
|
||||
name: string;
|
||||
email: string;
|
||||
emailNorm: string;
|
||||
phone: string | null;
|
||||
phone: string;
|
||||
notes: string | null;
|
||||
isMinor: boolean;
|
||||
guardianName: string | null;
|
||||
guardianEmail: string | null;
|
||||
guardianEmailNorm: string | null;
|
||||
};
|
||||
|
||||
export const EMPTY_SIGNUP: SignupValues = {
|
||||
@@ -41,9 +34,6 @@ export const EMPTY_SIGNUP: SignupValues = {
|
||||
email: '',
|
||||
phone: '',
|
||||
notes: '',
|
||||
under18: false,
|
||||
guardianName: '',
|
||||
guardianEmail: '',
|
||||
};
|
||||
|
||||
const controlChars = /[\u0000-\u001F\u007F]/;
|
||||
@@ -69,9 +59,6 @@ export function parseSignupForm(
|
||||
email: z.string(),
|
||||
phone: z.string(),
|
||||
notes: z.string(),
|
||||
under18: z.boolean(),
|
||||
guardianName: z.string(),
|
||||
guardianEmail: z.string(),
|
||||
})
|
||||
.safeParse(input);
|
||||
if (!parsed.success) return { ok: false, errors: { form: 'Check the signup fields and try again.' } };
|
||||
@@ -103,47 +90,24 @@ export function parseSignupForm(
|
||||
|
||||
const phoneRaw = parsed.data.phone.normalize('NFC').trim();
|
||||
const phone = phoneRaw.length === 0 ? '' : formatPhone(phoneRaw);
|
||||
if (phoneRaw.length > PHONE_MAX || phone.length > PHONE_MAX) errors.phone = `Use ${PHONE_MAX} characters or fewer.`;
|
||||
if (phoneRaw.length === 0 || phone.length === 0) {
|
||||
errors.phone = voice === 'coordinator' ? 'Enter their phone number.' : 'Enter your phone number.';
|
||||
} else if (phoneRaw.length > PHONE_MAX || phone.length > PHONE_MAX) errors.phone = `Use ${PHONE_MAX} characters or fewer.`;
|
||||
else if (controlChars.test(phoneRaw)) errors.phone = 'Enter a phone number without line breaks.';
|
||||
|
||||
const notes = parsed.data.notes.normalize('NFC').trim();
|
||||
if (notes.length > NOTES_MAX) errors.notes = `Use ${NOTES_MAX} characters or fewer.`;
|
||||
else if (controlChars.test(notes)) errors.notes = 'Enter notes without control characters.';
|
||||
|
||||
let guardianName: string | null = null;
|
||||
let guardianEmail: string | null = null;
|
||||
let guardianEmailNorm: string | null = null;
|
||||
if (parsed.data.under18) {
|
||||
const guardianRaw = parsed.data.guardianName.normalize('NFC').trim();
|
||||
guardianName = capitalizeName(guardianRaw);
|
||||
if (guardianRaw.length === 0 || guardianName.length === 0) errors.guardianName = 'Enter the guardian name.';
|
||||
else if (guardianRaw.length > NAME_MAX || guardianName.length > NAME_MAX) errors.guardianName = `Use ${NAME_MAX} characters or fewer.`;
|
||||
else if (controlChars.test(guardianRaw)) errors.guardianName = 'Enter the guardian name without line breaks.';
|
||||
if (parsed.data.guardianEmail.trim() === '') {
|
||||
errors.guardianEmail = 'Enter the guardian email.';
|
||||
} else {
|
||||
try {
|
||||
guardianEmailNorm = normalizeEmail(parsed.data.guardianEmail);
|
||||
guardianEmail = guardianEmailNorm;
|
||||
} catch (err) {
|
||||
errors.guardianEmail = err instanceof EmailAddressError ? err.message : 'Enter the guardian email.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(errors).length > 0 || emailNorm.length === 0) return { ok: false, errors };
|
||||
if (Object.keys(errors).length > 0 || emailNorm.length === 0 || phone.length === 0) return { ok: false, errors };
|
||||
return {
|
||||
ok: true,
|
||||
draft: {
|
||||
name,
|
||||
email: emailNorm,
|
||||
emailNorm,
|
||||
phone: phone.length === 0 ? null : phone,
|
||||
phone,
|
||||
notes: notes.length === 0 ? null : notes,
|
||||
isMinor: parsed.data.under18,
|
||||
guardianName: parsed.data.under18 ? guardianName : null,
|
||||
guardianEmail: parsed.data.under18 ? guardianEmail : null,
|
||||
guardianEmailNorm: parsed.data.under18 ? guardianEmailNorm : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
+2
-17
@@ -24,7 +24,7 @@ import {
|
||||
type SignupFormView,
|
||||
type SwitchForm,
|
||||
} from './pages.js';
|
||||
import { recordInvalidManageToken, recordSignupEmail, recordSignupGuardian, recordSignupIp, recordSwitchAttempt } from './rate-limit.js';
|
||||
import { recordInvalidManageToken, recordSignupEmail, recordSignupIp, recordSwitchAttempt } from './rate-limit.js';
|
||||
import { getPublicShift, type PublicShift } from './schedule.js';
|
||||
import { EMPTY_SIGNUP, parseSignupForm, type SignupErrors, type SignupValues } from './signup-form.js';
|
||||
import type { MailIdentity } from './mail/types.js';
|
||||
@@ -154,13 +154,6 @@ async function submitSignup(c: Context, services: SignupServices): Promise<Respo
|
||||
if (emailLimit.limited) {
|
||||
return shiftResponse(c, services, shift, 429, formFor(services, shift, values, {}, textField(body, 'form_token')), TOO_MANY, emailLimit.retryAfter);
|
||||
}
|
||||
const guardianEmail = parsed.draft.guardianEmailNorm;
|
||||
if (guardianEmail && guardianEmail !== parsed.draft.emailNorm) {
|
||||
const guardianLimit = recordSignupGuardian(db, config.sessionSecret, now, config.defaultTimeZone, guardianEmail);
|
||||
if (guardianLimit.limited) {
|
||||
return shiftResponse(c, services, shift, 429, formFor(services, shift, values, {}, textField(body, 'form_token')), TOO_MANY, guardianLimit.retryAfter);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const reserved = reserveSignup(db, {
|
||||
shiftId: shift.id,
|
||||
@@ -168,9 +161,6 @@ async function submitSignup(c: Context, services: SignupServices): Promise<Respo
|
||||
email: parsed.draft.emailNorm,
|
||||
phone: parsed.draft.phone,
|
||||
notes: parsed.draft.notes,
|
||||
isMinor: parsed.draft.isMinor,
|
||||
guardianName: parsed.draft.guardianName,
|
||||
guardianEmail: parsed.draft.guardianEmail,
|
||||
operationId: tokenResult.claims.operationId,
|
||||
now,
|
||||
mail: mailIdentity(db, config),
|
||||
@@ -284,9 +274,6 @@ function valuesFrom(body: Record<string, unknown>): SignupValues {
|
||||
email: textField(body, 'email'),
|
||||
phone: textField(body, 'phone'),
|
||||
notes: textField(body, 'notes'),
|
||||
under18: textField(body, 'under18') === 'yes',
|
||||
guardianName: textField(body, 'guardianName'),
|
||||
guardianEmail: textField(body, 'guardianEmail'),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -381,10 +368,8 @@ async function submitSwitch(c: Context, services: SignupServices): Promise<Respo
|
||||
if (!formToken.ok) return showManage(c, services, token, 400, SWITCH_STALE);
|
||||
try {
|
||||
const ip = clientAddress(services.config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for'));
|
||||
const recipients = [signup.emailNorm];
|
||||
if (signup.isMinor && signup.guardianEmail) recipients.push(signup.guardianEmail);
|
||||
const limit = recordSwitchAttempt(
|
||||
services.db, services.config.sessionSecret, services.now(), services.config.defaultTimeZone, ip, recipients,
|
||||
services.db, services.config.sessionSecret, services.now(), services.config.defaultTimeZone, ip, [signup.emailNorm],
|
||||
);
|
||||
if (limit.limited) {
|
||||
c.header('Retry-After', String(limit.retryAfter));
|
||||
|
||||
+4
-22
@@ -15,9 +15,6 @@ export type ReserveInput = {
|
||||
email: string;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
isMinor: boolean;
|
||||
guardianName: string | null;
|
||||
guardianEmail: string | null;
|
||||
operationId: string;
|
||||
now: string;
|
||||
mail: MailIdentity;
|
||||
@@ -36,9 +33,6 @@ export type ManageView = {
|
||||
email: string;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
isMinor: boolean;
|
||||
guardianName: string | null;
|
||||
guardianEmail: string | null;
|
||||
status: 'confirmed' | 'cancelled';
|
||||
remindersOff: boolean;
|
||||
emailNorm: string;
|
||||
@@ -109,9 +103,6 @@ export function readManageSignup(db: Database.Database, token: string, now: stri
|
||||
su.email AS email,
|
||||
su.phone AS phone,
|
||||
su.notes AS notes,
|
||||
su.is_minor AS is_minor,
|
||||
su.guardian_name AS guardian_name,
|
||||
su.guardian_email AS guardian_email,
|
||||
su.status AS status,
|
||||
su.reminders_off AS reminders_off,
|
||||
su.email_norm AS email_norm,
|
||||
@@ -138,9 +129,6 @@ export function readManageSignup(db: Database.Database, token: string, now: stri
|
||||
email: row.email,
|
||||
phone: row.phone,
|
||||
notes: row.notes,
|
||||
isMinor: row.is_minor === 1,
|
||||
guardianName: row.guardian_name,
|
||||
guardianEmail: row.guardian_email,
|
||||
status: row.status,
|
||||
remindersOff: row.reminders_off === 1,
|
||||
emailNorm: row.email_norm,
|
||||
@@ -214,9 +202,9 @@ function placeReservation(db: Database.Database, input: ReserveInput, emailNorm:
|
||||
emailNorm,
|
||||
emailNorm,
|
||||
input.phone,
|
||||
input.isMinor ? 1 : 0,
|
||||
input.isMinor ? input.guardianName : null,
|
||||
input.isMinor ? input.guardianEmail : null,
|
||||
0,
|
||||
null,
|
||||
null,
|
||||
input.notes,
|
||||
sha256(manageToken),
|
||||
expiresAt,
|
||||
@@ -232,7 +220,6 @@ function placeReservation(db: Database.Database, input: ReserveInput, emailNorm:
|
||||
token: manageToken,
|
||||
volunteerName: input.name,
|
||||
volunteerEmail: emailNorm,
|
||||
guardianEmail: input.isMinor ? input.guardianEmail : null,
|
||||
shift: shiftFacts(shift).facts,
|
||||
mail: input.mail,
|
||||
now: input.now,
|
||||
@@ -282,7 +269,7 @@ function cancelConfirmed(db: Database.Database, hash: string, token: string, now
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT su.id AS id, su.status AS status, su.token_expires_at AS token_expires_at, su.anonymized_at AS anonymized_at,
|
||||
su.name AS name, su.email_norm AS email_norm, su.guardian_email AS guardian_email, su.shift_id AS shift_id
|
||||
su.name AS name, su.email_norm AS email_norm, su.shift_id AS shift_id
|
||||
FROM signups su
|
||||
WHERE su.manage_token_hash = ?`,
|
||||
)
|
||||
@@ -294,7 +281,6 @@ function cancelConfirmed(db: Database.Database, hash: string, token: string, now
|
||||
anonymized_at: string | null;
|
||||
name: string | null;
|
||||
email_norm: string | null;
|
||||
guardian_email: string | null;
|
||||
shift_id: number;
|
||||
}
|
||||
| undefined;
|
||||
@@ -322,7 +308,6 @@ function cancelConfirmed(db: Database.Database, hash: string, token: string, now
|
||||
token,
|
||||
volunteerName: row.name,
|
||||
volunteerEmail: row.email_norm,
|
||||
guardianEmail: row.guardian_email,
|
||||
shift: shift.facts,
|
||||
mail,
|
||||
now,
|
||||
@@ -405,9 +390,6 @@ type ManageRow = {
|
||||
email_norm: string | null;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
is_minor: number;
|
||||
guardian_name: string | null;
|
||||
guardian_email: string | null;
|
||||
status: string;
|
||||
reminders_off: number;
|
||||
token_expires_at: string | null;
|
||||
|
||||
+13
-32
@@ -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 } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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,
|
||||
|
||||
@@ -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',
|
||||
});
|
||||
|
||||
@@ -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');
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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: {
|
||||
|
||||
@@ -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');
|
||||
|
||||
Reference in new issue
Block a user