@@ -445,32 +437,7 @@ export function ManagePage(props: {
) : null}
) : null}
-
{party ? (
@@ -595,28 +562,172 @@ export function SwitchAlreadyPage() {
);
}
-export function ReminderOffPage(props: { config: AppConfig; token: string; replyTo: string; off: boolean; error?: string }) {
+export function ReminderOffPage(props: { config: AppConfig; token: string; signup: ReminderPageSignup; error?: string }) {
+ const signup = props.signup;
+ const cancelled = signup.status !== 'confirmed';
+ const canCancel = !cancelled && !signup.ended;
return (
- <>
-
Reminder emails
+
+
{props.error ? (
{props.error}
) : null}
- {props.off ? (
- Reminder emails for this signup are off. The signup stays. Confirmation, change, and cancellation emails still arrive.
- ) : (
-
- )}
- >
+
+
+ {cancelled ? null : (
+
+
+ {canCancel ? (
+
+ ) : null}
+
+
+
+ )}
+
+ {cancelled ? {cancelledSignupCopy(signup.groupSize)}
: null}
+
);
}
+export function ReminderCancelPage(props: {
+ config: AppConfig;
+ token: string;
+ signup: ReminderPageSignup;
+ cancelToken: string;
+ error?: string;
+}) {
+ return (
+
+
+ {props.error ? (
+
+ {props.error}
+
+ ) : null}
+
+
+ );
+}
+
+type SignupIdentity = {
+ name: string;
+ email: string;
+ phone: string | null;
+ notes: string | null;
+ groupSize: number;
+ status: 'confirmed' | 'cancelled';
+ role: string;
+ location: string;
+ eventTitle: string;
+ when: ZonedClock;
+ ended: boolean;
+};
+
+function SignupIntro(props: { signup: SignupIdentity }) {
+ const signup = props.signup;
+ const cancelled = signup.status !== 'confirmed';
+ return (
+
+ Your signup
+ {cancelled ? 'Cancelled' : 'Confirmed'}
+ {signup.eventTitle}
+ {signup.role}
+
+ {signup.when.dateLabel} {signup.when.timeLabel} {signup.when.abbreviation}
+
+ {signup.location ? {signup.location}
: null}
+ {!cancelled && signup.ended ? This shift has ended.
: null}
+
+ );
+}
+
+function SignupFacts(props: { signup: SignupIdentity }) {
+ const signup = props.signup;
+ return (
+
+
+
Name
+ {signup.name}
+
+
+
People
+ {signup.groupSize}
+
+
+
Email
+ {signup.email}
+
+ {signup.phone ? (
+
+
Phone
+ {signup.phone}
+
+ ) : null}
+ {signup.notes ? (
+
+
Notes
+ {signup.notes}
+
+ ) : null}
+
+ );
+}
+
+function ReminderPreference(props: { config: AppConfig; token: string; off: boolean }) {
+ if (props.off) {
+ return (
+
Reminder emails are off. This signup stays.
+ );
+ }
+ return (
+
+ );
+}
+
+function openSpots(groupSize: number): string {
+ return groupSize > 1 ? `Opens these ${groupSize} spots for someone else.` : 'Opens the spot for someone else.';
+}
+
+function cancelEffect(groupSize: number): string {
+ return groupSize > 1
+ ? `Cancel this signup to open these ${groupSize} spots for someone else. A cancellation email is queued when you cancel.`
+ : 'Cancel this signup to open the spot for someone else. A cancellation email is queued when you cancel.';
+}
+
+function cancelledSignupCopy(groupSize: number): string {
+ return groupSize > 1
+ ? `This signup is cancelled. The ${groupSize} spots it held are open for someone else. A cancellation email is queued.`
+ : 'This signup is cancelled. The spot is open for someone else. A cancellation email is queued.';
+}
+
export function NotFoundPage() {
return (
<>
diff --git a/src/reminder-http.tsx b/src/reminder-http.tsx
index 04df153..e35dfd2 100644
--- a/src/reminder-http.tsx
+++ b/src/reminder-http.tsx
@@ -1,79 +1,164 @@
import { getConnInfo } from '@hono/node-server/conninfo';
import type { Context, Hono } from 'hono';
import type { Child } from 'hono/jsx';
+import type Database from 'better-sqlite3';
import { readSession } from './auth/session.js';
+import { issueReminderCancelToken, reminderCancelTokenMatches } from './cancel-token.js';
import { clientAddress } from './client-ip.js';
import type { AppConfig } from './config.js';
-import { Layout, NotFoundPage, ReminderOffPage, WaitPage } from './pages.js';
+import type { MailIdentity } from './mail/types.js';
+import { originAllowed } from './origin.js';
+import { Layout, NotFoundPage, ReminderCancelPage, ReminderOffPage, WaitPage } from './pages.js';
import { recordInvalidUnsubscribe } from './rate-limit.js';
-import { disableReminders, readReminderOffToken } from './reminders.js';
+import { disableReminders, readReminderOffToken, readReminderSignup, type ReminderPageSignup } from './reminders.js';
import { readReplyTo } from './settings.js';
+import { cancelSignupById } from './signup.js';
import { isBusy } from './sqlite-error.js';
-import { appPath } from './url.js';
-import type Database from 'better-sqlite3';
+import { absoluteUrl, appPath } from './url.js';
-export function registerReminderOff(
- app: Hono,
- services: {
- config: AppConfig;
- db: Database.Database;
- now: () => string;
- clientIp?: (c: Context) => string | null;
- },
-): void {
- app.get(appPath(services.config, '/u/:token'), (c) => showReminderOff(c, services));
- app.post(appPath(services.config, '/u/:token'), (c) => submitReminderOff(c, services));
+const CANCEL_ORIGIN = 'The cancellation could not be sent from this page.';
+const CANCEL_REJECTED = 'The cancellation could not be confirmed. Please try again.';
+const CANCEL_UNAVAILABLE = 'The cancellation could not be saved. Please try again in a little while.';
+
+type ReminderServices = {
+ config: AppConfig;
+ db: Database.Database;
+ now: () => string;
+ clientIp?: (c: Context) => string | null;
+};
+
+/**
+ * The reminder link opens one signup.
+ * POST /u/:token only turns reminders off, because mail clients one-click unsubscribe to that address.
+ * Cancelling is a separate confirmed POST.
+ */
+export function registerReminderOff(app: Hono, services: ReminderServices): void {
+ const unsubscribe = appPath(services.config, '/u/:token');
+ const cancel = appPath(services.config, '/u/:token/cancel');
+ app.get(cancel, (c) => showCancel(c, services));
+ app.post(cancel, (c) => submitCancel(c, services));
+ app.get(unsubscribe, (c) => showReminderOff(c, services));
+ app.post(unsubscribe, (c) => submitReminderOff(c, services));
}
-function showReminderOff(
- c: Context,
- services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null },
-) {
- const signupId = readReminderOffToken(services.config.sessionSecret, c.req.param('token') ?? '');
- if (signupId === null || !reminderSignup(services.db, signupId)) return unavailable(c, services);
- const off = remindersOff(services.db, signupId);
- return page(c, services,
);
+function showReminderOff(c: Context, services: ReminderServices) {
+ const loaded = loadSignup(c, services);
+ if (!loaded) return unavailable(c, services);
+ return page(c, services, 'Your signup · Hope Volunteer',
);
}
-async function submitReminderOff(
- c: Context,
- services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null },
-): Promise
{
- const token = c.req.param('token') ?? '';
- const signupId = readReminderOffToken(services.config.sessionSecret, token);
- if (signupId === null || !reminderSignup(services.db, signupId)) return unavailable(c, services);
+async function submitReminderOff(c: Context, services: ReminderServices): Promise {
+ const loaded = loadSignup(c, services);
+ if (!loaded) return unavailable(c, services);
try {
- const result = disableReminders(services.db, signupId, services.now());
+ const result = disableReminders(services.db, loaded.signupId, services.now());
if (!result.ok) return unavailable(c, services);
} catch (err) {
if (!isBusy(err)) throw err;
console.error('Reminder opt-out could not lock the database.');
- return page(c, services, , 503);
+ return page(
+ c,
+ services,
+ 'Your signup · Hope Volunteer',
+ ,
+ 503,
+ );
}
- return page(c, services, );
+ const signup = readReminderSignup(services.db, loaded.signupId, services.now()) ?? { ...loaded.signup, remindersOff: true };
+ return page(c, services, 'Your signup · Hope Volunteer', );
}
-function reminderSignup(db: Database.Database, signupId: number): boolean {
- const row = db.prepare('SELECT id FROM signups WHERE id = ? AND anonymized_at IS NULL').get(signupId);
- return Boolean(row);
+function showCancel(c: Context, services: ReminderServices) {
+ const loaded = loadSignup(c, services);
+ if (!loaded) return unavailable(c, services);
+ if (!canCancel(loaded.signup)) {
+ c.header('Cache-Control', 'no-store');
+ return c.redirect(appPath(services.config, `/u/${loaded.token}`), 303);
+ }
+ return confirmPage(c, services, loaded.token, loaded.signup);
}
-function remindersOff(db: Database.Database, signupId: number): boolean {
- const row = db.prepare('SELECT reminders_off AS reminders_off FROM signups WHERE id = ?').get(signupId) as { reminders_off: number } | undefined;
- return row?.reminders_off === 1;
+async function submitCancel(c: Context, services: ReminderServices): Promise {
+ const loaded = loadSignup(c, services);
+ if (!loaded) return unavailable(c, services);
+ if (loaded.signup.status === 'cancelled') {
+ c.header('Cache-Control', 'no-store');
+ return c.redirect(appPath(services.config, `/u/${loaded.token}`), 303);
+ }
+ if (!canCancel(loaded.signup)) {
+ return page(c, services, 'Your signup · Hope Volunteer', , 400);
+ }
+ if (!originAllowed(c, services.config.baseUrl)) return confirmPage(c, services, loaded.token, loaded.signup, 403, CANCEL_ORIGIN);
+ const body = await c.req.parseBody();
+ if (!reminderCancelTokenMatches(services.config.sessionSecret, loaded.token, textField(body, 'cancel_token'))) {
+ return confirmPage(c, services, loaded.token, loaded.signup, 400, CANCEL_REJECTED);
+ }
+ try {
+ const result = cancelSignupById(
+ services.db,
+ loaded.signupId,
+ services.now(),
+ mailIdentity(services),
+ absoluteUrl(services.config, `/u/${loaded.token}`),
+ );
+ if (!result.ok && result.reason === 'ended') {
+ const signup = readReminderSignup(services.db, loaded.signupId, services.now()) ?? loaded.signup;
+ return page(c, services, 'Your signup · Hope Volunteer', , 400);
+ }
+ if (!result.ok) return unavailable(c, services);
+ } catch (err) {
+ if (!isBusy(err)) throw err;
+ console.error('Cancellation could not lock the database.');
+ return confirmPage(c, services, loaded.token, loaded.signup, 503, CANCEL_UNAVAILABLE);
+ }
+ c.header('Cache-Control', 'no-store');
+ return c.redirect(appPath(services.config, `/u/${loaded.token}`), 303);
}
-function unavailable(
+function loadSignup(c: Context, services: ReminderServices): { token: string; signupId: number; signup: ReminderPageSignup } | null {
+ const token = c.req.param('token') ?? '';
+ const signupId = readReminderOffToken(services.config.sessionSecret, token);
+ if (signupId === null) return null;
+ const signup = readReminderSignup(services.db, signupId, services.now());
+ if (!signup) return null;
+ return { token, signupId, signup };
+}
+
+function canCancel(signup: ReminderPageSignup): boolean {
+ return signup.status === 'confirmed' && !signup.ended;
+}
+
+function confirmPage(
c: Context,
- services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null },
+ services: ReminderServices,
+ token: string,
+ signup: ReminderPageSignup,
+ status: 200 | 400 | 403 | 503 = 200,
+ error?: string,
) {
+ return page(
+ c,
+ services,
+ 'Cancel this signup · Hope Volunteer',
+ ,
+ status,
+ );
+}
+
+function unavailable(c: Context, services: ReminderServices) {
const ip = clientAddress(services.config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for'));
const limit = recordInvalidUnsubscribe(services.db, services.config.sessionSecret, services.now(), ip);
if (limit.limited) {
c.header('Retry-After', String(limit.retryAfter));
- return page(c, services, , 429);
+ return page(c, services, 'Please wait · Hope Volunteer', , 429);
}
- return page(c, services, , 404);
+ return page(c, services, 'That page is not available · Hope Volunteer', , 404);
}
function peerAddress(c: Context, override?: (c: Context) => string | null): string | null {
@@ -85,18 +170,31 @@ function peerAddress(c: Context, override?: (c: Context) => string | null): stri
}
}
-function page(
- c: Context,
- services: { config: AppConfig; db: Database.Database; now: () => string },
- body: Child,
- status: 200 | 404 | 429 | 503 = 200,
-) {
+function page(c: Context, services: ReminderServices, title: string, body: Child, status: 200 | 400 | 403 | 404 | 429 | 503 = 200) {
c.header('Cache-Control', 'no-store');
const account = readSession(services.db, c.req.header('cookie'), services.now());
return c.html(
-
+
{body}
,
status,
);
}
+
+function mailIdentity(services: ReminderServices): MailIdentity {
+ return {
+ baseUrl: services.config.baseUrl,
+ basePath: services.config.basePath,
+ from: services.config.mail.from,
+ replyTo: replyTo(services),
+ };
+}
+
+function replyTo(services: ReminderServices): string {
+ return readReplyTo(services.db, services.config.mail.replyTo);
+}
+
+function textField(body: Record, name: string): string {
+ const value = body[name];
+ return typeof value === 'string' ? value : '';
+}
diff --git a/src/reminders.ts b/src/reminders.ts
index 1e5eb7b..71c2db8 100644
--- a/src/reminders.ts
+++ b/src/reminders.ts
@@ -5,7 +5,7 @@ import { cancelPendingReminders } from './mail/queue.js';
import { renderReminder } from './mail/templates.js';
import type { MailIdentity } from './mail/types.js';
import { readReminderOffsets, readReplyTo } from './settings.js';
-import { formatInstantInZone } from './time.js';
+import { formatInstantInZone, type ZonedClock } from './time.js';
import { absoluteUrl } from './url.js';
export type ReminderPass = { queued: number; suppressed: number };
@@ -132,6 +132,69 @@ export function issueReminderOffToken(secret: string, signupId: number): string
return `${id}.${mac}`;
}
+export type ReminderPageSignup = {
+ name: string;
+ email: string;
+ phone: string | null;
+ notes: string | null;
+ role: string;
+ eventTitle: string;
+ location: string;
+ when: ZonedClock;
+ groupSize: number;
+ status: 'confirmed' | 'cancelled';
+ ended: boolean;
+ remindersOff: boolean;
+};
+
+/** The signup a reminder link may show. An anonymized row, or a row without a name and email, is omitted. */
+export function readReminderSignup(db: Database.Database, signupId: number, now: string): ReminderPageSignup | null {
+ const row = db
+ .prepare(
+ `SELECT su.name AS name, su.email AS email, su.phone AS phone, su.notes AS notes,
+ su.group_size AS group_size, su.status AS status, su.reminders_off AS reminders_off,
+ s.role AS role, s.starts_at_utc AS starts_at_utc, s.ends_at_utc AS ends_at_utc,
+ e.title AS title, e.location AS location, e.tz AS tz
+ FROM signups su
+ JOIN shifts s ON s.id = su.shift_id
+ JOIN events e ON e.id = s.event_id
+ WHERE su.id = ? AND su.anonymized_at IS NULL`,
+ )
+ .get(signupId) as
+ | {
+ name: string | null;
+ email: string | null;
+ phone: string | null;
+ notes: string | null;
+ group_size: number;
+ status: string;
+ reminders_off: number;
+ role: string;
+ starts_at_utc: string;
+ ends_at_utc: string;
+ title: string;
+ location: string;
+ tz: string;
+ }
+ | undefined;
+ if (!row || !row.name || !row.email) return null;
+ if (row.status !== 'confirmed' && row.status !== 'cancelled') return null;
+ return {
+ name: row.name,
+ email: row.email,
+ phone: row.phone,
+ notes: row.notes,
+ role: row.role,
+ eventTitle: row.title,
+ location: row.location.trim(),
+ when: formatInstantInZone(row.starts_at_utc, row.tz),
+ groupSize: Number(row.group_size),
+ status: row.status,
+ ended: row.ends_at_utc <= now,
+ remindersOff: row.reminders_off === 1,
+ };
+}
+
export function readReminderOffToken(secret: string, token: string): number | null {
if (!/^([1-9][0-9]{0,15})\.([A-Za-z0-9_-]{20,128})$/.test(token)) return null;
const id = Number(token.slice(0, token.indexOf('.')));
diff --git a/src/signup.ts b/src/signup.ts
index 4f93d9d..e860612 100644
--- a/src/signup.ts
+++ b/src/signup.ts
@@ -101,6 +101,23 @@ export function cancelSignup(db: Database.Database, token: string, now: string,
return db.transaction(() => cancelConfirmed(db, hash, token, now, mail)).immediate();
}
+/**
+ * Cancels one signup from the reminder link. The private manage token is only stored as a hash, so this does not need it.
+ * The manage link keeps working. The cancellation letter links to pageUrl, which is the reminder page.
+ * Cancelling again does not queue a second letter.
+ * Once the shift has ended, a confirmed signup stays confirmed and no mail is queued.
+ */
+export function cancelSignupById(
+ db: Database.Database,
+ signupId: number,
+ now: string,
+ mail: MailIdentity,
+ pageUrl: string,
+): CancelResult {
+ if (!Number.isSafeInteger(signupId) || signupId <= 0 || pageUrl.trim() === '') return { ok: false, reason: 'invalid' };
+ return db.transaction(() => cancelConfirmedById(db, signupId, now, mail, pageUrl)).immediate();
+}
+
export type PartySizeResult =
| { ok: true; groupSize: number; changed: boolean }
| { ok: false; reason: 'invalid' | 'cancelled' | 'full' | 'ended'; spotsLeft?: number };
@@ -399,6 +416,92 @@ function writePartySize(
return { ok: true, groupSize, changed: true };
}
+type CancelMailRow = {
+ id: number;
+ status: string;
+ anonymized_at: string | null;
+ name: string | null;
+ email_norm: string | null;
+ shift_id: number;
+ group_size: number;
+};
+
+function cancelConfirmedById(
+ db: Database.Database,
+ signupId: number,
+ now: string,
+ mail: MailIdentity,
+ pageUrl: string,
+): CancelResult {
+ const row = db
+ .prepare(
+ `SELECT su.id AS id, su.status AS status, su.anonymized_at AS anonymized_at,
+ su.name AS name, su.email_norm AS email_norm, su.shift_id AS shift_id, su.group_size AS group_size
+ FROM signups su
+ WHERE su.id = ?`,
+ )
+ .get(signupId) as CancelMailRow | undefined;
+ if (!row || row.anonymized_at) return { ok: false, reason: 'invalid' };
+ if (row.status === 'cancelled') return { ok: true, already: true };
+ if (row.status !== 'confirmed' || !row.name || !row.email_norm) return { ok: false, reason: 'invalid' };
+ const endsAt = shiftEndsAt(db, row.shift_id);
+ if (endsAt === null) return { ok: false, reason: 'invalid' };
+ if (endsAt <= now) return { ok: false, reason: 'ended' };
+ const updated = db
+ .prepare(
+ `UPDATE signups
+ SET status = 'cancelled', updated_at = ?
+ WHERE id = ? AND status = 'confirmed' AND anonymized_at IS NULL`,
+ )
+ .run(now, signupId);
+ if (updated.changes === 1) {
+ queueVolunteerCancellation(db, row, now, mail, { token: '', pageUrl });
+ return { ok: true, already: false };
+ }
+ const again = db.prepare('SELECT status AS status FROM signups WHERE id = ?').get(signupId) as { status: string } | undefined;
+ if (again?.status === 'cancelled') return { ok: true, already: true };
+ return { ok: false, reason: 'invalid' };
+}
+
+function queueVolunteerCancellation(
+ db: Database.Database,
+ row: CancelMailRow,
+ now: string,
+ mail: MailIdentity,
+ link: { token: string; pageUrl?: string },
+): void {
+ if (!row.name || !row.email_norm) return;
+ cancelPendingConfirmations(db, row.id);
+ cancelPendingReminders(db, row.id, 'The signup was cancelled before this reminder was sent.');
+ const shift = loadShiftFacts(db, row.shift_id);
+ if (!shift) return;
+ queueCancellation(db, {
+ signupId: row.id,
+ shiftId: row.shift_id,
+ shiftVersion: shift.version,
+ token: link.token,
+ pageUrl: link.pageUrl,
+ volunteerName: row.name,
+ volunteerEmail: row.email_norm,
+ groupSize: Number(row.group_size),
+ shift: shift.facts,
+ mail,
+ now,
+ });
+ queueCoordinatorNotices(db, {
+ action: 'cancel',
+ signupId: row.id,
+ shiftId: row.shift_id,
+ shiftVersion: shift.version,
+ volunteerName: row.name,
+ volunteerEmail: row.email_norm,
+ groupSize: Number(row.group_size),
+ shift: shift.facts,
+ mail,
+ now,
+ });
+}
+
function shiftEndsAt(db: Database.Database, shiftId: number): string | null {
const shift = db.prepare('SELECT ends_at_utc AS ends_at_utc FROM shifts WHERE id = ?').get(shiftId) as
| { ends_at_utc: string }
@@ -460,35 +563,7 @@ function cancelConfirmed(db: Database.Database, hash: string, token: string, now
)
.run(now, hash, now);
if (updated.changes === 1) {
- cancelPendingConfirmations(db, row.id);
- cancelPendingReminders(db, row.id, 'The signup was cancelled before this reminder was sent.');
- const shift = loadShiftFacts(db, row.shift_id);
- if (shift) {
- queueCancellation(db, {
- signupId: row.id,
- shiftId: row.shift_id,
- shiftVersion: shift.version,
- token,
- volunteerName: row.name,
- volunteerEmail: row.email_norm,
- groupSize: Number(row.group_size),
- shift: shift.facts,
- mail,
- now,
- });
- queueCoordinatorNotices(db, {
- action: 'cancel',
- signupId: row.id,
- shiftId: row.shift_id,
- shiftVersion: shift.version,
- volunteerName: row.name,
- volunteerEmail: row.email_norm,
- groupSize: Number(row.group_size),
- shift: shift.facts,
- mail,
- now,
- });
- }
+ queueVolunteerCancellation(db, row, now, mail, { token });
return { ok: true, already: false };
}
const again = db
diff --git a/tests/reminders.test.ts b/tests/reminders.test.ts
index 7aefd95..a2fda5f 100644
--- a/tests/reminders.test.ts
+++ b/tests/reminders.test.ts
@@ -9,6 +9,8 @@ import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js';
import { deliverDueMail } from '../src/mail/deliver.js';
import type { Mailer } from '../src/mail/types.js';
+import { issueReminderCancelToken } from '../src/cancel-token.js';
+import { renderReminder } from '../src/mail/templates.js';
import { issueReminderOffToken } from '../src/reminders.js';
import { queueDueReminders } from '../src/reminders.js';
import { reserveSignup, type ReserveInput } from '../src/signup.js';
@@ -45,14 +47,18 @@ describe('reminder mail', () => {
it('queues the 48 hour reminder, sends it once, and records provider acceptance', async () => {
const db = await openDb();
const shiftId = insertShift(db, LATER_START, LATER_END);
- reserveSignup(db, reservation(shiftId, { name: 'Pat