feat: add volunteer shift signup app
Initial source, tests, migrations, and local Docker setup for the Hope Food Pantry volunteer scheduler.
This commit is contained in:
commit
f1a46e2ba7
129 files changed
+25290
No files matched your search
@@ -0,0 +1,18 @@
|
||||
import type { Mailer, OutboundMail } from './types.js';
|
||||
|
||||
/** Development mailbox. The message is accepted locally and printed. It is not delivered to a person. */
|
||||
export function createConsoleMailer(write: (line: string) => void = (line) => console.log(line)): Mailer {
|
||||
return {
|
||||
async send(message: OutboundMail) {
|
||||
const extra = Object.entries(message.headers ?? {}).map(([name, value]) => `${name}: ${value}`);
|
||||
write([
|
||||
'Mail console driver accepted a message.',
|
||||
`To: ${message.to}`,
|
||||
`Subject: ${message.subject}`,
|
||||
...extra,
|
||||
message.text,
|
||||
].join('\n'));
|
||||
return { result: 'sent', providerId: null };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { formatUtc } from '../time.js';
|
||||
import { redactMailError } from './redact.js';
|
||||
import type { MailDelivery, Mailer, OutboundMail } from './types.js';
|
||||
|
||||
const LEASE_MS = 2 * 60 * 1000;
|
||||
const MAX_ATTEMPTS = 5;
|
||||
const BATCH = 20;
|
||||
|
||||
type ClaimedRow = {
|
||||
id: number;
|
||||
signup_id: number | null;
|
||||
kind: string;
|
||||
dedupe_key: string;
|
||||
to_email: string;
|
||||
subject: string;
|
||||
body_text: string;
|
||||
body_html: string;
|
||||
headers_json: string;
|
||||
attempts: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Claims due confirmation, change, cancellation, reminder, and sign-in mail, then sends outside the database transaction.
|
||||
* An expired sending lease becomes delivery_unknown and is not sent again.
|
||||
* sent_at means the provider accepted the message.
|
||||
*/
|
||||
export async function deliverDueMail(
|
||||
db: Database.Database,
|
||||
mailer: Mailer,
|
||||
now: string,
|
||||
random: () => number = Math.random,
|
||||
): Promise<number> {
|
||||
let accepted = 0;
|
||||
for (let index = 0; index < BATCH; index += 1) {
|
||||
const claimed = claimNext(db, now);
|
||||
if (!claimed) break;
|
||||
const reason = obsoleteReason(db, claimed, now);
|
||||
if (reason) {
|
||||
settle(db, claimed.id, { result: 'failed', error: reason }, now, random, 'cancelled');
|
||||
continue;
|
||||
}
|
||||
let delivery: MailDelivery;
|
||||
try {
|
||||
delivery = await mailer.send(outbound(claimed));
|
||||
} catch (err) {
|
||||
delivery = { result: 'unknown', error: redactMailError(err instanceof Error ? err.message : 'Mail send failed.') };
|
||||
}
|
||||
settle(db, claimed.id, delivery, now, random);
|
||||
if (delivery.result === 'sent') accepted += 1;
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
|
||||
export function retryDelayMs(attempts: number, random: () => number): number {
|
||||
const base = Math.min(30_000 * 2 ** Math.max(0, attempts - 1), 15 * 60 * 1000);
|
||||
const unit = random();
|
||||
const jitter = 0.8 + (Number.isFinite(unit) ? Math.min(1, Math.max(0, unit)) : 0) * 0.4;
|
||||
return Math.round(base * jitter);
|
||||
}
|
||||
|
||||
function claimNext(db: Database.Database, now: string): ClaimedRow | null {
|
||||
const leaseEnd = formatUtc(Temporal.Instant.from(now).add({ milliseconds: LEASE_MS }));
|
||||
return db.transaction(() => {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'delivery_unknown', delivery_unknown_at = ?, last_error = ?
|
||||
WHERE status = 'sending' AND lease_expires_at IS NOT NULL AND lease_expires_at <= ?`,
|
||||
).run(now, 'The sending lease expired before a result was recorded.', now);
|
||||
const next = db
|
||||
.prepare(
|
||||
`SELECT id AS id
|
||||
FROM outbox
|
||||
WHERE status = 'pending' AND send_after <= ? AND kind IN ('confirmation', 'cancelled', 'changed', 'reminder', 'magic_link')
|
||||
ORDER BY id
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(now) as { id: number } | undefined;
|
||||
if (!next) return null;
|
||||
const claimed = db
|
||||
.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'sending', attempts = attempts + 1, claimed_at = ?, lease_expires_at = ?
|
||||
WHERE id = ? AND status = 'pending'`,
|
||||
)
|
||||
.run(now, leaseEnd, next.id);
|
||||
if (claimed.changes !== 1) return null;
|
||||
return db
|
||||
.prepare(
|
||||
`SELECT id, signup_id, kind, dedupe_key, to_email, subject, body_text, body_html, headers_json, attempts
|
||||
FROM outbox WHERE id = ?`,
|
||||
)
|
||||
.get(next.id) as ClaimedRow;
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
function obsoleteReason(db: Database.Database, row: ClaimedRow, now: string): string | null {
|
||||
if (row.kind === 'magic_link') return magicLinkReason(db, row, now);
|
||||
if (row.signup_id === null) return 'The signup is no longer available.';
|
||||
const signup = db
|
||||
.prepare(
|
||||
`SELECT su.status AS status, su.token_expires_at AS token_expires_at, su.anonymized_at AS anonymized_at,
|
||||
su.reminders_off AS reminders_off,
|
||||
s.cancelled AS shift_cancelled, s.version AS version, s.starts_at_utc AS starts_at_utc
|
||||
FROM signups su
|
||||
JOIN shifts s ON s.id = su.shift_id
|
||||
WHERE su.id = ?`,
|
||||
)
|
||||
.get(row.signup_id) as
|
||||
| {
|
||||
status: string;
|
||||
token_expires_at: string | null;
|
||||
anonymized_at: string | null;
|
||||
reminders_off: number;
|
||||
shift_cancelled: number;
|
||||
version: number;
|
||||
starts_at_utc: string;
|
||||
}
|
||||
| undefined;
|
||||
if (!signup || signup.anonymized_at) return 'The signup is no longer available.';
|
||||
if (row.kind === 'reminder') return reminderReason(row, signup, now);
|
||||
if (!signup.token_expires_at || signup.token_expires_at <= now) return 'The manage link expired before this message was sent.';
|
||||
if (row.kind === 'confirmation' && (signup.status !== 'confirmed' || signup.shift_cancelled === 1)) {
|
||||
return 'The signup changed before this message was sent.';
|
||||
}
|
||||
if (row.kind === 'changed') {
|
||||
const version = changedVersion(row.dedupe_key);
|
||||
if (signup.status !== 'confirmed' || signup.shift_cancelled === 1 || version !== signup.version) {
|
||||
return 'The shift changed again before this message was sent.';
|
||||
}
|
||||
}
|
||||
if (row.kind === 'cancelled' && signup.status !== 'cancelled') return 'The signup is not cancelled.';
|
||||
return null;
|
||||
}
|
||||
|
||||
function magicLinkReason(db: Database.Database, row: ClaimedRow, now: string): string | null {
|
||||
const match = /^magic_link:([a-f0-9]{64})$/.exec(row.dedupe_key);
|
||||
const hash = match?.[1];
|
||||
if (!hash) return 'The sign-in link is no longer available.';
|
||||
const token = db
|
||||
.prepare(
|
||||
`SELECT t.used_at AS used_at, t.expires_at AS expires_at, c.active AS active
|
||||
FROM login_tokens t
|
||||
JOIN coordinators c ON c.id = t.coordinator_id
|
||||
WHERE t.token_hash = ?`,
|
||||
)
|
||||
.get(hash) as { used_at: string | null; expires_at: string; active: number } | undefined;
|
||||
if (!token || token.used_at !== null || token.expires_at <= now || token.active !== 1) {
|
||||
return 'The sign-in link is no longer available.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function reminderReason(
|
||||
row: ClaimedRow,
|
||||
signup: { status: string; reminders_off: number; shift_cancelled: number; version: number; starts_at_utc: string; token_expires_at: string | null },
|
||||
now: string,
|
||||
): string | null {
|
||||
const version = reminderVersion(row.dedupe_key);
|
||||
if (signup.status !== 'confirmed' || signup.reminders_off === 1) {
|
||||
return signup.reminders_off === 1
|
||||
? 'Reminders were turned off before this message was sent.'
|
||||
: 'The signup changed before this reminder was sent.';
|
||||
}
|
||||
if (signup.shift_cancelled === 1 || version !== signup.version) return 'The shift changed before this reminder was sent.';
|
||||
if (signup.starts_at_utc <= now) return 'The shift started before this reminder was sent.';
|
||||
if (!signup.token_expires_at || signup.token_expires_at <= now) return 'The manage link expired before this message was sent.';
|
||||
return null;
|
||||
}
|
||||
|
||||
function reminderVersion(dedupeKey: string): number | null {
|
||||
const match = /^reminder:v([1-9][0-9]*):/.exec(dedupeKey);
|
||||
if (!match?.[1]) return null;
|
||||
const value = Number(match[1]);
|
||||
return Number.isSafeInteger(value) ? value : null;
|
||||
}
|
||||
|
||||
function changedVersion(dedupeKey: string): number | null {
|
||||
const match = /^changed:v([1-9][0-9]*):/.exec(dedupeKey);
|
||||
if (!match?.[1]) return null;
|
||||
const value = Number(match[1]);
|
||||
return Number.isSafeInteger(value) ? value : null;
|
||||
}
|
||||
|
||||
function outbound(row: ClaimedRow): OutboundMail {
|
||||
const stored = JSON.parse(row.headers_json) as Record<string, string>;
|
||||
const headers: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(stored)) {
|
||||
if (key === 'From' || key === 'Reply-To' || typeof value !== 'string') continue;
|
||||
headers[key] = value;
|
||||
}
|
||||
return {
|
||||
from: stored.From ?? '',
|
||||
to: row.to_email,
|
||||
replyTo: stored['Reply-To'] ?? '',
|
||||
subject: row.subject,
|
||||
text: row.body_text,
|
||||
html: row.body_html,
|
||||
headers,
|
||||
};
|
||||
}
|
||||
|
||||
function settle(
|
||||
db: Database.Database,
|
||||
id: number,
|
||||
delivery: MailDelivery,
|
||||
now: string,
|
||||
random: () => number,
|
||||
force?: 'cancelled',
|
||||
): void {
|
||||
if (force === 'cancelled') {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?, lease_expires_at = NULL
|
||||
WHERE id = ? AND status = 'sending'`,
|
||||
).run(delivery.result === 'failed' ? delivery.error : 'The message was not sent.', id);
|
||||
return;
|
||||
}
|
||||
if (delivery.result === 'sent') {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'sent', provider_id = ?, sent_at = ?, last_error = NULL, lease_expires_at = NULL
|
||||
WHERE id = ? AND status = 'sending'`,
|
||||
).run(delivery.providerId, now, id);
|
||||
db.prepare('UPDATE reminders_sent SET sent_at = ? WHERE outbox_id = ? AND sent_at IS NULL').run(now, id);
|
||||
return;
|
||||
}
|
||||
const attempts = db.prepare('SELECT attempts AS attempts FROM outbox WHERE id = ?').get(id) as { attempts: number };
|
||||
const error = redactMailError(delivery.error);
|
||||
if (delivery.result === 'unknown') {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'delivery_unknown', delivery_unknown_at = ?, last_error = ?, lease_expires_at = NULL
|
||||
WHERE id = ? AND status = 'sending'`,
|
||||
).run(now, error, id);
|
||||
console.error(`Mail result unknown for outbox ${id}.`);
|
||||
return;
|
||||
}
|
||||
if (delivery.result === 'retry' && attempts.attempts < MAX_ATTEMPTS) {
|
||||
const sendAfter = formatUtc(Temporal.Instant.from(now).add({ milliseconds: retryDelayMs(attempts.attempts, random) }));
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'pending', send_after = ?, last_error = ?, claimed_at = NULL, lease_expires_at = NULL
|
||||
WHERE id = ? AND status = 'sending'`,
|
||||
).run(sendAfter, error, id);
|
||||
return;
|
||||
}
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'failed', last_error = ?, lease_expires_at = NULL
|
||||
WHERE id = ? AND status = 'sending'`,
|
||||
).run(error, id);
|
||||
console.error(`Mail result failed for outbox ${id}.`);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { createConsoleMailer } from './console.js';
|
||||
import { createPostmarkMailer } from './postmark.js';
|
||||
import { createSesMailer } from './ses.js';
|
||||
import type { Mailer } from './types.js';
|
||||
|
||||
export function createMailer(config: AppConfig): Mailer {
|
||||
if (config.mail.driver === 'console') return createConsoleMailer();
|
||||
if (config.mail.driver === 'postmark') {
|
||||
if (!config.mail.postmarkToken) throw new Error('POSTMARK_TOKEN is required for the postmark mail driver.');
|
||||
return createPostmarkMailer(config.mail.postmarkToken);
|
||||
}
|
||||
if (!config.mail.ses) throw new Error('SES credentials are required for the ses mail driver.');
|
||||
return createSesMailer({
|
||||
region: config.mail.ses.region,
|
||||
accessKeyId: config.mail.ses.accessKeyId,
|
||||
secretAccessKey: config.mail.ses.secretAccessKey,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/** Escape text that came from a person before it is placed in HTML mail. */
|
||||
export function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
/** Keep a subject on one line so a name cannot add mail headers. */
|
||||
export function singleLine(value: string): string {
|
||||
return value.replace(/[\u0000-\u001F\u007F]+/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { redactMailError } from './redact.js';
|
||||
import type { MailDelivery, Mailer, OutboundMail } from './types.js';
|
||||
|
||||
const ENDPOINT = 'https://api.postmarkapp.com/email';
|
||||
|
||||
/**
|
||||
* Postmark's send API. There is no idempotency key that makes a second POST harmless,
|
||||
* so a duplicate is prevented by the outbox dedupe key, not by Postmark.
|
||||
*/
|
||||
export function createPostmarkMailer(token: string, fetchImpl: typeof fetch = fetch): Mailer {
|
||||
return {
|
||||
async send(message: OutboundMail): Promise<MailDelivery> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetchImpl(ENDPOINT, {
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
redirect: 'error',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Postmark-Server-Token': token,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
From: message.from,
|
||||
To: message.to,
|
||||
Subject: message.subject,
|
||||
TextBody: message.text,
|
||||
HtmlBody: message.html,
|
||||
ReplyTo: message.replyTo,
|
||||
MessageStream: 'outbound',
|
||||
...(message.headers && Object.keys(message.headers).length > 0
|
||||
? { Headers: Object.entries(message.headers).map(([Name, Value]) => ({ Name, Value })) }
|
||||
: {}),
|
||||
}),
|
||||
});
|
||||
} catch (err) {
|
||||
const messageText = err instanceof Error ? err.message : 'Postmark request failed.';
|
||||
const uncertain = err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError');
|
||||
return {
|
||||
result: uncertain ? 'unknown' : 'retry',
|
||||
error: redactMailError(messageText),
|
||||
};
|
||||
}
|
||||
if (response.status === 408 || response.status === 504) {
|
||||
return { result: 'unknown', error: `Postmark responded ${response.status}.` };
|
||||
}
|
||||
if (response.status === 429 || response.status >= 500) {
|
||||
return { result: 'retry', error: `Postmark responded ${response.status}.` };
|
||||
}
|
||||
let payload: { ErrorCode?: number; Message?: string; MessageID?: string } = {};
|
||||
try {
|
||||
payload = (await response.json()) as typeof payload;
|
||||
} catch {
|
||||
return { result: response.ok ? 'unknown' : 'failed', error: `Postmark responded ${response.status}.` };
|
||||
}
|
||||
if (response.ok && (payload.ErrorCode === undefined || payload.ErrorCode === 0)) {
|
||||
return { result: 'sent', providerId: payload.MessageID ?? null };
|
||||
}
|
||||
return { result: 'failed', error: redactMailError(payload.Message || `Postmark responded ${response.status}.`) };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { absoluteUrl } from '../url.js';
|
||||
import { renderCancellation, renderChanged, renderConfirmation, renderMagicLink, renderMoved, renderSwitched, type MailShift } from './templates.js';
|
||||
import type { MailIdentity } from './types.js';
|
||||
|
||||
export type QueuedSignup = {
|
||||
signupId: number;
|
||||
shiftId: number;
|
||||
shiftVersion: number;
|
||||
token: string;
|
||||
volunteerName: string;
|
||||
volunteerEmail: string;
|
||||
guardianEmail: string | null;
|
||||
shift: MailShift;
|
||||
mail: MailIdentity;
|
||||
now: string;
|
||||
linkNote?: string;
|
||||
};
|
||||
|
||||
/** 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,
|
||||
volunteerName: input.volunteerName,
|
||||
shift: input.shift,
|
||||
manageUrl: manageUrl(input),
|
||||
replyTo: input.mail.replyTo,
|
||||
}));
|
||||
}
|
||||
|
||||
export function queueCancellation(db: Database.Database, input: QueuedSignup): void {
|
||||
queue(db, 'cancelled', input, (audience) => renderCancellation({
|
||||
audience,
|
||||
volunteerName: input.volunteerName,
|
||||
shift: input.shift,
|
||||
manageUrl: manageUrl(input),
|
||||
replyTo: input.mail.replyTo,
|
||||
linkNote: input.linkNote,
|
||||
}));
|
||||
}
|
||||
|
||||
export function queueChanged(db: Database.Database, input: QueuedSignup, reason: 'edit' | 'move' | 'switch' = 'edit'): void {
|
||||
queue(db, 'changed', input, (audience) => {
|
||||
const letter = {
|
||||
audience,
|
||||
volunteerName: input.volunteerName,
|
||||
shift: input.shift,
|
||||
manageUrl: manageUrl(input),
|
||||
replyTo: input.mail.replyTo,
|
||||
};
|
||||
if (reason === 'move') return renderMoved(letter);
|
||||
if (reason === 'switch') return renderSwitched(letter);
|
||||
return renderChanged(letter);
|
||||
});
|
||||
}
|
||||
|
||||
export function queueMagicLink(
|
||||
db: Database.Database,
|
||||
input: { email: string; token: string; tokenHash: string; mail: MailIdentity; now: string },
|
||||
): void {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?
|
||||
WHERE kind = 'magic_link' AND status = 'pending' AND to_email = ?`,
|
||||
).run('A newer sign-in link replaced this message.', input.email);
|
||||
const rendered = renderMagicLink({
|
||||
signInUrl: absoluteUrl(input.mail, `/login/link/${input.token}`),
|
||||
replyTo: input.mail.replyTo,
|
||||
});
|
||||
db.prepare(
|
||||
`INSERT INTO outbox (
|
||||
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||
headers_json, send_after, attempts, status, created_at
|
||||
) VALUES (?, NULL, NULL, 'magic_link', ?, ?, ?, ?, ?, ?, 0, 'pending', ?)`,
|
||||
).run(
|
||||
`magic_link:${input.tokenHash}`,
|
||||
input.email,
|
||||
rendered.subject,
|
||||
rendered.text,
|
||||
rendered.html,
|
||||
JSON.stringify({ From: input.mail.from, 'Reply-To': input.mail.replyTo }),
|
||||
input.now,
|
||||
input.now,
|
||||
);
|
||||
}
|
||||
|
||||
/** Pending confirmation or change mail is obsolete after the signup is cancelled. Sent mail cannot be recalled. */
|
||||
export function cancelPendingConfirmations(db: Database.Database, signupId: number): void {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?
|
||||
WHERE signup_id = ? AND kind IN ('confirmation', 'changed') AND status = 'pending'`,
|
||||
).run('The signup was cancelled before this message was sent.', signupId);
|
||||
}
|
||||
|
||||
/** A reminder still waiting is not sent after the signup moves, is cancelled, or turns reminders off. Sent mail cannot be recalled. */
|
||||
export function cancelPendingReminders(
|
||||
db: Database.Database,
|
||||
signupId: number,
|
||||
reason = 'The signup moved before this reminder was sent.',
|
||||
): void {
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?
|
||||
WHERE signup_id = ? AND kind = 'reminder' AND status = 'pending'`,
|
||||
).run(reason, signupId);
|
||||
}
|
||||
|
||||
function queue(
|
||||
db: Database.Database,
|
||||
kind: 'confirmation' | 'cancelled' | 'changed',
|
||||
input: QueuedSignup,
|
||||
render: (audience: 'volunteer' | 'guardian') => { 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);
|
||||
db.prepare(
|
||||
`INSERT INTO outbox (
|
||||
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||
headers_json, send_after, attempts, status, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'pending', ?)
|
||||
ON CONFLICT (dedupe_key) DO NOTHING`,
|
||||
).run(
|
||||
`${kind}:v${input.shiftVersion}:${input.signupId}:${recipient}`,
|
||||
input.signupId,
|
||||
input.shiftId,
|
||||
kind,
|
||||
recipient,
|
||||
rendered.subject,
|
||||
rendered.text,
|
||||
rendered.html,
|
||||
JSON.stringify({ From: input.mail.from, 'Reply-To': input.mail.replyTo }),
|
||||
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 {
|
||||
return absoluteUrl(input.mail, `/m/${input.token}`);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Drop addresses and manage links before an error is stored or logged. */
|
||||
export function redactMailError(value: string): string {
|
||||
return value
|
||||
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '[email]')
|
||||
.replace(/\/m\/[A-Za-z0-9_-]{10,}/g, '/m/[token]')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.slice(0, 300);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { deliverDueMail } from './deliver.js';
|
||||
import type { Mailer } from './types.js';
|
||||
|
||||
const INTERVAL_MS = 30_000;
|
||||
|
||||
/**
|
||||
* One in-process pass every 30 seconds. A pass that is still running is not started again.
|
||||
* Already accepted mail cannot be recalled.
|
||||
*/
|
||||
export function startOutboxRunner(db: Database.Database, mailer: Mailer, now: () => string): { stop: () => void } {
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
const tick = () => {
|
||||
if (running || stopped) return;
|
||||
running = true;
|
||||
void deliverDueMail(db, mailer, now())
|
||||
.catch((err: unknown) => {
|
||||
console.error(err instanceof Error ? err.message : 'Mail delivery failed.');
|
||||
})
|
||||
.finally(() => {
|
||||
running = false;
|
||||
});
|
||||
};
|
||||
const timer = setInterval(tick, INTERVAL_MS);
|
||||
timer.unref();
|
||||
tick();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { SESv2Client, SendEmailCommand } from '@aws-sdk/client-sesv2';
|
||||
import { redactMailError } from './redact.js';
|
||||
import type { MailDelivery, Mailer, OutboundMail } from './types.js';
|
||||
|
||||
const PERMANENT = new Set([
|
||||
'MessageRejected',
|
||||
'MailFromDomainNotVerifiedException',
|
||||
'AccountSuspendedException',
|
||||
'SendingPausedException',
|
||||
]);
|
||||
|
||||
const RETRYABLE = new Set([
|
||||
'TooManyRequestsException',
|
||||
'LimitExceededException',
|
||||
'ServiceUnavailableException',
|
||||
'InternalFailure',
|
||||
]);
|
||||
|
||||
export type SesSender = {
|
||||
send(command: SendEmailCommand, options?: { abortSignal?: AbortSignal }): Promise<{ MessageId?: string }>;
|
||||
};
|
||||
|
||||
/** SESv2 SendEmail. Acceptance is MessageId, not proof the person received the mail. */
|
||||
export function createSesMailer(options: {
|
||||
region: string;
|
||||
accessKeyId: string;
|
||||
secretAccessKey: string;
|
||||
client?: SesSender;
|
||||
}): Mailer {
|
||||
const client = options.client ?? new SESv2Client({
|
||||
maxAttempts: 1,
|
||||
region: options.region,
|
||||
credentials: {
|
||||
accessKeyId: options.accessKeyId,
|
||||
secretAccessKey: options.secretAccessKey,
|
||||
},
|
||||
});
|
||||
return {
|
||||
async send(message: OutboundMail): Promise<MailDelivery> {
|
||||
try {
|
||||
const result = await client.send(new SendEmailCommand({
|
||||
FromEmailAddress: message.from,
|
||||
Destination: { ToAddresses: [message.to] },
|
||||
ReplyToAddresses: [message.replyTo],
|
||||
Content: {
|
||||
Simple: {
|
||||
Subject: { Data: message.subject, Charset: 'UTF-8' },
|
||||
Body: {
|
||||
Text: { Data: message.text, Charset: 'UTF-8' },
|
||||
Html: { Data: message.html, Charset: 'UTF-8' },
|
||||
},
|
||||
...(message.headers && Object.keys(message.headers).length > 0
|
||||
? { Headers: Object.entries(message.headers).map(([Name, Value]) => ({ Name, Value })) }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
}), { abortSignal: AbortSignal.timeout(15_000) });
|
||||
return { result: 'sent', providerId: result.MessageId ?? null };
|
||||
} catch (err) {
|
||||
return mapSesError(err);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function mapSesError(err: unknown): MailDelivery {
|
||||
const name = err instanceof Error ? err.name : '';
|
||||
const error = redactMailError(err instanceof Error ? err.message : 'SES request failed.');
|
||||
if (PERMANENT.has(name)) return { result: 'failed', error };
|
||||
if (RETRYABLE.has(name)) return { result: 'retry', error };
|
||||
if (name === 'TimeoutError' || name === 'AbortError') return { result: 'unknown', error };
|
||||
return { result: 'unknown', error };
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
import { escapeHtml, singleLine } from './html.js';
|
||||
|
||||
export type MailShift = {
|
||||
role: string;
|
||||
eventTitle: string;
|
||||
location: string;
|
||||
whenLabel: string;
|
||||
};
|
||||
|
||||
export type RenderedMail = {
|
||||
subject: string;
|
||||
text: string;
|
||||
html: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Confirmation and cancellation letters.
|
||||
* Email clients do not load the app stylesheet, so the HTML repeats the fallback
|
||||
* ink and blue from public/brand/tokens.css.
|
||||
*/
|
||||
export function renderConfirmation(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} 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},`,
|
||||
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.',
|
||||
manageUrl: input.manageUrl,
|
||||
replyTo: input.replyTo,
|
||||
});
|
||||
}
|
||||
|
||||
export function renderCancellation(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
linkNote?: string;
|
||||
}): 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},`,
|
||||
shift: input.shift,
|
||||
linkLabel: 'Open this signup',
|
||||
linkNote: input.linkNote ?? 'That link opens the cancelled signup.',
|
||||
manageUrl: input.manageUrl,
|
||||
replyTo: input.replyTo,
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function changedLetter(
|
||||
input: { audience: 'volunteer' | 'guardian'; volunteerName: string; shift: MailShift; manageUrl: string; replyTo: string },
|
||||
subject: string,
|
||||
hello: string,
|
||||
): RenderedMail {
|
||||
const name = singleLine(input.volunteerName);
|
||||
return render({
|
||||
subject,
|
||||
hello,
|
||||
greeting: input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`,
|
||||
shift: input.shift,
|
||||
linkLabel: 'Open this signup',
|
||||
linkNote: 'This link replaces the earlier one. The previous link no longer works.',
|
||||
manageUrl: input.manageUrl,
|
||||
replyTo: input.replyTo,
|
||||
});
|
||||
}
|
||||
|
||||
export function renderReminder(input: {
|
||||
audience: 'volunteer' | 'guardian';
|
||||
volunteerName: string;
|
||||
shift: MailShift;
|
||||
unsubscribeUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
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 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 when = input.shift.whenLabel;
|
||||
const place = input.shift.location.trim();
|
||||
const lines = [
|
||||
greeting,
|
||||
'',
|
||||
hello,
|
||||
'',
|
||||
input.shift.eventTitle,
|
||||
when,
|
||||
...(place ? [place] : []),
|
||||
'',
|
||||
cancelNote,
|
||||
'',
|
||||
stopNote,
|
||||
'',
|
||||
'Hope Food Pantry',
|
||||
];
|
||||
const htmlPlace = place ? `<br>${escapeHtml(place)}` : '';
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(subject)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:24px;background:#f4fafd;color:#222;font-family:sans-serif;line-height:1.5">
|
||||
<p>${escapeHtml(greeting)}</p>
|
||||
<p>${escapeHtml(hello)}</p>
|
||||
<p>${escapeHtml(input.shift.eventTitle)}<br>${escapeHtml(when)}${htmlPlace}</p>
|
||||
<p>${escapeHtml(cancelNote)}</p>
|
||||
<p><a href="${escapeHtml(input.unsubscribeUrl)}" style="color:#222">Stop reminder emails</a></p>
|
||||
<p>The pantry reads mail sent to ${escapeHtml(input.replyTo)}. Stopping reminders does not cancel the signup. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
<p>Hope Food Pantry</p>
|
||||
</body>
|
||||
</html>`;
|
||||
return { subject, text: lines.join('\n'), html };
|
||||
}
|
||||
|
||||
export function renderMagicLink(input: { signInUrl: string; replyTo: string }): RenderedMail {
|
||||
const subject = 'Sign in to Hope Volunteer';
|
||||
const hello = 'Use this link to sign in. It expires in 15 minutes and works once.';
|
||||
const note = 'Opening the link does not sign you in. Use the button on the page. If you did not ask for this, you can ignore it.';
|
||||
const text = ['Hello,', '', hello, '', input.signInUrl, '', note, `Replies go to ${input.replyTo}.`, '', 'Hope Food Pantry'].join('\n');
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(subject)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:24px;background:#f4fafd;color:#222;font-family:sans-serif;line-height:1.5">
|
||||
<p>Hello,</p>
|
||||
<p>${escapeHtml(hello)}</p>
|
||||
<p><a href="${escapeHtml(input.signInUrl)}" style="color:#222">Sign in</a></p>
|
||||
<p>${escapeHtml(note)} Replies go to ${escapeHtml(input.replyTo)}.</p>
|
||||
<p>Hope Food Pantry</p>
|
||||
</body>
|
||||
</html>`;
|
||||
return { subject, text, html };
|
||||
}
|
||||
|
||||
function render(input: {
|
||||
subject: string;
|
||||
greeting: string;
|
||||
hello: string;
|
||||
shift: MailShift;
|
||||
linkLabel: string;
|
||||
linkNote: string;
|
||||
manageUrl: string;
|
||||
replyTo: string;
|
||||
}): RenderedMail {
|
||||
const when = input.shift.whenLabel;
|
||||
const place = input.shift.location.trim();
|
||||
const lines = [
|
||||
input.greeting,
|
||||
'',
|
||||
input.hello,
|
||||
'',
|
||||
input.shift.eventTitle,
|
||||
when,
|
||||
...(place ? [place] : []),
|
||||
'',
|
||||
`${input.linkLabel}:`,
|
||||
input.manageUrl,
|
||||
'',
|
||||
input.linkNote,
|
||||
`Replies go to ${input.replyTo}.`,
|
||||
'',
|
||||
'Hope Food Pantry',
|
||||
];
|
||||
const htmlPlace = place ? `<br>${escapeHtml(place)}` : '';
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(input.subject)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:24px;background:#f4fafd;color:#222;font-family:sans-serif;line-height:1.5">
|
||||
<p>${escapeHtml(input.greeting)}</p>
|
||||
<p>${escapeHtml(input.hello)}</p>
|
||||
<p>${escapeHtml(input.shift.eventTitle)}<br>${escapeHtml(when)}${htmlPlace}</p>
|
||||
<p><a href="${escapeHtml(input.manageUrl)}" style="color:#222">${escapeHtml(input.linkLabel)}</a></p>
|
||||
<p>${escapeHtml(input.linkNote)} Replies go to ${escapeHtml(input.replyTo)}.</p>
|
||||
<p>Hope Food Pantry</p>
|
||||
</body>
|
||||
</html>`;
|
||||
return { subject: input.subject, text: lines.join('\n'), html };
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export type MailIdentity = {
|
||||
baseUrl: string;
|
||||
basePath: string;
|
||||
from: string;
|
||||
replyTo: string;
|
||||
};
|
||||
|
||||
export type OutboundMail = {
|
||||
from: string;
|
||||
to: string;
|
||||
replyTo: string;
|
||||
subject: string;
|
||||
text: string;
|
||||
html: string;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
|
||||
/** sent: the provider accepted the message. That is not proof the person received it. */
|
||||
export type MailDelivery =
|
||||
| { result: 'sent'; providerId: string | null }
|
||||
| { result: 'retry'; error: string }
|
||||
| { result: 'failed'; error: string }
|
||||
| { result: 'unknown'; error: string };
|
||||
|
||||
export type Mailer = {
|
||||
send(message: OutboundMail): Promise<MailDelivery>;
|
||||
};
|
||||
Reference in new issue
Block a user