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
+1313
File diff suppressed because it is too large.
Load diff
+1377
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,185 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import { assertSameDayShift, LocalTimeError } from '../time.js';
|
||||
|
||||
export type EventValues = {
|
||||
title: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
published: boolean;
|
||||
};
|
||||
|
||||
export type EventInput = {
|
||||
title: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
published: boolean;
|
||||
};
|
||||
|
||||
export type ShiftValues = {
|
||||
role: string;
|
||||
date: string;
|
||||
start: string;
|
||||
end: string;
|
||||
capacity: string;
|
||||
};
|
||||
|
||||
export type ShiftInput = {
|
||||
role: string;
|
||||
date: string;
|
||||
start: string;
|
||||
end: string;
|
||||
capacity: number;
|
||||
};
|
||||
|
||||
export function eventValuesFrom(body: Record<string, unknown>, fallbackTz: string): EventValues {
|
||||
return {
|
||||
title: text(body, 'title'),
|
||||
slug: text(body, 'slug'),
|
||||
description: text(body, 'description'),
|
||||
location: text(body, 'location'),
|
||||
tz: text(body, 'tz') || fallbackTz,
|
||||
published: text(body, 'published') === 'yes',
|
||||
};
|
||||
}
|
||||
|
||||
export function parseEvent(values: EventValues): { ok: true; value: EventInput } | { ok: false; error: string } {
|
||||
const title = values.title.trim();
|
||||
if (title.length === 0) return { ok: false, error: 'Enter a title.' };
|
||||
if (title.length > 120) return { ok: false, error: 'Use a shorter title.' };
|
||||
const slug = values.slug.trim() ? normalizeSlug(values.slug) : normalizeSlug(title);
|
||||
if (!validSlug(slug)) return { ok: false, error: 'Use a public address with lowercase letters, numbers, and hyphens.' };
|
||||
const description = values.description.trim();
|
||||
if (description.length > 2000) return { ok: false, error: 'Use a shorter description.' };
|
||||
const location = values.location.trim();
|
||||
if (location.length > 200) return { ok: false, error: 'Use a shorter location.' };
|
||||
const tz = values.tz.trim();
|
||||
if (tz.length === 0) return { ok: false, error: 'Enter a time zone.' };
|
||||
return { ok: true, value: { title, slug, description, location, tz, published: values.published } };
|
||||
}
|
||||
|
||||
export function shiftValuesFrom(body: Record<string, unknown>): ShiftValues {
|
||||
return {
|
||||
role: text(body, 'role'),
|
||||
date: text(body, 'date'),
|
||||
start: clock(text(body, 'start')),
|
||||
end: clock(text(body, 'end')),
|
||||
capacity: text(body, 'capacity'),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseShift(values: ShiftValues): { ok: true; value: ShiftInput } | { ok: false; error: string } {
|
||||
const role = values.role.trim();
|
||||
if (role.length === 0) return { ok: false, error: 'Enter a role.' };
|
||||
if (role.length > 80) return { ok: false, error: 'Use a shorter role.' };
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(values.date)) return { ok: false, error: 'Enter a date.' };
|
||||
if (!/^\d{2}:\d{2}$/.test(values.start)) return { ok: false, error: 'Enter a start time as HH:MM.' };
|
||||
if (!/^\d{2}:\d{2}$/.test(values.end)) return { ok: false, error: 'Enter an end time as HH:MM.' };
|
||||
if (!/^[1-9][0-9]*$/.test(values.capacity)) return { ok: false, error: 'Enter a capacity of at least 1.' };
|
||||
const capacity = Number(values.capacity);
|
||||
if (!Number.isSafeInteger(capacity) || capacity > 500) return { ok: false, error: 'Capacity cannot be more than 500.' };
|
||||
return { ok: true, value: { role, date: values.date, start: values.start, end: values.end, capacity } };
|
||||
}
|
||||
|
||||
export type TemplateValues = {
|
||||
role: string;
|
||||
weekday: string;
|
||||
start: string;
|
||||
end: string;
|
||||
capacity: string;
|
||||
startsOn: string;
|
||||
endsOn: string;
|
||||
};
|
||||
|
||||
export type TemplateInput = {
|
||||
role: string;
|
||||
weekday: number;
|
||||
start: string;
|
||||
end: string;
|
||||
capacity: number;
|
||||
startsOn: string;
|
||||
endsOn: string | null;
|
||||
};
|
||||
|
||||
export function templateValuesFrom(body: Record<string, unknown>): TemplateValues {
|
||||
return {
|
||||
role: text(body, 'role'),
|
||||
weekday: text(body, 'weekday'),
|
||||
start: clock(text(body, 'start')),
|
||||
end: clock(text(body, 'end')),
|
||||
capacity: text(body, 'capacity'),
|
||||
startsOn: text(body, 'startsOn'),
|
||||
endsOn: text(body, 'endsOn'),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseTemplate(values: TemplateValues): { ok: true; value: TemplateInput } | { ok: false; error: string } {
|
||||
const role = values.role.trim();
|
||||
if (role.length === 0) return { ok: false, error: 'Enter a role.' };
|
||||
if (role.length > 80) return { ok: false, error: 'Use a shorter role.' };
|
||||
if (!/^[0-6]$/.test(values.weekday)) return { ok: false, error: 'Choose a day.' };
|
||||
try {
|
||||
assertSameDayShift(values.start, values.end);
|
||||
} catch (err) {
|
||||
if (err instanceof LocalTimeError) return { ok: false, error: err.message };
|
||||
throw err;
|
||||
}
|
||||
if (!calendarDate(values.startsOn)) return { ok: false, error: 'Enter the first date.' };
|
||||
const endsOn = values.endsOn.trim();
|
||||
if (endsOn.length > 0 && !calendarDate(endsOn)) return { ok: false, error: 'Enter an end date, or leave it blank.' };
|
||||
if (endsOn.length > 0 && endsOn < values.startsOn) {
|
||||
return { ok: false, error: 'The end date must be on or after the first date.' };
|
||||
}
|
||||
if (!/^[1-9][0-9]*$/.test(values.capacity)) return { ok: false, error: 'Enter a capacity of at least 1.' };
|
||||
const capacity = Number(values.capacity);
|
||||
if (!Number.isSafeInteger(capacity) || capacity > 500) return { ok: false, error: 'Capacity cannot be more than 500.' };
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
role,
|
||||
weekday: Number(values.weekday),
|
||||
start: values.start,
|
||||
end: values.end,
|
||||
capacity,
|
||||
startsOn: values.startsOn,
|
||||
endsOn: endsOn.length > 0 ? endsOn : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeSlug(input: string): string {
|
||||
return input
|
||||
.normalize('NFC')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 80)
|
||||
.replace(/-+$/g, '');
|
||||
}
|
||||
|
||||
function validSlug(slug: string): boolean {
|
||||
return slug.length >= 1 && slug.length <= 80 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug);
|
||||
}
|
||||
|
||||
function calendarDate(value: string): boolean {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
||||
try {
|
||||
Temporal.PlainDate.from(value);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function text(body: Record<string, unknown>, name: string): string {
|
||||
const value = body[name];
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
function clock(value: string): string {
|
||||
return /^([01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?$/.test(value) ? value.slice(0, 5) : value;
|
||||
}
|
||||
+1587
File diff suppressed because it is too large.
Load diff
+166
@@ -0,0 +1,166 @@
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { Hono, type Context } from 'hono';
|
||||
import { bodyLimit } from 'hono/body-limit';
|
||||
import type { Child } from 'hono/jsx';
|
||||
import { registerAdmin } from './admin-http.js';
|
||||
import { readSession } from './auth/session.js';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { EmptySchedulePage, EventPage, Layout, NotFoundPage, PrivacyPage, ProblemPage } from './pages.js';
|
||||
import { getPublishedEvent } from './schedule.js';
|
||||
import { privacyParagraphs, readPantrySettings } from './settings.js';
|
||||
import { registerReminderOff } from './reminder-http.js';
|
||||
import { registerPublicSignup } from './signup-http.js';
|
||||
import { securityHeaders } from './security.js';
|
||||
import { nowUtc } from './time.js';
|
||||
import { appPath } from './url.js';
|
||||
|
||||
export function publicDirectory(): string {
|
||||
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../public');
|
||||
}
|
||||
|
||||
export function createApp(
|
||||
config: AppConfig,
|
||||
db: Database.Database,
|
||||
options?: {
|
||||
now?: string;
|
||||
publicDir?: string;
|
||||
clientIp?: (c: Context) => string | null;
|
||||
verifyTurnstile?: Parameters<typeof registerPublicSignup>[1]['verifyTurnstile'];
|
||||
},
|
||||
): Hono {
|
||||
const app = new Hono();
|
||||
const now = () => options?.now ?? nowUtc();
|
||||
const publicDir = options?.publicDir ?? publicDirectory();
|
||||
|
||||
app.use('*', securityHeaders({ https: config.secureCookies }));
|
||||
app.use('*', bodyLimit({
|
||||
maxSize: 64 * 1024,
|
||||
onError: (c) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.text('Request body too large.', 413);
|
||||
},
|
||||
}));
|
||||
app.use(appPath(config, '/css/*'), staticFiles(config, publicDir));
|
||||
app.use(appPath(config, '/brand/*'), staticFiles(config, publicDir));
|
||||
app.use(appPath(config, '/img/*'), staticFiles(config, publicDir));
|
||||
app.use(appPath(config, '/js/*'), staticFiles(config, publicDir));
|
||||
|
||||
app.get(appPath(config, '/healthz'), (c) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
try {
|
||||
db.prepare('SELECT 1 AS ok').get();
|
||||
return c.json({ ok: true, database: 'ok' });
|
||||
} catch {
|
||||
return c.json({ ok: false, database: 'unavailable' }, 503);
|
||||
}
|
||||
});
|
||||
|
||||
app.get(appPath(config, '/'), (c) => {
|
||||
const at = now();
|
||||
const event = getPublishedEvent(db, 'weekly-pantry', at);
|
||||
if (!event) {
|
||||
return page(c, config, db, at, 'Weekly pantry · Hope Volunteer', <EmptySchedulePage />);
|
||||
}
|
||||
return page(
|
||||
c,
|
||||
config,
|
||||
db,
|
||||
at,
|
||||
`${event.title} · Hope Volunteer`,
|
||||
<EventPage config={config} event={event} now={at} month={c.req.query('month')} path="/" />,
|
||||
);
|
||||
});
|
||||
|
||||
if (config.basePath !== '') {
|
||||
app.get(`${config.basePath}/`, (c) => c.redirect(config.basePath, 302));
|
||||
}
|
||||
|
||||
app.get(appPath(config, '/privacy'), (c) => {
|
||||
const paragraphs = privacyParagraphs(readPantrySettings(db, config.mail.replyTo).privacyText);
|
||||
return page(c, config, db, now(), 'Privacy · Hope Volunteer', <PrivacyPage paragraphs={paragraphs} />);
|
||||
});
|
||||
|
||||
app.get(appPath(config, '/e/:slug'), (c) => {
|
||||
const at = now();
|
||||
const slug = c.req.param('slug') ?? '';
|
||||
const event = getPublishedEvent(db, slug, at);
|
||||
if (!event) return page(c, config, db, at, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
return page(
|
||||
c,
|
||||
config,
|
||||
db,
|
||||
at,
|
||||
`${event.title} · Hope Volunteer`,
|
||||
<EventPage config={config} event={event} now={at} month={c.req.query('month')} />,
|
||||
);
|
||||
});
|
||||
|
||||
registerPublicSignup(app, {
|
||||
config,
|
||||
db,
|
||||
now,
|
||||
clientIp: options?.clientIp,
|
||||
verifyTurnstile: options?.verifyTurnstile,
|
||||
});
|
||||
|
||||
registerReminderOff(app, {
|
||||
config,
|
||||
db,
|
||||
now,
|
||||
clientIp: options?.clientIp,
|
||||
});
|
||||
|
||||
registerAdmin(app, {
|
||||
config,
|
||||
db,
|
||||
now,
|
||||
clientIp: options?.clientIp,
|
||||
verifyTurnstile: options?.verifyTurnstile,
|
||||
});
|
||||
|
||||
app.notFound((c) => page(c, config, db, now(), 'That page is not available · Hope Volunteer', <NotFoundPage />, 404));
|
||||
app.onError((err, c) => {
|
||||
console.error(err instanceof Error ? err.message : err);
|
||||
return page(c, config, db, now(), 'Something went wrong · Hope Volunteer', <ProblemPage />, 500);
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
function page(
|
||||
c: Context,
|
||||
config: AppConfig,
|
||||
db: Database.Database,
|
||||
now: string,
|
||||
title: string,
|
||||
body: Child,
|
||||
status: 200 | 404 | 500 = 200,
|
||||
) {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
const account = readSession(db, c.req.header('cookie'), now);
|
||||
return c.html(
|
||||
<Layout config={config} title={title} path={c.req.path} account={account ? { csrf: account.csrf } : null}>
|
||||
{body}
|
||||
</Layout>,
|
||||
status,
|
||||
);
|
||||
}
|
||||
|
||||
function staticFiles(config: AppConfig, publicDir: string) {
|
||||
return serveStatic({
|
||||
root: publicDir,
|
||||
onFound: (_path, c) => {
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
},
|
||||
rewriteRequestPath: (requestPath) => {
|
||||
if (config.basePath !== '' && requestPath.startsWith(config.basePath)) {
|
||||
return requestPath.slice(config.basePath.length) || '/';
|
||||
}
|
||||
return requestPath;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
/** Records an admin or host action. Detail is ids and counts only, never addresses or notes. */
|
||||
export function writeAudit(
|
||||
db: Database.Database,
|
||||
coordinatorId: number | null,
|
||||
action: string,
|
||||
detail: Record<string, number>,
|
||||
now: string,
|
||||
): void {
|
||||
const json = JSON.stringify(detail);
|
||||
if (json.includes('@')) throw new Error('Audit detail cannot include an email address.');
|
||||
db.prepare('INSERT INTO audit (coordinator_id, action, detail_json, at) VALUES (?, ?, ?, ?)').run(
|
||||
coordinatorId,
|
||||
action,
|
||||
json,
|
||||
now,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { normalizeEmail } from '../email.js';
|
||||
import { isUniqueConstraint } from '../sqlite-error.js';
|
||||
import { writeAudit } from './audit.js';
|
||||
|
||||
/**
|
||||
* Inserts one administrator when the coordinators table is empty.
|
||||
* A later start does not overwrite that account, even if the configured address changed.
|
||||
*/
|
||||
export function bootstrapAdmin(db: Database.Database, email: string, now: string): { created: boolean } {
|
||||
const normalized = normalizeEmail(email);
|
||||
try {
|
||||
return db.transaction(() => {
|
||||
const count = db.prepare('SELECT COUNT(*) AS n FROM coordinators').get() as { n: number };
|
||||
if (count.n > 0) return { created: false };
|
||||
const inserted = db
|
||||
.prepare(
|
||||
`INSERT INTO coordinators (email, name, role, password_hash, active, created_at)
|
||||
VALUES (?, 'Administrator', 'admin', NULL, 1, ?)`,
|
||||
)
|
||||
.run(normalized, now);
|
||||
writeAudit(db, null, 'bootstrap', { coordinatorId: Number(inserted.lastInsertRowid) }, now);
|
||||
return { created: true };
|
||||
}).immediate();
|
||||
} catch (err) {
|
||||
if (isUniqueConstraint(err)) return { created: false };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { normalizeEmail } from '../email.js';
|
||||
import { queueMagicLink } from '../mail/queue.js';
|
||||
import type { MailIdentity } from '../mail/types.js';
|
||||
import { formatUtc } from '../time.js';
|
||||
import { writeAudit } from './audit.js';
|
||||
import { insertSession } from './session.js';
|
||||
|
||||
const TOKEN_SHAPE = /^[A-Za-z0-9_-]{20,128}$/;
|
||||
const LOGIN_PROOF = 'hope-login-v1\0';
|
||||
const LINK_MINUTES = 15;
|
||||
|
||||
export function requestMagicLink(
|
||||
db: Database.Database,
|
||||
input: { email: string; now: string; mail: MailIdentity },
|
||||
): { queued: boolean } {
|
||||
let emailNorm: string;
|
||||
try {
|
||||
emailNorm = normalizeEmail(input.email);
|
||||
} catch {
|
||||
return { queued: false };
|
||||
}
|
||||
return db.transaction(() => {
|
||||
const coordinator = db
|
||||
.prepare('SELECT id AS id, active AS active FROM coordinators WHERE email = ?')
|
||||
.get(emailNorm) as { id: number; active: number } | undefined;
|
||||
if (!coordinator || coordinator.active !== 1) return { queued: false };
|
||||
db.prepare('UPDATE login_tokens SET used_at = ? WHERE coordinator_id = ? AND used_at IS NULL').run(input.now, coordinator.id);
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const tokenHash = sha256(token);
|
||||
const expiresAt = formatUtc(Temporal.Instant.from(input.now).add({ minutes: LINK_MINUTES }));
|
||||
db.prepare(
|
||||
`INSERT INTO login_tokens (token_hash, coordinator_id, expires_at, used_at, created_at)
|
||||
VALUES (?, ?, ?, NULL, ?)`,
|
||||
).run(tokenHash, coordinator.id, expiresAt, input.now);
|
||||
queueMagicLink(db, { email: emailNorm, token, tokenHash, mail: input.mail, now: input.now });
|
||||
return { queued: true };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
/** Reads a sign-in link without using it. Email scanners that only open the link stop here. */
|
||||
export function loginLinkOpen(db: Database.Database, token: string, now: string): boolean {
|
||||
const row = lookup(db, token);
|
||||
return Boolean(row && row.used_at === null && row.expires_at > now && row.active === 1);
|
||||
}
|
||||
|
||||
export function consumeLoginLink(
|
||||
db: Database.Database,
|
||||
token: string,
|
||||
now: string,
|
||||
): { ok: true; sessionToken: string; csrf: string } | { ok: false } {
|
||||
if (!TOKEN_SHAPE.test(token)) return { ok: false };
|
||||
const hash = sha256(token);
|
||||
return db.transaction((): { ok: true; sessionToken: string; csrf: string } | { ok: false } => {
|
||||
const row = lookup(db, token);
|
||||
if (!row || row.used_at !== null || row.expires_at <= now || row.active !== 1) return { ok: false };
|
||||
const used = db
|
||||
.prepare(
|
||||
`UPDATE login_tokens
|
||||
SET used_at = ?
|
||||
WHERE token_hash = ? AND used_at IS NULL AND expires_at > ?`,
|
||||
)
|
||||
.run(now, hash, now);
|
||||
if (used.changes !== 1) return { ok: false };
|
||||
const session = insertSession(db, row.coordinator_id, now);
|
||||
writeAudit(db, row.coordinator_id, 'login', {}, now);
|
||||
return { ok: true as const, sessionToken: session.token, csrf: session.csrf };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
export function issueLoginProof(secret: string, token: string): string {
|
||||
return createHmac('sha256', secret).update(`${LOGIN_PROOF}${token}`).digest('base64url');
|
||||
}
|
||||
|
||||
export function loginProofMatches(secret: string, token: string, proof: string): boolean {
|
||||
const expected = issueLoginProof(secret, token);
|
||||
if (!TOKEN_SHAPE.test(proof) || !TOKEN_SHAPE.test(expected)) return false;
|
||||
const left = Buffer.from(expected);
|
||||
const right = Buffer.from(proof);
|
||||
return left.length === right.length && timingSafeEqual(left, right);
|
||||
}
|
||||
|
||||
function lookup(db: Database.Database, token: string): { coordinator_id: number; expires_at: string; used_at: string | null; active: number } | null {
|
||||
if (!TOKEN_SHAPE.test(token)) return null;
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT t.coordinator_id AS coordinator_id, t.expires_at AS expires_at, t.used_at AS used_at, c.active AS active
|
||||
FROM login_tokens t
|
||||
JOIN coordinators c ON c.id = t.coordinator_id
|
||||
WHERE t.token_hash = ?`,
|
||||
)
|
||||
.get(sha256(token)) as
|
||||
| { coordinator_id: number; expires_at: string; used_at: string | null; active: number }
|
||||
| undefined;
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
function sha256(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { normalizeEmail } from '../email.js';
|
||||
import { writeAudit } from './audit.js';
|
||||
|
||||
/**
|
||||
* Host-only recovery. There is no web page for this.
|
||||
* Revokes sessions and unused sign-in links. Optionally replaces the sign-in address.
|
||||
*/
|
||||
export function recoverCoordinator(
|
||||
db: Database.Database,
|
||||
input: { email: string; replaceWith?: string; now: string },
|
||||
): { coordinatorId: number } {
|
||||
const email = normalizeEmail(input.email);
|
||||
const next = input.replaceWith ? normalizeEmail(input.replaceWith) : null;
|
||||
return db.transaction(() => {
|
||||
const row = db.prepare('SELECT id AS id FROM coordinators WHERE email = ?').get(email) as { id: number } | undefined;
|
||||
if (!row) throw new Error('No coordinator has that address.');
|
||||
if (next && next !== email) {
|
||||
const taken = db.prepare('SELECT id AS id FROM coordinators WHERE email = ?').get(next);
|
||||
if (taken) throw new Error('Another coordinator already uses the new address.');
|
||||
db.prepare('UPDATE coordinators SET email = ? WHERE id = ?').run(next, row.id);
|
||||
}
|
||||
db.prepare('DELETE FROM sessions WHERE coordinator_id = ?').run(row.id);
|
||||
db.prepare('UPDATE login_tokens SET used_at = ? WHERE coordinator_id = ? AND used_at IS NULL').run(input.now, row.id);
|
||||
db.prepare(
|
||||
`UPDATE outbox
|
||||
SET status = 'cancelled', last_error = ?
|
||||
WHERE kind = 'magic_link' AND status = 'pending' AND to_email IN (?, ?)`,
|
||||
).run('A host recovery replaced this sign-in link.', email, next ?? email);
|
||||
writeAudit(db, null, 'host.recover', { coordinatorId: row.id }, input.now);
|
||||
return { coordinatorId: row.id };
|
||||
}).immediate();
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { formatUtc } from '../time.js';
|
||||
import { cookiePath } from '../url.js';
|
||||
|
||||
export const SESSION_COOKIE = 'hope_session';
|
||||
const SESSION_SECONDS = 14 * 24 * 60 * 60;
|
||||
const TOKEN_SHAPE = /^[A-Za-z0-9_-]{20,128}$/;
|
||||
|
||||
export type CoordinatorSession = {
|
||||
coordinatorId: number;
|
||||
role: 'admin' | 'coordinator';
|
||||
csrf: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
type CookieConfig = { basePath: string; secureCookies: boolean };
|
||||
|
||||
export function insertSession(
|
||||
db: Database.Database,
|
||||
coordinatorId: number,
|
||||
now: string,
|
||||
): { token: string; csrf: string } {
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const csrf = randomBytes(32).toString('base64url');
|
||||
const expiresAt = formatUtc(Temporal.Instant.from(now).add({ seconds: SESSION_SECONDS }));
|
||||
db.prepare(
|
||||
`INSERT INTO sessions (id_hash, coordinator_id, csrf, expires_at, created_at, last_seen_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
).run(sha256(token), coordinatorId, csrf, expiresAt, now, now);
|
||||
return { token, csrf };
|
||||
}
|
||||
|
||||
/** Absolute 14-day expiry. last_seen_at updates, and expires_at does not move. */
|
||||
export function readSession(db: Database.Database, cookieHeader: string | undefined, now: string): CoordinatorSession | null {
|
||||
const token = readCookie(cookieHeader, SESSION_COOKIE);
|
||||
if (!token || !TOKEN_SHAPE.test(token)) return null;
|
||||
const hash = sha256(token);
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT s.csrf AS csrf, s.expires_at AS expires_at, c.id AS id, c.role AS role, c.name AS name, c.active AS active
|
||||
FROM sessions s
|
||||
JOIN coordinators c ON c.id = s.coordinator_id
|
||||
WHERE s.id_hash = ?`,
|
||||
)
|
||||
.get(hash) as
|
||||
| { csrf: string; expires_at: string; id: number; role: string; name: string; active: number }
|
||||
| undefined;
|
||||
if (!row || row.active !== 1 || row.expires_at <= now) return null;
|
||||
if (row.role !== 'admin' && row.role !== 'coordinator') return null;
|
||||
db.prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?').run(now, hash);
|
||||
return { coordinatorId: row.id, role: row.role, csrf: row.csrf, name: row.name };
|
||||
}
|
||||
|
||||
export function revokeSession(db: Database.Database, cookieHeader: string | undefined): void {
|
||||
const token = readCookie(cookieHeader, SESSION_COOKIE);
|
||||
if (!token || !TOKEN_SHAPE.test(token)) return;
|
||||
db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(sha256(token));
|
||||
}
|
||||
|
||||
export function csrfMatches(expected: string, received: string): boolean {
|
||||
if (!TOKEN_SHAPE.test(expected) || !TOKEN_SHAPE.test(received)) return false;
|
||||
const left = Buffer.from(expected);
|
||||
const right = Buffer.from(received);
|
||||
return left.length === right.length && timingSafeEqual(left, right);
|
||||
}
|
||||
|
||||
export function sessionSetCookie(config: CookieConfig, token: string): string {
|
||||
return `${SESSION_COOKIE}=${token}; HttpOnly; SameSite=Lax; Path=${cookiePath(config)}; Max-Age=${SESSION_SECONDS}${secureFlag(config)}`;
|
||||
}
|
||||
|
||||
export function sessionClearCookie(config: CookieConfig): string {
|
||||
return `${SESSION_COOKIE}=; HttpOnly; SameSite=Lax; Path=${cookiePath(config)}; Max-Age=0${secureFlag(config)}`;
|
||||
}
|
||||
|
||||
function secureFlag(config: CookieConfig): string {
|
||||
return config.secureCookies ? '; Secure' : '';
|
||||
}
|
||||
|
||||
function readCookie(header: string | undefined, name: string): string | null {
|
||||
if (!header) return null;
|
||||
for (const part of header.split(';')) {
|
||||
const separator = part.indexOf('=');
|
||||
if (separator === -1) continue;
|
||||
if (part.slice(0, separator).trim() !== name) continue;
|
||||
return part.slice(separator + 1).trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function sha256(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import { todayInZone } from './time.js';
|
||||
|
||||
const WEEKDAY_LONG = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] as const;
|
||||
const MONTH_LONG = [
|
||||
'January',
|
||||
'February',
|
||||
'March',
|
||||
'April',
|
||||
'May',
|
||||
'June',
|
||||
'July',
|
||||
'August',
|
||||
'September',
|
||||
'October',
|
||||
'November',
|
||||
'December',
|
||||
] as const;
|
||||
|
||||
export const WEEKDAY_SHORT = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as const;
|
||||
|
||||
export type CalendarDay = {
|
||||
date: string;
|
||||
day: number;
|
||||
weekday: string;
|
||||
inMonth: boolean;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export type CalendarMonth = {
|
||||
id: string;
|
||||
label: string;
|
||||
weeks: CalendarDay[][];
|
||||
};
|
||||
|
||||
/** Sunday-first month grid. Leading and trailing days belong to the neighboring months. */
|
||||
export function calendarMonth(monthId: string): CalendarMonth {
|
||||
const month = Temporal.PlainYearMonth.from(monthId);
|
||||
const first = month.toPlainDate({ day: 1 });
|
||||
const last = month.toPlainDate({ day: month.daysInMonth });
|
||||
const start = first.subtract({ days: first.dayOfWeek % 7 });
|
||||
const weeks: CalendarDay[][] = [];
|
||||
let cursor = start;
|
||||
while (Temporal.PlainDate.compare(cursor, last) <= 0) {
|
||||
const days: CalendarDay[] = [];
|
||||
for (let index = 0; index < 7; index += 1) {
|
||||
days.push(toCalendarDay(cursor, month));
|
||||
cursor = cursor.add({ days: 1 });
|
||||
}
|
||||
weeks.push(days);
|
||||
}
|
||||
const monthName = MONTH_LONG[month.month - 1];
|
||||
if (!monthName) throw new Error(`${monthId} is not a month.`);
|
||||
return {
|
||||
id: month.toString(),
|
||||
label: `${monthName} ${month.year}`,
|
||||
weeks,
|
||||
};
|
||||
}
|
||||
|
||||
/** Months that contain at least one shift, earliest first. */
|
||||
export function monthsCovering(dates: string[]): string[] {
|
||||
return [...new Set(dates.map((date) => date.slice(0, 7)))].sort();
|
||||
}
|
||||
|
||||
const MONTH_ID = /^\d{4}-\d{2}$/;
|
||||
|
||||
export function parseMonthId(value: string | undefined): string | null {
|
||||
if (!value || !MONTH_ID.test(value)) return null;
|
||||
try {
|
||||
return Temporal.PlainYearMonth.from(value).toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The requested month when it has shifts, otherwise the month of today or the nearest later month. */
|
||||
export function chooseCalendarMonth(requested: string | undefined, dates: string[], today: string): string {
|
||||
const months = monthsCovering(dates);
|
||||
const parsed = parseMonthId(requested);
|
||||
if (parsed && months.includes(parsed)) return parsed;
|
||||
const todayMonth = today.slice(0, 7);
|
||||
if (months.includes(todayMonth)) return todayMonth;
|
||||
return months.find((month) => month >= todayMonth) ?? months.at(-1) ?? todayMonth;
|
||||
}
|
||||
|
||||
export function monthStep(current: string, dates: string[]): { previous: string | null; next: string | null } {
|
||||
const months = monthsCovering(dates);
|
||||
const index = months.indexOf(current);
|
||||
if (index === -1) {
|
||||
return {
|
||||
previous: [...months].reverse().find((month) => month < current) ?? null,
|
||||
next: months.find((month) => month > current) ?? null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
previous: index > 0 ? (months[index - 1] ?? null) : null,
|
||||
next: months[index + 1] ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function calendarToday(timeZone: string, nowUtc: string): string {
|
||||
return todayInZone(timeZone, Temporal.Instant.from(nowUtc));
|
||||
}
|
||||
|
||||
function toCalendarDay(date: Temporal.PlainDate, month: Temporal.PlainYearMonth): CalendarDay {
|
||||
const weekdayName = WEEKDAY_LONG[date.dayOfWeek % 7];
|
||||
const monthName = MONTH_LONG[date.month - 1];
|
||||
if (!weekdayName || !monthName) throw new Error(`${date.toString()} is not a calendar day.`);
|
||||
return {
|
||||
date: date.toString(),
|
||||
day: date.day,
|
||||
weekday: weekdayName,
|
||||
inMonth: date.year === month.year && date.month === month.month,
|
||||
label: `${weekdayName}, ${monthName} ${date.day}, ${date.year}`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
/**
|
||||
* Ties a cancel POST to the manage page we rendered for this link.
|
||||
* Knowing the address is not enough. The field is not a second manage token.
|
||||
*/
|
||||
export function issueCancelToken(secret: string, manageToken: string): string {
|
||||
return createHmac('sha256', secret).update(`hope-cancel-v1\0${manageToken}`).digest('base64url');
|
||||
}
|
||||
|
||||
export function issueSwitchToken(secret: string, manageToken: string): string {
|
||||
return createHmac('sha256', secret).update(`hope-switch-v1\0${manageToken}`).digest('base64url');
|
||||
}
|
||||
|
||||
export function issueReminderPageToken(secret: string, manageToken: string): string {
|
||||
return createHmac('sha256', secret).update(`hope-reminder-page-v1\0${manageToken}`).digest('base64url');
|
||||
}
|
||||
|
||||
export function cancelTokenMatches(secret: string, manageToken: string, received: string): boolean {
|
||||
return tokenMatches(issueCancelToken(secret, manageToken), received);
|
||||
}
|
||||
|
||||
export function switchTokenMatches(secret: string, manageToken: string, received: string): boolean {
|
||||
return tokenMatches(issueSwitchToken(secret, manageToken), received);
|
||||
}
|
||||
|
||||
export function reminderPageTokenMatches(secret: string, manageToken: string, received: string): boolean {
|
||||
return tokenMatches(issueReminderPageToken(secret, manageToken), received);
|
||||
}
|
||||
|
||||
function tokenMatches(expected: string, received: string): boolean {
|
||||
if (!/^[A-Za-z0-9_-]{20,128}$/.test(received)) return false;
|
||||
const left = Buffer.from(expected);
|
||||
const right = Buffer.from(received);
|
||||
return left.length === right.length && timingSafeEqual(left, right);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { isIP } from 'node:net';
|
||||
|
||||
/**
|
||||
* Client IP comes from the TCP peer unless that peer is a configured proxy.
|
||||
* A trusted proxy must replace X-Forwarded-For with one client address.
|
||||
* A list of addresses is ignored, because the left-most value is attacker-controlled
|
||||
* when a proxy appends instead of replacing.
|
||||
*/
|
||||
|
||||
export type TrustProxy = { mode: 'disabled' } | { mode: 'list'; entries: TrustEntry[] };
|
||||
|
||||
export type TrustEntry =
|
||||
| { type: 'loopback' }
|
||||
| { type: 'ipv4'; network: number; bits: number }
|
||||
| { type: 'ipv6'; address: string };
|
||||
|
||||
export function parseTrustProxy(value: string | undefined): TrustProxy {
|
||||
const raw = (value ?? '').trim();
|
||||
if (raw === '' || /^(false|0|no|off)$/i.test(raw)) return { mode: 'disabled' };
|
||||
if (/^(true|1|yes|on)$/i.test(raw)) {
|
||||
throw new Error(
|
||||
'TRUST_PROXY cannot be true. Name the proxy instead, for example loopback or 172.18.0.1.',
|
||||
);
|
||||
}
|
||||
const entries: TrustEntry[] = [];
|
||||
for (const part of raw.split(',')) {
|
||||
const item = part.trim();
|
||||
if (item === '') continue;
|
||||
if (/^loopback$/i.test(item)) {
|
||||
entries.push({ type: 'loopback' });
|
||||
continue;
|
||||
}
|
||||
entries.push(parseAddressOrCidr(item));
|
||||
}
|
||||
if (entries.length === 0) throw new Error('TRUST_PROXY is empty.');
|
||||
return { mode: 'list', entries };
|
||||
}
|
||||
|
||||
export function clientAddress(
|
||||
trust: TrustProxy,
|
||||
remoteAddress: string | null | undefined,
|
||||
forwardedFor: string | null | undefined,
|
||||
): string {
|
||||
const peer = normalizeIp(remoteAddress);
|
||||
if (!peer) return 'unknown';
|
||||
if (trust.mode === 'disabled' || !isTrustedPeer(trust, peer)) return peer;
|
||||
return singleForwardedAddress(forwardedFor) ?? peer;
|
||||
}
|
||||
|
||||
export function normalizeIp(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
let ip = value.trim();
|
||||
if (ip.startsWith('[') && ip.endsWith(']')) ip = ip.slice(1, -1);
|
||||
const zone = ip.indexOf('%');
|
||||
if (zone !== -1) ip = ip.slice(0, zone);
|
||||
const lower = ip.toLowerCase();
|
||||
if (lower.startsWith('::ffff:')) {
|
||||
const mapped = lower.slice('::ffff:'.length);
|
||||
if (isIP(mapped) === 4) return mapped;
|
||||
}
|
||||
if (isIP(ip) === 4) return ip;
|
||||
if (isIP(lower) === 6) return lower;
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseAddressOrCidr(value: string): TrustEntry {
|
||||
if (value.includes(':')) {
|
||||
if (value.includes('/')) {
|
||||
throw new Error(`TRUST_PROXY does not accept an IPv6 range (${value}). Use an exact IPv6 address or loopback.`);
|
||||
}
|
||||
const address = normalizeIp(value);
|
||||
if (!address || isIP(address) !== 6) throw new Error(`TRUST_PROXY has an invalid address: ${value}`);
|
||||
return { type: 'ipv6', address };
|
||||
}
|
||||
const [base, bitsText] = value.split('/');
|
||||
if (!base || value.split('/').length > 2) throw new Error(`TRUST_PROXY has an invalid address: ${value}`);
|
||||
const bits = bitsText === undefined ? 32 : Number(bitsText);
|
||||
if (!Number.isInteger(bits) || bits < 8 || bits > 32) {
|
||||
throw new Error(`TRUST_PROXY prefix for ${value} must be from 8 through 32 so it cannot trust the whole internet.`);
|
||||
}
|
||||
const network = ipv4ToInt(base);
|
||||
if (network === null) throw new Error(`TRUST_PROXY has an invalid address: ${value}`);
|
||||
const mask = (0xffffffff << (32 - bits)) >>> 0;
|
||||
return { type: 'ipv4', network: (network & mask) >>> 0, bits };
|
||||
}
|
||||
|
||||
function isTrustedPeer(trust: Extract<TrustProxy, { mode: 'list' }>, peer: string): boolean {
|
||||
return trust.entries.some((entry) => matchesEntry(entry, peer));
|
||||
}
|
||||
|
||||
function matchesEntry(entry: TrustEntry, peer: string): boolean {
|
||||
if (entry.type === 'loopback') {
|
||||
if (peer === '::1') return true;
|
||||
const value = ipv4ToInt(peer);
|
||||
if (value === null) return false;
|
||||
return (value >>> 24) === 127;
|
||||
}
|
||||
if (entry.type === 'ipv6') return peer === entry.address;
|
||||
const value = ipv4ToInt(peer);
|
||||
if (value === null) return false;
|
||||
const mask = (0xffffffff << (32 - entry.bits)) >>> 0;
|
||||
return ((value & mask) >>> 0) === entry.network;
|
||||
}
|
||||
|
||||
function singleForwardedAddress(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
const parts = value.split(',').map((part) => part.trim()).filter((part) => part !== '');
|
||||
if (parts.length !== 1) return null;
|
||||
return normalizeIp(parts[0]);
|
||||
}
|
||||
|
||||
function ipv4ToInt(ip: string): number | null {
|
||||
if (isIP(ip) !== 4) return null;
|
||||
const parts = ip.split('.').map((part) => Number(part));
|
||||
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return null;
|
||||
const a = parts[0];
|
||||
const b = parts[1];
|
||||
const c = parts[2];
|
||||
const d = parts[3];
|
||||
if (a === undefined || b === undefined || c === undefined || d === undefined) return null;
|
||||
return ((a * 2 ** 24) + (b * 2 ** 16) + (c * 2 ** 8) + d) >>> 0;
|
||||
}
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
import path from 'node:path';
|
||||
import { z } from 'zod';
|
||||
import { parseTrustProxy, type TrustProxy } from './client-ip.js';
|
||||
import { EmailAddressError, normalizeEmail } from './email.js';
|
||||
import { assertValidTimeZone, LocalTimeError } from './time.js';
|
||||
|
||||
/**
|
||||
* All configuration is read here. Production refuses Cloudflare test keys,
|
||||
* console mail, non-https origins, and weak session secrets.
|
||||
*/
|
||||
|
||||
export const DATABASE_FILENAME = 'app.db';
|
||||
|
||||
/** Documented Cloudflare Turnstile test keys. Development and test only. */
|
||||
export const TURNSTILE_TEST_SITE_KEYS = [
|
||||
'1x00000000000000000000AA',
|
||||
'1x00000000000000000000BB',
|
||||
'2x00000000000000000000AB',
|
||||
'2x00000000000000000000BB',
|
||||
'3x00000000000000000000FF',
|
||||
] as const;
|
||||
|
||||
export const TURNSTILE_TEST_SECRET_KEYS = [
|
||||
'1x0000000000000000000000000000000AA',
|
||||
'2x0000000000000000000000000000000AA',
|
||||
'3x0000000000000000000000000000000AA',
|
||||
] as const;
|
||||
|
||||
const TEST_KEY_PATTERN = /^[123]x0{10,}[0-9a-z]*$/i;
|
||||
const WEAK_SECRET_MARKERS = [
|
||||
'change-me',
|
||||
'changeme',
|
||||
'password',
|
||||
'secret',
|
||||
'placeholder',
|
||||
'dev-only',
|
||||
'qwerty',
|
||||
'letmein',
|
||||
];
|
||||
|
||||
export class ConfigError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'ConfigError';
|
||||
}
|
||||
}
|
||||
|
||||
export type MailDriver = 'console' | 'postmark' | 'ses';
|
||||
|
||||
export type AppConfig = {
|
||||
nodeEnv: 'development' | 'test' | 'production';
|
||||
port: number;
|
||||
baseUrl: string;
|
||||
basePath: string;
|
||||
dataDir: string;
|
||||
databaseFile: string;
|
||||
sessionSecret: string;
|
||||
secureCookies: boolean;
|
||||
defaultTimeZone: string;
|
||||
mail: {
|
||||
driver: MailDriver;
|
||||
from: string;
|
||||
replyTo: string;
|
||||
postmarkToken: string | null;
|
||||
ses: { region: string; accessKeyId: string; secretAccessKey: string } | null;
|
||||
};
|
||||
turnstile: { siteKey: string; secretKey: string };
|
||||
brandSrc: string;
|
||||
bootstrapAdminEmail: string;
|
||||
trustProxy: TrustProxy;
|
||||
/** 127.0.0.1 for local development. 0.0.0.0 inside Docker so the published localhost port can connect. */
|
||||
bindHost: '127.0.0.1' | '0.0.0.0';
|
||||
};
|
||||
|
||||
const schema = z.object({
|
||||
NODE_ENV: z.enum(['development', 'test', 'production'], {
|
||||
errorMap: () => ({ message: 'NODE_ENV must be development, test, or production.' }),
|
||||
}),
|
||||
PORT: z.string().regex(/^[0-9]+$/, 'PORT must be a whole number.'),
|
||||
BASE_URL: z.string().min(1, 'BASE_URL is required.'),
|
||||
BASE_PATH: z.string(),
|
||||
DATA_DIR: z.string().min(1, 'DATA_DIR is required.'),
|
||||
SESSION_SECRET: z.string().min(32, 'SESSION_SECRET must be at least 32 characters.'),
|
||||
DEFAULT_TZ: z.string().min(1, 'DEFAULT_TZ is required.'),
|
||||
MAIL_DRIVER: z.enum(['console', 'postmark', 'ses'], {
|
||||
errorMap: () => ({ message: 'MAIL_DRIVER must be console, postmark, or ses.' }),
|
||||
}),
|
||||
MAIL_FROM: z.string().min(1, 'MAIL_FROM is required.'),
|
||||
MAIL_REPLY_TO: z.string().min(1, 'MAIL_REPLY_TO is required.'),
|
||||
POSTMARK_TOKEN: z.string(),
|
||||
SES_REGION: z.string(),
|
||||
SES_ACCESS_KEY_ID: z.string(),
|
||||
SES_SECRET_ACCESS_KEY: z.string(),
|
||||
TURNSTILE_SITE_KEY: z.string().min(1, 'TURNSTILE_SITE_KEY is required.'),
|
||||
TURNSTILE_SECRET_KEY: z.string().min(1, 'TURNSTILE_SECRET_KEY is required.'),
|
||||
BRAND_SRC: z.string().min(1, 'BRAND_SRC is required.'),
|
||||
BOOTSTRAP_ADMIN_EMAIL: z.string().min(1, 'BOOTSTRAP_ADMIN_EMAIL is required.'),
|
||||
TRUST_PROXY: z.string(),
|
||||
BIND_HOST: z.string(),
|
||||
});
|
||||
|
||||
export function isTurnstileTestKey(value: string): boolean {
|
||||
return (
|
||||
TURNSTILE_TEST_SITE_KEYS.some((key) => key === value) ||
|
||||
TURNSTILE_TEST_SECRET_KEYS.some((key) => key === value) ||
|
||||
TEST_KEY_PATTERN.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
|
||||
const parsed = schema.safeParse({
|
||||
NODE_ENV: blank(env.NODE_ENV),
|
||||
PORT: blank(env.PORT) ?? '3000',
|
||||
BASE_URL: blank(env.BASE_URL),
|
||||
BASE_PATH: (env.BASE_PATH ?? '').trim(),
|
||||
DATA_DIR: blank(env.DATA_DIR) ?? '/data',
|
||||
SESSION_SECRET: (env.SESSION_SECRET ?? '').trim(),
|
||||
DEFAULT_TZ: blank(env.DEFAULT_TZ) ?? 'America/Chicago',
|
||||
MAIL_DRIVER: blank(env.MAIL_DRIVER),
|
||||
MAIL_FROM: blank(env.MAIL_FROM),
|
||||
MAIL_REPLY_TO: blank(env.MAIL_REPLY_TO),
|
||||
POSTMARK_TOKEN: (env.POSTMARK_TOKEN ?? '').trim(),
|
||||
SES_REGION: (env.SES_REGION ?? '').trim(),
|
||||
SES_ACCESS_KEY_ID: (env.SES_ACCESS_KEY_ID ?? '').trim(),
|
||||
SES_SECRET_ACCESS_KEY: (env.SES_SECRET_ACCESS_KEY ?? '').trim(),
|
||||
TURNSTILE_SITE_KEY: blank(env.TURNSTILE_SITE_KEY),
|
||||
TURNSTILE_SECRET_KEY: blank(env.TURNSTILE_SECRET_KEY),
|
||||
BRAND_SRC: blank(env.BRAND_SRC) ?? '../Hope Food Pantry Website/brand',
|
||||
BOOTSTRAP_ADMIN_EMAIL: blank(env.BOOTSTRAP_ADMIN_EMAIL),
|
||||
TRUST_PROXY: blank(env.TRUST_PROXY) ?? 'false',
|
||||
BIND_HOST: blank(env.BIND_HOST) ?? '127.0.0.1',
|
||||
});
|
||||
if (!parsed.success) {
|
||||
throw new ConfigError(formatProblems(parsed.error.issues.map((issue) => issue.message)));
|
||||
}
|
||||
const input = parsed.data;
|
||||
const problems: string[] = [];
|
||||
const port = Number(input.PORT);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
problems.push('PORT must be from 1 through 65535.');
|
||||
}
|
||||
const baseUrl = normalizeBaseUrl(input.BASE_URL, input.NODE_ENV, problems);
|
||||
const basePath = normalizeBasePath(input.BASE_PATH, problems);
|
||||
const dataDir = path.resolve(input.DATA_DIR);
|
||||
if (dataDir === path.parse(dataDir).root) {
|
||||
problems.push('DATA_DIR must be a directory for this app, not the filesystem root.');
|
||||
}
|
||||
let defaultTimeZone = input.DEFAULT_TZ;
|
||||
try {
|
||||
defaultTimeZone = assertValidTimeZone(input.DEFAULT_TZ);
|
||||
} catch (err) {
|
||||
problems.push(err instanceof LocalTimeError ? err.message : 'DEFAULT_TZ is not a recognized IANA time zone.');
|
||||
}
|
||||
const sessionProblems = sessionSecretProblems(input.SESSION_SECRET, input.NODE_ENV);
|
||||
problems.push(...sessionProblems);
|
||||
const from = parseFrom(input.MAIL_FROM, problems);
|
||||
const replyTo = parseReplyTo(input.MAIL_REPLY_TO, problems);
|
||||
const mail = resolveMail(input, problems);
|
||||
// TODO(D5): Production must use the real Turnstile keys for the public hostname.
|
||||
if (input.NODE_ENV === 'production' && isTurnstileTestKey(input.TURNSTILE_SITE_KEY)) {
|
||||
problems.push('TURNSTILE_SITE_KEY is a Cloudflare test key. Production requires the real site key for the pantry hostname.');
|
||||
}
|
||||
if (input.NODE_ENV === 'production' && isTurnstileTestKey(input.TURNSTILE_SECRET_KEY)) {
|
||||
problems.push('TURNSTILE_SECRET_KEY is a Cloudflare test key. Production requires the real secret key for the pantry hostname.');
|
||||
}
|
||||
if (input.TURNSTILE_SITE_KEY.length < 20 || input.TURNSTILE_SECRET_KEY.length < 20) {
|
||||
problems.push('TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY do not look like Turnstile keys.');
|
||||
}
|
||||
let bootstrapAdminEmail = '';
|
||||
try {
|
||||
// TODO(D4): Validated only. This step does not create the administrator account.
|
||||
bootstrapAdminEmail = normalizeEmail(input.BOOTSTRAP_ADMIN_EMAIL);
|
||||
} catch (err) {
|
||||
problems.push(err instanceof EmailAddressError ? 'BOOTSTRAP_ADMIN_EMAIL must be an email address.' : 'BOOTSTRAP_ADMIN_EMAIL is invalid.');
|
||||
}
|
||||
let trustProxy: TrustProxy = { mode: 'disabled' };
|
||||
try {
|
||||
trustProxy = parseTrustProxy(input.TRUST_PROXY);
|
||||
} catch (err) {
|
||||
problems.push(err instanceof Error ? err.message : 'TRUST_PROXY is invalid.');
|
||||
}
|
||||
if (input.BIND_HOST !== '127.0.0.1' && input.BIND_HOST !== '0.0.0.0') {
|
||||
problems.push('BIND_HOST must be 127.0.0.1 or 0.0.0.0.');
|
||||
}
|
||||
if (problems.length > 0 || !baseUrl || basePath === null || !from || !replyTo || !mail) {
|
||||
throw new ConfigError(formatProblems(problems));
|
||||
}
|
||||
return {
|
||||
nodeEnv: input.NODE_ENV,
|
||||
port,
|
||||
baseUrl: baseUrl.origin,
|
||||
basePath,
|
||||
dataDir,
|
||||
databaseFile: path.join(dataDir, DATABASE_FILENAME),
|
||||
sessionSecret: input.SESSION_SECRET,
|
||||
secureCookies: baseUrl.secure,
|
||||
defaultTimeZone,
|
||||
mail: {
|
||||
driver: input.MAIL_DRIVER,
|
||||
from,
|
||||
replyTo,
|
||||
postmarkToken: mail.postmarkToken,
|
||||
ses: mail.ses,
|
||||
},
|
||||
turnstile: {
|
||||
siteKey: input.TURNSTILE_SITE_KEY,
|
||||
secretKey: input.TURNSTILE_SECRET_KEY,
|
||||
},
|
||||
brandSrc: input.BRAND_SRC,
|
||||
bootstrapAdminEmail,
|
||||
trustProxy,
|
||||
bindHost: input.BIND_HOST === '0.0.0.0' ? '0.0.0.0' : '127.0.0.1',
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(
|
||||
value: string,
|
||||
nodeEnv: 'development' | 'test' | 'production',
|
||||
problems: string[],
|
||||
): { origin: string; secure: boolean } | null {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
problems.push('BASE_URL must be an absolute origin, such as http://127.0.0.1:3000 or https://example.org.');
|
||||
return null;
|
||||
}
|
||||
if (url.username || url.password) problems.push('BASE_URL must not include a username or password.');
|
||||
if (url.search || url.hash) problems.push('BASE_URL must not include a query or hash.');
|
||||
if (url.pathname !== '/' && url.pathname !== '') {
|
||||
problems.push('BASE_URL is the public origin only. Put a mount prefix such as /volunteer in BASE_PATH.');
|
||||
}
|
||||
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
||||
problems.push('BASE_URL must start with http:// or https://.');
|
||||
return null;
|
||||
}
|
||||
const host = url.hostname.toLowerCase();
|
||||
if (nodeEnv === 'production') {
|
||||
if (url.protocol !== 'https:') problems.push('Production BASE_URL must use https.');
|
||||
if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.local') || !host.includes('.')) {
|
||||
problems.push('Production BASE_URL must be the public hostname, not a local address.');
|
||||
}
|
||||
}
|
||||
return { origin: url.origin, secure: url.protocol === 'https:' };
|
||||
}
|
||||
|
||||
function normalizeBasePath(input: string, problems: string[]): string | null {
|
||||
const trimmed = input.trim();
|
||||
if (trimmed === '' || trimmed === '/') return '';
|
||||
let value = trimmed;
|
||||
if (value.endsWith('/')) value = value.slice(0, -1);
|
||||
if (!value.startsWith('/')) {
|
||||
problems.push('BASE_PATH must start with /, or be empty.');
|
||||
return null;
|
||||
}
|
||||
if (value.includes('//') || value.includes('\\') || value.includes('?') || value.includes('#') || value.includes('..')) {
|
||||
problems.push('BASE_PATH must be a simple prefix such as /volunteer.');
|
||||
return null;
|
||||
}
|
||||
if (!/^\/(?:[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*)$/.test(value)) {
|
||||
problems.push('BASE_PATH must be a simple prefix such as /volunteer.');
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function sessionSecretProblems(secret: string, nodeEnv: 'development' | 'test' | 'production'): string[] {
|
||||
if (nodeEnv !== 'production') return [];
|
||||
const problems: string[] = [];
|
||||
const lower = secret.toLowerCase();
|
||||
if (WEAK_SECRET_MARKERS.some((marker) => lower.includes(marker))) {
|
||||
problems.push(
|
||||
'SESSION_SECRET looks like a placeholder. Generate a random one with: node -e "console.log(require(\'crypto\').randomBytes(32).toString(\'base64url\'))"',
|
||||
);
|
||||
}
|
||||
if (new Set(secret).size < 16) {
|
||||
problems.push('SESSION_SECRET does not look random enough for production.');
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
function parseFrom(value: string, problems: string[]): string | null {
|
||||
if (/[\r\n]/.test(value)) {
|
||||
problems.push('MAIL_FROM must not contain a line break.');
|
||||
return null;
|
||||
}
|
||||
const named = /^(.*?)<\s*([^>]+)\s*>\s*$/.exec(value.trim());
|
||||
try {
|
||||
if (!named) return normalizeEmail(value);
|
||||
const display = (named[1] ?? '').trim().replace(/^"|"$/g, '');
|
||||
const address = normalizeEmail(named[2] ?? '');
|
||||
if (/[<>]/.test(display)) {
|
||||
problems.push('MAIL_FROM has an invalid display name.');
|
||||
return null;
|
||||
}
|
||||
return display === '' ? address : `${display} <${address}>`;
|
||||
} catch {
|
||||
problems.push('MAIL_FROM must be an email address, or a name and address such as Hope Food Pantry <volunteer@example.org>.');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseReplyTo(value: string, problems: string[]): string | null {
|
||||
if (value.includes('<') || value.includes('>')) {
|
||||
problems.push('MAIL_REPLY_TO must be an email address without a display name.');
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return normalizeEmail(value);
|
||||
} catch {
|
||||
problems.push('MAIL_REPLY_TO must be an email address.');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveMail(
|
||||
input: z.infer<typeof schema>,
|
||||
problems: string[],
|
||||
): { postmarkToken: string | null; ses: AppConfig['mail']['ses'] } | null {
|
||||
// TODO(D1): The pantry chooses the provider and verifies the sender and reply-to before real mail is enabled.
|
||||
if (input.NODE_ENV === 'production' && input.MAIL_DRIVER === 'console') {
|
||||
problems.push('MAIL_DRIVER=console is only for development. Choose postmark or ses after the pantry confirms the email provider.');
|
||||
}
|
||||
if (input.MAIL_DRIVER === 'postmark') {
|
||||
const token = requireCredential(input.POSTMARK_TOKEN, 'POSTMARK_TOKEN', problems);
|
||||
if (!token) return null;
|
||||
return { postmarkToken: token, ses: null };
|
||||
}
|
||||
if (input.MAIL_DRIVER === 'ses') {
|
||||
if (!/^[a-z]{2}-[a-z]+-\d+$/.test(input.SES_REGION)) {
|
||||
problems.push('SES_REGION must look like us-east-1.');
|
||||
}
|
||||
const accessKeyId = requireCredential(input.SES_ACCESS_KEY_ID, 'SES_ACCESS_KEY_ID', problems);
|
||||
const secretAccessKey = requireCredential(input.SES_SECRET_ACCESS_KEY, 'SES_SECRET_ACCESS_KEY', problems);
|
||||
if (!accessKeyId || !secretAccessKey || !/^[a-z]{2}-[a-z]+-\d+$/.test(input.SES_REGION)) return null;
|
||||
return {
|
||||
postmarkToken: null,
|
||||
ses: { region: input.SES_REGION, accessKeyId, secretAccessKey },
|
||||
};
|
||||
}
|
||||
return { postmarkToken: null, ses: null };
|
||||
}
|
||||
|
||||
function requireCredential(value: string, label: string, problems: string[]): string | null {
|
||||
if (value === '') {
|
||||
problems.push(`${label} is required for the selected mail driver.`);
|
||||
return null;
|
||||
}
|
||||
if (/^(change-me|changeme|placeholder|secret|token|password|example)$/i.test(value)) {
|
||||
problems.push(`${label} is still a placeholder.`);
|
||||
return null;
|
||||
}
|
||||
if (value.length < 16) {
|
||||
problems.push(`${label} is too short.`);
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function formatProblems(problems: string[]): string {
|
||||
const unique = [...new Set(problems.filter((problem) => problem.trim() !== ''))];
|
||||
return `Configuration is invalid:\n- ${unique.join('\n- ')}`;
|
||||
}
|
||||
|
||||
function blank(value: string | undefined): string | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed === '' ? undefined : trimmed;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
||||
|
||||
const COOKIE = 'hope_confirm';
|
||||
const MAX_AGE_SECONDS = 900;
|
||||
|
||||
export type ConfirmationSeal = {
|
||||
signupId: number;
|
||||
shiftId: number;
|
||||
token: string;
|
||||
expiresAtMs: number;
|
||||
};
|
||||
|
||||
export function sealConfirmation(secret: string, payload: ConfirmationSeal): string {
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv('aes-256-gcm', cookieKey(secret), iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(payload), 'utf8'), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return Buffer.concat([iv, tag, ciphertext]).toString('base64url');
|
||||
}
|
||||
|
||||
export function openConfirmation(secret: string, cookieHeader: string | undefined, nowMs: number): ConfirmationSeal | null {
|
||||
const raw = readCookie(cookieHeader, COOKIE);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const bytes = Buffer.from(raw, 'base64url');
|
||||
if (bytes.length < 12 + 16 + 2) return null;
|
||||
const iv = bytes.subarray(0, 12);
|
||||
const tag = bytes.subarray(12, 28);
|
||||
const ciphertext = bytes.subarray(28);
|
||||
const decipher = createDecipheriv('aes-256-gcm', cookieKey(secret), iv);
|
||||
decipher.setAuthTag(tag);
|
||||
const json = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
|
||||
const parsed = JSON.parse(json) as Partial<ConfirmationSeal>;
|
||||
if (!parsed || typeof parsed.signupId !== 'number' || typeof parsed.shiftId !== 'number') return null;
|
||||
if (typeof parsed.token !== 'string' || typeof parsed.expiresAtMs !== 'number') return null;
|
||||
if (parsed.expiresAtMs <= nowMs) return null;
|
||||
return {
|
||||
signupId: parsed.signupId,
|
||||
shiftId: parsed.shiftId,
|
||||
token: parsed.token,
|
||||
expiresAtMs: parsed.expiresAtMs,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function confirmationCookie(value: string, path: string, secure: boolean): string {
|
||||
const parts = [
|
||||
`${COOKIE}=${value}`,
|
||||
'HttpOnly',
|
||||
'SameSite=Lax',
|
||||
`Path=${path}`,
|
||||
`Max-Age=${MAX_AGE_SECONDS}`,
|
||||
];
|
||||
if (secure) parts.push('Secure');
|
||||
return parts.join('; ');
|
||||
}
|
||||
|
||||
function cookieKey(secret: string): Buffer {
|
||||
return createHash('sha256').update(`hope-confirm-v1\0${secret}`).digest();
|
||||
}
|
||||
|
||||
function readCookie(header: string | undefined, name: string): string | null {
|
||||
if (!header) return null;
|
||||
for (const part of header.split(';')) {
|
||||
const separator = part.indexOf('=');
|
||||
if (separator === -1) continue;
|
||||
if (part.slice(0, separator).trim() === name) return part.slice(separator + 1).trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs';
|
||||
import { mkdir, rm } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import Database from 'better-sqlite3';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { nowUtc } from './time.js';
|
||||
|
||||
const MIGRATION_NAME = /^(\d{3,})_[a-z0-9_]+\.sql$/;
|
||||
|
||||
export class MigrationError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'MigrationError';
|
||||
}
|
||||
}
|
||||
|
||||
export type ApplyMigrationsOptions = {
|
||||
migrationsDir: string;
|
||||
now?: string;
|
||||
backupBeforePending?: () => Promise<void>;
|
||||
};
|
||||
|
||||
export function defaultMigrationsDir(): string {
|
||||
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../migrations');
|
||||
}
|
||||
|
||||
export function configureConnection(db: Database.Database): void {
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
db.pragma('busy_timeout = 5000');
|
||||
}
|
||||
|
||||
export function openDatabaseFile(file: string): Database.Database {
|
||||
try {
|
||||
mkdirSync(path.dirname(file), { recursive: true });
|
||||
} catch (err) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. Could not create the data directory ${path.dirname(file)}. ${messageOf(err)}`,
|
||||
);
|
||||
}
|
||||
const db = new Database(file);
|
||||
configureConnection(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
export async function openAppDatabase(
|
||||
config: AppConfig,
|
||||
options?: { migrationsDir?: string },
|
||||
): Promise<Database.Database> {
|
||||
const db = openDatabaseFile(config.databaseFile);
|
||||
try {
|
||||
await applyMigrations(db, {
|
||||
migrationsDir: options?.migrationsDir ?? defaultMigrationsDir(),
|
||||
backupBeforePending:
|
||||
config.nodeEnv === 'production' ? () => backupBeforeProductionMigration(db, config.dataDir) : undefined,
|
||||
});
|
||||
const quick = db.pragma('quick_check', { simple: true });
|
||||
if (quick !== 'ok') {
|
||||
throw new MigrationError(`Startup aborted. Database integrity check failed: ${String(quick)}`);
|
||||
}
|
||||
return db;
|
||||
} catch (err) {
|
||||
db.close();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function backupDatabase(db: Database.Database, destination: string): Promise<void> {
|
||||
await mkdir(path.dirname(destination), { recursive: true });
|
||||
try {
|
||||
await db.backup(destination);
|
||||
const check = new Database(destination);
|
||||
try {
|
||||
check.pragma('wal_checkpoint(TRUNCATE)');
|
||||
const mode = check.pragma('journal_mode = DELETE', { simple: true });
|
||||
if (mode !== 'delete') throw new Error(`journal mode stayed ${String(mode)}`);
|
||||
const result = check.pragma('integrity_check', { simple: true });
|
||||
if (result !== 'ok') throw new Error(`integrity check returned ${String(result)}`);
|
||||
} finally {
|
||||
check.close();
|
||||
}
|
||||
await rm(`${destination}-wal`, { force: true });
|
||||
await rm(`${destination}-shm`, { force: true });
|
||||
} catch (err) {
|
||||
await rm(destination, { force: true });
|
||||
await rm(`${destination}-wal`, { force: true });
|
||||
await rm(`${destination}-shm`, { force: true });
|
||||
throw new Error(`Backup ${destination} failed. ${messageOf(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyMigrations(
|
||||
db: Database.Database,
|
||||
options: ApplyMigrationsOptions,
|
||||
): Promise<{ applied: string[] }> {
|
||||
const foreignKeys = Number(db.pragma('foreign_keys', { simple: true }));
|
||||
if (foreignKeys !== 1) {
|
||||
throw new MigrationError('Startup aborted. foreign_keys must be ON before migrations run.');
|
||||
}
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
name TEXT PRIMARY KEY,
|
||||
checksum TEXT NOT NULL,
|
||||
applied_at TEXT NOT NULL
|
||||
)`);
|
||||
const files = listMigrationFiles(options.migrationsDir);
|
||||
verifyAppliedChecksums(db, files, options.migrationsDir);
|
||||
const appliedNames = new Set(
|
||||
(db.prepare('SELECT name FROM schema_migrations').all() as { name: string }[]).map((row) => row.name),
|
||||
);
|
||||
const pending = files.filter((file) => !appliedNames.has(file.name));
|
||||
// A brand-new database has nothing to preserve. Later production migrations
|
||||
// snapshot the existing file before any new SQL runs.
|
||||
if (pending.length > 0 && appliedNames.size > 0 && options.backupBeforePending) {
|
||||
try {
|
||||
await options.backupBeforePending();
|
||||
} catch (err) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. The database was not migrated because the pre-migration backup failed. ${messageOf(err)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const applied: string[] = [];
|
||||
for (const file of pending) {
|
||||
const apply = db.transaction(() => {
|
||||
db.exec(file.sql);
|
||||
db.prepare('INSERT INTO schema_migrations (name, checksum, applied_at) VALUES (?, ?, ?)').run(
|
||||
file.name,
|
||||
file.checksum,
|
||||
options.now ?? nowUtc(),
|
||||
);
|
||||
});
|
||||
try {
|
||||
apply();
|
||||
} catch (err) {
|
||||
throw new MigrationError(`Startup aborted. Migration ${file.name} failed: ${messageOf(err)}`);
|
||||
}
|
||||
applied.push(file.name);
|
||||
}
|
||||
return { applied };
|
||||
}
|
||||
|
||||
async function backupBeforeProductionMigration(db: Database.Database, dataDir: string): Promise<void> {
|
||||
const destination = path.join(dataDir, 'backups', `pre-migrate-${backupStamp()}.db`);
|
||||
await backupDatabase(db, destination);
|
||||
}
|
||||
|
||||
function backupStamp(now = nowUtc()): string {
|
||||
return now.replace(/[-:]/g, '').replace('.', '');
|
||||
}
|
||||
|
||||
type MigrationFile = { name: string; sql: string; checksum: string };
|
||||
|
||||
function listMigrationFiles(migrationsDir: string): MigrationFile[] {
|
||||
if (!existsSync(migrationsDir)) {
|
||||
throw new MigrationError(`Startup aborted. Migrations directory is missing: ${migrationsDir}`);
|
||||
}
|
||||
const names = readdirSync(migrationsDir).filter((name) => name !== '.gitkeep');
|
||||
const files: MigrationFile[] = [];
|
||||
const numbers = new Map<string, string>();
|
||||
for (const name of names) {
|
||||
const match = MIGRATION_NAME.exec(name);
|
||||
if (!match) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. ${name} is not a numbered migration. Use a name like 002_description.sql.`,
|
||||
);
|
||||
}
|
||||
const number = match[1];
|
||||
if (!number) throw new MigrationError(`Startup aborted. Could not read the migration number in ${name}.`);
|
||||
const previous = numbers.get(number);
|
||||
if (previous) {
|
||||
throw new MigrationError(`Startup aborted. Duplicate migration number ${number} on ${previous} and ${name}.`);
|
||||
}
|
||||
numbers.set(number, name);
|
||||
const full = path.join(migrationsDir, name);
|
||||
const bytes = readFileSync(full);
|
||||
const sql = bytes.toString('utf8');
|
||||
if (/^\s*(BEGIN|COMMIT|ROLLBACK|PRAGMA)\b/im.test(sql)) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. ${name} must not contain BEGIN, COMMIT, ROLLBACK, or PRAGMA. The runner handles those.`,
|
||||
);
|
||||
}
|
||||
files.push({
|
||||
name,
|
||||
sql,
|
||||
checksum: createHash('sha256').update(bytes).digest('hex'),
|
||||
});
|
||||
}
|
||||
files.sort((a, b) => {
|
||||
const aNumber = Number(MIGRATION_NAME.exec(a.name)?.[1] ?? 0);
|
||||
const bNumber = Number(MIGRATION_NAME.exec(b.name)?.[1] ?? 0);
|
||||
return aNumber - bNumber || a.name.localeCompare(b.name);
|
||||
});
|
||||
return files;
|
||||
}
|
||||
|
||||
function verifyAppliedChecksums(db: Database.Database, files: MigrationFile[], migrationsDir: string): void {
|
||||
const byName = new Map(files.map((file) => [file.name, file]));
|
||||
const applied = db.prepare('SELECT name, checksum FROM schema_migrations').all() as {
|
||||
name: string;
|
||||
checksum: string;
|
||||
}[];
|
||||
for (const row of applied) {
|
||||
const file = byName.get(row.name);
|
||||
if (!file) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. The database has applied ${row.name}, but that file is missing from ${migrationsDir}.`,
|
||||
);
|
||||
}
|
||||
if (file.checksum !== row.checksum) {
|
||||
throw new MigrationError(
|
||||
`Startup aborted. ${row.name} changed after it was applied. Add a new numbered migration instead of editing an applied file.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function messageOf(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { openAppDatabase } from '../db.js';
|
||||
import { normalizeEmail } from '../email.js';
|
||||
import { loadConfig } from '../config.js';
|
||||
import {
|
||||
addLocalDays,
|
||||
localShiftToUtc,
|
||||
nowUtc,
|
||||
todayInZone,
|
||||
weekdayIndex,
|
||||
} from '../time.js';
|
||||
|
||||
export const SEED_EMAIL_DOMAIN = 'example.invalid';
|
||||
|
||||
export type SeedResult = {
|
||||
eventId: number;
|
||||
slug: string;
|
||||
templateId: number;
|
||||
shiftIds: number[];
|
||||
signupIds: number[];
|
||||
};
|
||||
|
||||
export function assertDevelopmentSeed(env: NodeJS.ProcessEnv): void {
|
||||
if (env.NODE_ENV === 'production') {
|
||||
throw new Error(
|
||||
'Refusing to seed because NODE_ENV=production. Seed data is fake and is only for local development.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function seedDevelopment(
|
||||
db: Database.Database,
|
||||
config: AppConfig,
|
||||
options?: { today?: string },
|
||||
): SeedResult {
|
||||
if (config.nodeEnv === 'production') {
|
||||
throw new Error(
|
||||
'Refusing to seed because NODE_ENV=production. Seed data is fake and is only for local development.',
|
||||
);
|
||||
}
|
||||
const existing = db.prepare('SELECT COUNT(*) AS n FROM events').get() as { n: number };
|
||||
if (existing.n > 0) {
|
||||
throw new Error(
|
||||
'Refusing to seed because this database already has events. Delete the development database file if you want a fresh seed.',
|
||||
);
|
||||
}
|
||||
|
||||
const timeZone = config.defaultTimeZone;
|
||||
const today = options?.today ?? todayInZone(timeZone);
|
||||
const createdAt = nowUtc();
|
||||
const weekday = weekdayIndex(today, timeZone);
|
||||
const shiftDates = [1, 3, 6].map((days) => addLocalDays(today, days));
|
||||
const roles = ['Sorting', 'Distribution', 'Intake'] as const;
|
||||
const capacities = [3, 4, 2] as const;
|
||||
|
||||
const insert = db.transaction((): SeedResult => {
|
||||
const event = db
|
||||
.prepare(
|
||||
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
|
||||
VALUES ('weekly-pantry', 'Weekly pantry', '', '', ?, 1, ?)`,
|
||||
)
|
||||
.run(timeZone, createdAt);
|
||||
const eventId = insertId(event);
|
||||
const template = db
|
||||
.prepare(
|
||||
`INSERT INTO shift_templates (
|
||||
event_id, role, weekday, start_local, end_local, capacity, starts_on, ends_on, active, revision
|
||||
) VALUES (?, 'Sorting', ?, '09:00', '12:00', 6, ?, NULL, 1, 1)`,
|
||||
)
|
||||
.run(eventId, weekday, today);
|
||||
const templateId = insertId(template);
|
||||
const shiftIds: number[] = [];
|
||||
for (let index = 0; index < shiftDates.length; index += 1) {
|
||||
const date = shiftDates[index];
|
||||
const role = roles[index];
|
||||
const capacity = capacities[index];
|
||||
if (!date || !role || !capacity) throw new Error('Seed shift list is incomplete.');
|
||||
const times = localShiftToUtc(date, '09:00', '12:00', timeZone);
|
||||
const shift = db
|
||||
.prepare(
|
||||
`INSERT INTO shifts (
|
||||
event_id, template_id, occurrence_date, template_revision, role,
|
||||
starts_at_utc, ends_at_utc, capacity, notes, cancelled, manually_modified, version
|
||||
) VALUES (?, NULL, NULL, NULL, ?, ?, ?, ?, 'Development seed. Not a real pantry shift.', 0, 0, 1)`,
|
||||
)
|
||||
.run(eventId, role, times.startsAtUtc, times.endsAtUtc, capacity);
|
||||
shiftIds.push(insertId(shift));
|
||||
}
|
||||
const firstShift = shiftIds[0];
|
||||
if (firstShift === undefined) throw new Error('Seed did not create a shift.');
|
||||
const signupIds = insertFakeSignups(db, firstShift, createdAt);
|
||||
return { eventId, slug: 'weekly-pantry', templateId, shiftIds, signupIds };
|
||||
});
|
||||
return insert();
|
||||
}
|
||||
|
||||
export async function runSeedCli(env: NodeJS.ProcessEnv = process.env): Promise<void> {
|
||||
assertDevelopmentSeed(env);
|
||||
const config = loadConfig(env);
|
||||
const db = await openAppDatabase(config);
|
||||
try {
|
||||
const result = seedDevelopment(db, config);
|
||||
console.log('Seeded fake development data.');
|
||||
console.log(`Database: ${config.databaseFile}`);
|
||||
console.log(
|
||||
`Event ${result.slug}: ${result.shiftIds.length} one-off shifts and ${result.signupIds.length} fake signups.`,
|
||||
);
|
||||
console.log('Each signup is one person. Another person can use the same email. Group size is fixed at 1.');
|
||||
console.log('The weekly template is stored. Starting the app adds its shifts for the next eight weeks.');
|
||||
console.log('No coordinator account was created.');
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
function insertFakeSignups(db: Database.Database, shiftId: number, createdAt: string): number[] {
|
||||
// TODO(D2): These rows are individual signups. Do not invent group reservations here.
|
||||
// TODO(D4): Seed data does not create coordinator accounts.
|
||||
const people = [
|
||||
{
|
||||
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}`,
|
||||
notes: null,
|
||||
status: 'confirmed',
|
||||
},
|
||||
{
|
||||
name: 'Fake Volunteer Cam',
|
||||
email: `cam.fake@${SEED_EMAIL_DOMAIN}`,
|
||||
phone: null,
|
||||
isMinor: 0,
|
||||
guardianName: null,
|
||||
guardianEmail: null,
|
||||
notes: null,
|
||||
status: 'cancelled',
|
||||
},
|
||||
];
|
||||
const statement = db.prepare(
|
||||
`INSERT INTO signups (
|
||||
shift_id, name, email, email_norm, phone, is_minor, guardian_name, guardian_email,
|
||||
group_size, notes, status, manage_token_hash, token_expires_at, reminders_off,
|
||||
attended, created_at, updated_at, anonymized_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, NULL, NULL, 0, NULL, ?, ?, NULL)`,
|
||||
);
|
||||
return people.map((person) =>
|
||||
insertId(
|
||||
statement.run(
|
||||
shiftId,
|
||||
person.name,
|
||||
person.email,
|
||||
normalizeEmail(person.email),
|
||||
person.phone,
|
||||
person.isMinor,
|
||||
person.guardianName,
|
||||
person.guardianEmail,
|
||||
person.notes,
|
||||
person.status,
|
||||
createdAt,
|
||||
createdAt,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function insertId(result: { lastInsertRowid: number | bigint }): number {
|
||||
return Number(result.lastInsertRowid);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export class EmailAddressError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'EmailAddressError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Trim, Unicode normalize, and lowercase. Dots and plus-tags are kept. */
|
||||
export function normalizeEmail(input: string): string {
|
||||
const normalized = input.normalize('NFC').trim().toLowerCase();
|
||||
if (
|
||||
normalized.length === 0 ||
|
||||
/\s/.test(normalized) ||
|
||||
!normalized.includes('@') ||
|
||||
normalized.startsWith('@') ||
|
||||
normalized.endsWith('@')
|
||||
) {
|
||||
throw new EmailAddressError('Enter an email address.');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { formatInstantInZone } from './time.js';
|
||||
|
||||
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
const MAX_RANGE_DAYS = 366;
|
||||
const FORMULA = /^[\s\u0000-\u001F\u007F]*[=+\-@]/;
|
||||
|
||||
const COLUMNS = [
|
||||
'Date',
|
||||
'Start',
|
||||
'End',
|
||||
'Time zone',
|
||||
'Role',
|
||||
'Name',
|
||||
'Email',
|
||||
'Phone',
|
||||
'Group size',
|
||||
'Minor',
|
||||
'Guardian name',
|
||||
'Guardian email',
|
||||
'Notes',
|
||||
'Status',
|
||||
'Attended',
|
||||
] as const;
|
||||
|
||||
export type RosterExport = { csv: string; rows: number };
|
||||
|
||||
type RosterRecord = {
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
tz: string;
|
||||
role: string;
|
||||
name: string | null;
|
||||
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;
|
||||
anonymized_at: string | null;
|
||||
};
|
||||
|
||||
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
|
||||
JOIN events e ON e.id = s.event_id`;
|
||||
|
||||
/** A spreadsheet cell that would otherwise be a formula is prefixed so it stays text. */
|
||||
export function csvCell(value: string): string {
|
||||
const safe = FORMULA.test(value) ? `'${value}` : value;
|
||||
if (/[",\r\n]/.test(safe)) return `"${safe.replaceAll('"', '""')}"`;
|
||||
return safe;
|
||||
}
|
||||
|
||||
export function exportShiftRoster(db: Database.Database, shiftId: number): RosterExport | null {
|
||||
const shift = db.prepare('SELECT id FROM shifts WHERE id = ?').get(shiftId);
|
||||
if (!shift) return null;
|
||||
const rows = db
|
||||
.prepare(`${ROSTER_SQL} WHERE s.id = ? ORDER BY su.id`)
|
||||
.all(shiftId) as RosterRecord[];
|
||||
return renderRoster(rows);
|
||||
}
|
||||
|
||||
export function exportEventRoster(db: Database.Database, eventId: number): RosterExport | null {
|
||||
const event = db.prepare('SELECT id FROM events WHERE id = ?').get(eventId);
|
||||
if (!event) return null;
|
||||
const rows = db
|
||||
.prepare(`${ROSTER_SQL} WHERE e.id = ? ORDER BY s.starts_at_utc, s.id, su.id`)
|
||||
.all(eventId) as RosterRecord[];
|
||||
return renderRoster(rows);
|
||||
}
|
||||
|
||||
export function exportDateRange(
|
||||
db: Database.Database,
|
||||
from: string,
|
||||
to: string,
|
||||
): { ok: true; export: RosterExport } | { ok: false; error: string } {
|
||||
const start = parseDate(from);
|
||||
const end = parseDate(to);
|
||||
if (!start || !end) return { ok: false, error: 'Use real dates.' };
|
||||
if (Temporal.PlainDate.compare(end, start) < 0) return { ok: false, error: 'The end date is before the start date.' };
|
||||
if (start.until(end, { largestUnit: 'days' }).days > MAX_RANGE_DAYS) {
|
||||
return { ok: false, error: 'Choose a range of one year or less.' };
|
||||
}
|
||||
const lower = `${start.subtract({ days: 2 }).toString()}T00:00:00.000Z`;
|
||||
const upper = `${end.add({ days: 2 }).toString()}T23:59:59.999Z`;
|
||||
const rows = db
|
||||
.prepare(
|
||||
`${ROSTER_SQL}
|
||||
WHERE s.starts_at_utc >= ? AND s.starts_at_utc <= ?
|
||||
ORDER BY s.starts_at_utc, s.id, su.id`,
|
||||
)
|
||||
.all(lower, upper) as RosterRecord[];
|
||||
const kept = rows.filter((row) => {
|
||||
const local = formatInstantInZone(row.starts_at_utc, row.tz).date;
|
||||
return local >= start.toString() && local <= end.toString();
|
||||
});
|
||||
return { ok: true, export: renderRoster(kept) };
|
||||
}
|
||||
|
||||
export function dateStamp(value: string): number | null {
|
||||
const date = parseDate(value);
|
||||
if (!date) return null;
|
||||
return date.year * 10000 + date.month * 100 + date.day;
|
||||
}
|
||||
|
||||
function renderRoster(rows: RosterRecord[]): RosterExport {
|
||||
const lines = [COLUMNS.map(csvCell).join(','), ...rows.map((row) => present(row).map(csvCell).join(','))];
|
||||
return { csv: `\uFEFF${lines.join('\r\n')}\r\n`, rows: rows.length };
|
||||
}
|
||||
|
||||
function present(row: RosterRecord): string[] {
|
||||
const start = formatInstantInZone(row.starts_at_utc, row.tz);
|
||||
const end = formatInstantInZone(row.ends_at_utc, row.tz);
|
||||
return [
|
||||
start.date,
|
||||
start.timeLabel,
|
||||
end.timeLabel,
|
||||
`${row.tz} (${start.abbreviation})`,
|
||||
row.role,
|
||||
row.name ?? '',
|
||||
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' : '',
|
||||
];
|
||||
}
|
||||
|
||||
function parseDate(value: string): Temporal.PlainDate | null {
|
||||
if (!DATE.test(value)) return null;
|
||||
try {
|
||||
const date = Temporal.PlainDate.from(value);
|
||||
return date.toString() === value ? date : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
/** Supplemental bot signal. Not authentication. */
|
||||
export const MIN_FILL_MS = 3000;
|
||||
const MAX_AGE_MS = 2 * 60 * 60 * 1000;
|
||||
const CLOCK_SKEW_MS = 5000;
|
||||
|
||||
export type FormClaims = {
|
||||
shiftId: number;
|
||||
issuedAt: number;
|
||||
operationId: string;
|
||||
};
|
||||
|
||||
export type FormTokenResult =
|
||||
| { ok: true; claims: FormClaims }
|
||||
| { ok: false; reason: 'invalid' | 'too_fast' | 'expired' };
|
||||
|
||||
export function newOperationId(): string {
|
||||
return randomBytes(16).toString('base64url');
|
||||
}
|
||||
|
||||
export function issueFormToken(secret: string, claims: FormClaims): string {
|
||||
const payload = Buffer.from(
|
||||
JSON.stringify({
|
||||
v: 1,
|
||||
shiftId: claims.shiftId,
|
||||
issuedAt: claims.issuedAt,
|
||||
operationId: claims.operationId,
|
||||
}),
|
||||
'utf8',
|
||||
).toString('base64url');
|
||||
return `${payload}.${sign(secret, payload)}`;
|
||||
}
|
||||
|
||||
export function readFormToken(
|
||||
secret: string,
|
||||
token: string,
|
||||
shiftId: number,
|
||||
nowMs: number,
|
||||
minFillMs = MIN_FILL_MS,
|
||||
): FormTokenResult {
|
||||
const opened = openFormToken(secret, token, nowMs, minFillMs);
|
||||
if (!opened.ok) return opened;
|
||||
if (opened.claims.shiftId !== shiftId) return { ok: false, reason: 'invalid' };
|
||||
return opened;
|
||||
}
|
||||
|
||||
export function openFormToken(secret: string, token: string, nowMs: number, minFillMs = MIN_FILL_MS): FormTokenResult {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 2) return { ok: false, reason: 'invalid' };
|
||||
const payload = parts[0];
|
||||
const signature = parts[1];
|
||||
if (!payload || !signature || !safeEqual(sign(secret, payload), signature)) {
|
||||
return { ok: false, reason: 'invalid' };
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
||||
} catch {
|
||||
return { ok: false, reason: 'invalid' };
|
||||
}
|
||||
if (!isClaims(parsed)) return { ok: false, reason: 'invalid' };
|
||||
if (parsed.issuedAt > nowMs + CLOCK_SKEW_MS) return { ok: false, reason: 'invalid' };
|
||||
const age = nowMs - parsed.issuedAt;
|
||||
if (age < minFillMs) return { ok: false, reason: 'too_fast' };
|
||||
if (age > MAX_AGE_MS) return { ok: false, reason: 'expired' };
|
||||
return {
|
||||
ok: true,
|
||||
claims: { shiftId: parsed.shiftId, issuedAt: parsed.issuedAt, operationId: parsed.operationId },
|
||||
};
|
||||
}
|
||||
|
||||
function isClaims(value: unknown): value is FormClaims & { v: 1 } {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return (
|
||||
record.v === 1 &&
|
||||
typeof record.shiftId === 'number' &&
|
||||
Number.isSafeInteger(record.shiftId) &&
|
||||
record.shiftId > 0 &&
|
||||
typeof record.issuedAt === 'number' &&
|
||||
Number.isSafeInteger(record.issuedAt) &&
|
||||
typeof record.operationId === 'string' &&
|
||||
/^[A-Za-z0-9_-]{16,80}$/.test(record.operationId)
|
||||
);
|
||||
}
|
||||
|
||||
function sign(secret: string, payload: string): string {
|
||||
return createHmac('sha256', secret).update(payload).digest('base64url');
|
||||
}
|
||||
|
||||
function safeEqual(expected: string, received: string): boolean {
|
||||
const left = Buffer.from(expected);
|
||||
const right = Buffer.from(received);
|
||||
return left.length === right.length && timingSafeEqual(left, right);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import { copyFile, mkdir, rename, rm } from 'node:fs/promises';
|
||||
import { readdirSync, unlinkSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import Database from 'better-sqlite3';
|
||||
import { writeAudit } from '../auth/audit.js';
|
||||
import { backupDatabase } from '../db.js';
|
||||
import { formatInstantInZone } from '../time.js';
|
||||
|
||||
/** Central Time. 2:30 is missing on the spring-forward morning, so the clock comparison is used. */
|
||||
export const BACKUP_ZONE = 'America/Chicago';
|
||||
export const BACKUP_LOCAL_TIME = '02:30';
|
||||
export const DAILY_KEEP = 14;
|
||||
export const WEEKLY_KEEP = 8;
|
||||
|
||||
export function backupDirectory(dataDir: string): string {
|
||||
return path.join(dataDir, 'backups');
|
||||
}
|
||||
|
||||
const JOB = 'backup';
|
||||
const POLL_MS = 60 * 1000;
|
||||
const SNAPSHOT = /^(daily|weekly)-(\d{4}-\d{2}-\d{2})\.db$/;
|
||||
const MONTHS = [
|
||||
'January',
|
||||
'February',
|
||||
'March',
|
||||
'April',
|
||||
'May',
|
||||
'June',
|
||||
'July',
|
||||
'August',
|
||||
'September',
|
||||
'October',
|
||||
'November',
|
||||
'December',
|
||||
] as const;
|
||||
|
||||
export type BackupCopy = (db: Database.Database, destination: string) => Promise<void>;
|
||||
|
||||
export type BackupResult = {
|
||||
ran: boolean;
|
||||
date: string;
|
||||
weekly: boolean;
|
||||
prunedDaily: number;
|
||||
prunedWeekly: number;
|
||||
};
|
||||
|
||||
export type BackupStatus = {
|
||||
state: 'saved' | 'waiting' | 'behind';
|
||||
text: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves one consistent database copy per Central Time date, after 2:30.
|
||||
* A failed attempt does not remove older copies and does not record the day,
|
||||
* so the next check can try again. Sunday's copy is also kept as a weekly file.
|
||||
*/
|
||||
export async function runDueBackup(
|
||||
db: Database.Database,
|
||||
backupsDir: string,
|
||||
now: string,
|
||||
copy: BackupCopy = backupDatabase,
|
||||
): Promise<BackupResult> {
|
||||
const skipped: BackupResult = { ran: false, date: '', weekly: false, prunedDaily: 0, prunedWeekly: 0 };
|
||||
const clock = formatInstantInZone(now, BACKUP_ZONE);
|
||||
if (clock.time24 < BACKUP_LOCAL_TIME || alreadyRan(db, clock.date)) return skipped;
|
||||
const partial = path.join(backupsDir, `daily-${clock.date}.db.partial`);
|
||||
const daily = path.join(backupsDir, `daily-${clock.date}.db`);
|
||||
try {
|
||||
await copy(db, partial);
|
||||
await mkdir(backupsDir, { recursive: true });
|
||||
await rename(partial, daily);
|
||||
const weekly = clock.weekday === 0;
|
||||
if (weekly) await copySnapshot(daily, path.join(backupsDir, `weekly-${clock.date}.db`));
|
||||
const prunedDaily = pruneSnapshots(backupsDir, 'daily', DAILY_KEEP);
|
||||
const prunedWeekly = pruneSnapshots(backupsDir, 'weekly', WEEKLY_KEEP);
|
||||
markRan(db, clock.date, now);
|
||||
try {
|
||||
writeAudit(db, null, 'backup.save', { prunedDaily, prunedWeekly }, now);
|
||||
} catch {
|
||||
console.error('The database backup was saved, but the audit note was not recorded.');
|
||||
}
|
||||
return { ran: true, date: clock.date, weekly, prunedDaily, prunedWeekly };
|
||||
} catch (err) {
|
||||
await rm(partial, { force: true });
|
||||
console.error(err instanceof Error ? err.message : 'Database backup failed.');
|
||||
return skipped;
|
||||
}
|
||||
}
|
||||
|
||||
/** Newest daily copy, and whether today's backup is still expected later. */
|
||||
export function describeBackup(backupsDir: string, now: string): BackupStatus {
|
||||
const newest = newestSnapshot(backupsDir, 'daily');
|
||||
const clock = formatInstantInZone(now, BACKUP_ZONE);
|
||||
if (!newest) {
|
||||
const state = clock.time24 < BACKUP_LOCAL_TIME ? 'waiting' : 'behind';
|
||||
return { state, text: 'No database backup has been saved yet.' };
|
||||
}
|
||||
const label = prettyDate(newest);
|
||||
const savedToday = newest >= clock.date;
|
||||
const savedYesterday = newest >= previousDate(clock.date) && clock.time24 < BACKUP_LOCAL_TIME;
|
||||
if (savedToday || savedYesterday) return { state: 'saved', text: `Database backup saved ${label}.` };
|
||||
return { state: 'behind', text: `Database backup is behind. The newest saved copy is ${label}.` };
|
||||
}
|
||||
|
||||
export function startBackupRunner(
|
||||
db: Database.Database,
|
||||
backupsDir: string,
|
||||
now: () => string,
|
||||
): { stop: () => void } {
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
const tick = () => {
|
||||
if (running || stopped) return;
|
||||
running = true;
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await runDueBackup(db, backupsDir, now());
|
||||
if (result.ran) console.log(`Saved the database backup for ${result.date}.`);
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Database backup failed.');
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
})();
|
||||
};
|
||||
const timer = setInterval(tick, POLL_MS);
|
||||
timer.unref();
|
||||
tick();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function copySnapshot(source: string, destination: string): Promise<void> {
|
||||
const partial = `${destination}.partial`;
|
||||
try {
|
||||
await copyFile(source, partial);
|
||||
const check = new Database(partial, { readonly: true, fileMustExist: true });
|
||||
try {
|
||||
const result = check.pragma('integrity_check', { simple: true });
|
||||
if (result !== 'ok') throw new Error('Sunday backup failed the integrity check.');
|
||||
} finally {
|
||||
check.close();
|
||||
}
|
||||
await rename(partial, destination);
|
||||
} catch (err) {
|
||||
await rm(partial, { force: true });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function pruneSnapshots(backupsDir: string, kind: 'daily' | 'weekly', keep: number): number {
|
||||
const matched = listSnapshots(backupsDir, kind);
|
||||
const extra = matched.slice(keep);
|
||||
for (const file of extra) unlinkSync(path.join(backupsDir, file.name));
|
||||
return extra.length;
|
||||
}
|
||||
|
||||
function newestSnapshot(backupsDir: string, kind: 'daily' | 'weekly'): string | null {
|
||||
return listSnapshots(backupsDir, kind)[0]?.date ?? null;
|
||||
}
|
||||
|
||||
function listSnapshots(backupsDir: string, kind: 'daily' | 'weekly'): { name: string; date: string }[] {
|
||||
let names: string[] = [];
|
||||
try {
|
||||
names = readdirSync(backupsDir);
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];
|
||||
throw err;
|
||||
}
|
||||
return names
|
||||
.map((name) => {
|
||||
const match = SNAPSHOT.exec(name);
|
||||
if (!match || match[1] !== kind || !match[2]) return null;
|
||||
return { name, date: match[2] };
|
||||
})
|
||||
.filter((row): row is { name: string; date: string } => row !== null)
|
||||
.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0));
|
||||
}
|
||||
|
||||
function prettyDate(iso: string): string {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
|
||||
const month = match ? MONTHS[Number(match[2]) - 1] : undefined;
|
||||
if (!match || !month) return iso;
|
||||
return `${month} ${Number(match[3])}, ${match[1]}`;
|
||||
}
|
||||
|
||||
function previousDate(iso: string): string {
|
||||
return Temporal.PlainDate.from(iso).subtract({ days: 1 }).toString();
|
||||
}
|
||||
|
||||
function alreadyRan(db: Database.Database, localDate: string): boolean {
|
||||
const row = db.prepare('SELECT 1 AS ok FROM job_runs WHERE job = ? AND scope = ? AND local_date = ?').get(JOB, BACKUP_ZONE, localDate);
|
||||
return row !== undefined;
|
||||
}
|
||||
|
||||
function markRan(db: Database.Database, localDate: string, now: string): void {
|
||||
db.prepare('INSERT INTO job_runs (job, scope, local_date, ran_at) VALUES (?, ?, ?, ?)').run(JOB, BACKUP_ZONE, localDate, now);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { expandTemplates } from '../recurrence.js';
|
||||
import { formatInstantInZone } from '../time.js';
|
||||
|
||||
/** Local time after which that event's day gets its weekly fill. */
|
||||
export const REFILL_LOCAL_TIME = '01:00';
|
||||
|
||||
const JOB = 'template.expand';
|
||||
const INTERVAL_MS = 60 * 1000;
|
||||
|
||||
export type DailyExpandResult = {
|
||||
zones: string[];
|
||||
created: number;
|
||||
skipped: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Fills active weekly templates once each local date, after 01:00 in that
|
||||
* event's time zone. A restart later the same day still fills if that date
|
||||
* has not been recorded. The check uses the clock, not a 24-hour timer.
|
||||
*/
|
||||
export function runDueTemplateExpansion(db: Database.Database, now: string): DailyExpandResult {
|
||||
const zones = db.prepare('SELECT DISTINCT tz AS tz FROM events ORDER BY tz').all() as { tz: string }[];
|
||||
const ran: string[] = [];
|
||||
let created = 0;
|
||||
const skipped: string[] = [];
|
||||
for (const zone of zones) {
|
||||
let date = '';
|
||||
let time = '';
|
||||
try {
|
||||
const clock = formatInstantInZone(now, zone.tz);
|
||||
date = clock.date;
|
||||
time = clock.time24;
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Weekly refill could not read an event time zone.');
|
||||
continue;
|
||||
}
|
||||
if (time < REFILL_LOCAL_TIME || alreadyRan(db, zone.tz, date)) continue;
|
||||
try {
|
||||
const result = expandTemplates(db, now, { timeZone: zone.tz });
|
||||
markRan(db, zone.tz, date, now);
|
||||
created += result.created;
|
||||
skipped.push(...result.skipped);
|
||||
ran.push(zone.tz);
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Weekly refill failed.');
|
||||
}
|
||||
}
|
||||
return { zones: ran, created, skipped };
|
||||
}
|
||||
|
||||
/** Checks about once a minute. A check that is still running is not started again. */
|
||||
export function startDailyExpansionRunner(db: Database.Database, now: () => string): { stop: () => void } {
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
const tick = () => {
|
||||
if (running || stopped) return;
|
||||
running = true;
|
||||
try {
|
||||
const result = runDueTemplateExpansion(db, now());
|
||||
if (result.created > 0) {
|
||||
console.log(`Added ${result.created} weekly shifts for the next eight weeks.`);
|
||||
}
|
||||
for (const skip of result.skipped) console.error(skip);
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Weekly refill failed.');
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
const timer = setInterval(tick, INTERVAL_MS);
|
||||
timer.unref();
|
||||
tick();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function alreadyRan(db: Database.Database, timeZone: string, localDate: string): boolean {
|
||||
const row = db.prepare('SELECT 1 AS ok FROM job_runs WHERE job = ? AND scope = ? AND local_date = ?').get(JOB, timeZone, localDate);
|
||||
return row !== undefined;
|
||||
}
|
||||
|
||||
function markRan(db: Database.Database, timeZone: string, localDate: string, now: string): void {
|
||||
db.prepare('INSERT INTO job_runs (job, scope, local_date, ran_at) VALUES (?, ?, ?, ?)').run(JOB, timeZone, localDate, now);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { writeAudit } from '../auth/audit.js';
|
||||
import { purgeRateHits } from '../rate-limit.js';
|
||||
import { readRetentionMonths } from '../settings.js';
|
||||
import { formatInstantInZone, formatUtc } from '../time.js';
|
||||
|
||||
/** Central Time, once each local date, after the weekly refill hour. */
|
||||
export const RETENTION_ZONE = 'America/Chicago';
|
||||
export const RETENTION_LOCAL_TIME = '01:00';
|
||||
/** Volunteer mail keeps its recipient and body this long after it is finished. */
|
||||
export const OUTBOX_KEEP_DAYS = 30;
|
||||
/** Audit rows are counts and ids. They are kept for two years, separate from signup retention. */
|
||||
export const AUDIT_KEEP_MONTHS = 24;
|
||||
|
||||
const JOB = 'retention';
|
||||
const POLL_MS = 60 * 1000;
|
||||
const HOUR_MS = 60 * 60 * 1000;
|
||||
|
||||
export type RetentionResult = {
|
||||
signups: number;
|
||||
messages: number;
|
||||
sessions: number;
|
||||
loginTokens: number;
|
||||
auditRows: number;
|
||||
rateHits: number;
|
||||
};
|
||||
|
||||
type OutboxRow = {
|
||||
id: number;
|
||||
signup_id: number | null;
|
||||
kind: string;
|
||||
status: string;
|
||||
dedupe_key: string;
|
||||
created_at: string;
|
||||
sent_at: string | null;
|
||||
delivery_unknown_at: string | null;
|
||||
claimed_at: string | null;
|
||||
lease_expires_at: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes personal details that are past their keep period. Safe to run more
|
||||
* than once. A name is cleared in the live database only. Downloaded files,
|
||||
* inboxes, and older copies of the database file are outside this cleanup.
|
||||
*/
|
||||
export function runRetention(db: Database.Database, now: string): RetentionResult {
|
||||
const result = db.transaction((): RetentionResult => {
|
||||
const signups = anonymizeSignups(db, now);
|
||||
const login = purgeLoginPayloadsIn(db, now);
|
||||
const auditRows = purgeAudit(db, now);
|
||||
const rateHits = purgeRateHits(db, now);
|
||||
const changed = signups + login.messages + login.sessions + login.loginTokens + auditRows;
|
||||
if (changed > 0) {
|
||||
writeAudit(db, null, 'retention.cleanup', {
|
||||
signups,
|
||||
messages: login.messages,
|
||||
sessions: login.sessions,
|
||||
loginTokens: login.loginTokens,
|
||||
auditRows,
|
||||
}, now);
|
||||
}
|
||||
return { signups, messages: login.messages, sessions: login.sessions, loginTokens: login.loginTokens, auditRows, rateHits };
|
||||
}).immediate();
|
||||
if (result.signups > 0) console.log(`Removed personal details from ${result.signups} old signups.`);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Sign-in links, expired sessions, and expired sign-in messages. The hourly check uses this. */
|
||||
export function purgeLoginPayloads(db: Database.Database, now: string): Pick<RetentionResult, 'messages' | 'sessions' | 'loginTokens'> {
|
||||
return db.transaction(() => purgeLoginPayloadsIn(db, now)).immediate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the cleanup once per Central Time date, after 1:00. When 1:00 happens
|
||||
* twice, the second hour does nothing. A start before 1:00 does not record
|
||||
* the day, so the 1:00 run can still happen.
|
||||
*/
|
||||
export function runDueRetention(db: Database.Database, now: string): { ran: boolean; result: RetentionResult } {
|
||||
const clock = formatInstantInZone(now, RETENTION_ZONE);
|
||||
const empty = { signups: 0, messages: 0, sessions: 0, loginTokens: 0, auditRows: 0, rateHits: 0 };
|
||||
if (clock.time24 < RETENTION_LOCAL_TIME || alreadyRan(db, clock.date)) return { ran: false, result: empty };
|
||||
try {
|
||||
const result = runRetention(db, now);
|
||||
markRan(db, clock.date, now);
|
||||
return { ran: true, result };
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Retention cleanup failed.');
|
||||
return { ran: false, result: empty };
|
||||
}
|
||||
}
|
||||
|
||||
export function startRetentionRunner(db: Database.Database, now: () => string): { stop: () => void } {
|
||||
return startRunner(POLL_MS, () => {
|
||||
const due = runDueRetention(db, now());
|
||||
return due.ran ? due.result.messages : 0;
|
||||
});
|
||||
}
|
||||
|
||||
/** Expired sign-in messages, finished mail past 30 days, and rate-limit counters. Signup names stay on the daily run. */
|
||||
export function startHourlyCleanupRunner(db: Database.Database, now: () => string): { stop: () => void } {
|
||||
return startRunner(HOUR_MS, () => {
|
||||
const login = purgeLoginPayloads(db, now());
|
||||
purgeRateHits(db, now());
|
||||
return login.messages;
|
||||
});
|
||||
}
|
||||
|
||||
function startRunner(intervalMs: number, tickBody: () => number): { stop: () => void } {
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
const tick = () => {
|
||||
if (running || stopped) return;
|
||||
running = true;
|
||||
try {
|
||||
const messages = tickBody();
|
||||
if (messages > 0) console.log(`Removed personal details from ${messages} old messages.`);
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Retention cleanup failed.');
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
const timer = setInterval(tick, intervalMs);
|
||||
timer.unref();
|
||||
tick();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function anonymizeSignups(db: Database.Database, now: string): number {
|
||||
const months = readRetentionMonths(db);
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT su.id AS id, s.ends_at_utc AS ends_at_utc, 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.anonymized_at IS NULL`,
|
||||
)
|
||||
.all() as { id: number; ends_at_utc: string; tz: string }[];
|
||||
const update = db.prepare(
|
||||
`UPDATE signups
|
||||
SET name = NULL, email = NULL, email_norm = NULL, phone = NULL, is_minor = 0,
|
||||
guardian_name = NULL, guardian_email = NULL, notes = NULL,
|
||||
manage_token_hash = NULL, token_expires_at = NULL,
|
||||
anonymized_at = ?, updated_at = ?
|
||||
WHERE id = ? AND anonymized_at IS NULL`,
|
||||
);
|
||||
let count = 0;
|
||||
for (const row of rows) {
|
||||
let due = false;
|
||||
try {
|
||||
const ended = Temporal.Instant.from(row.ends_at_utc).toZonedDateTimeISO(row.tz);
|
||||
due = Temporal.Instant.compare(Temporal.Instant.from(now), ended.add({ months }).toInstant()) >= 0;
|
||||
} catch {
|
||||
console.error('Retention skipped a signup because its event time zone is not valid.');
|
||||
continue;
|
||||
}
|
||||
if (!due) continue;
|
||||
count += update.run(now, now, row.id).changes;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function purgeLoginPayloadsIn(db: Database.Database, now: string): Pick<RetentionResult, 'messages' | 'sessions' | 'loginTokens'> {
|
||||
const messages = purgeOutbox(db, now);
|
||||
const sessions = db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(now).changes;
|
||||
const loginTokens = db
|
||||
.prepare('DELETE FROM login_tokens WHERE used_at IS NOT NULL OR expires_at <= ?')
|
||||
.run(now).changes;
|
||||
return { messages, sessions, loginTokens };
|
||||
}
|
||||
|
||||
function purgeOutbox(db: Database.Database, now: string): number {
|
||||
const cutoff = formatUtc(Temporal.Instant.from(now).subtract({ hours: OUTBOX_KEEP_DAYS * 24 }));
|
||||
const liveMagic = new Set(
|
||||
(
|
||||
db
|
||||
.prepare(
|
||||
`SELECT token_hash AS token_hash FROM login_tokens
|
||||
WHERE used_at IS NULL AND expires_at > ?`,
|
||||
)
|
||||
.all(now) as { token_hash: string }[]
|
||||
).map((row) => row.token_hash),
|
||||
);
|
||||
const anonymized = new Set(
|
||||
(db.prepare('SELECT id AS id FROM signups WHERE anonymized_at IS NOT NULL').all() as { id: number }[]).map((row) => row.id),
|
||||
);
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT id AS id, signup_id AS signup_id, kind AS kind, status AS status, dedupe_key AS dedupe_key,
|
||||
created_at AS created_at, sent_at AS sent_at, delivery_unknown_at AS delivery_unknown_at,
|
||||
claimed_at AS claimed_at, lease_expires_at AS lease_expires_at
|
||||
FROM outbox
|
||||
WHERE dedupe_key NOT LIKE 'purged:%'`,
|
||||
)
|
||||
.all() as OutboxRow[];
|
||||
const update = db.prepare(
|
||||
`UPDATE outbox
|
||||
SET dedupe_key = ?, to_email = '', subject = '', body_text = '', body_html = '',
|
||||
headers_json = '{}', last_error = NULL,
|
||||
status = CASE WHEN status IN ('pending', 'sending') THEN 'cancelled' ELSE status END
|
||||
WHERE id = ?`,
|
||||
);
|
||||
let count = 0;
|
||||
for (const row of rows) {
|
||||
if (!messageDue(row, now, cutoff, liveMagic, anonymized)) continue;
|
||||
count += update.run(`purged:${row.id}`, row.id).changes;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function messageDue(row: OutboxRow, now: string, cutoff: string, liveMagic: Set<string>, anonymized: Set<number>): boolean {
|
||||
if (row.status === 'sending' && row.lease_expires_at && row.lease_expires_at > now) return false;
|
||||
if (row.signup_id !== null && anonymized.has(row.signup_id)) return true;
|
||||
if (row.kind === 'magic_link') {
|
||||
const hash = row.dedupe_key.startsWith('magic_link:') ? row.dedupe_key.slice('magic_link:'.length) : '';
|
||||
return hash.length === 0 || !liveMagic.has(hash);
|
||||
}
|
||||
const stamp = contentStamp(row);
|
||||
return stamp !== null && stamp <= cutoff;
|
||||
}
|
||||
|
||||
function contentStamp(row: OutboxRow): string | null {
|
||||
if (row.status === 'sent') return row.sent_at ?? row.created_at;
|
||||
if (row.status === 'delivery_unknown') return row.delivery_unknown_at ?? row.claimed_at ?? row.created_at;
|
||||
if (row.status === 'pending' || row.status === 'sending' || row.status === 'failed' || row.status === 'cancelled') {
|
||||
return row.claimed_at ?? row.created_at;
|
||||
}
|
||||
return row.created_at;
|
||||
}
|
||||
|
||||
function purgeAudit(db: Database.Database, now: string): number {
|
||||
const cutoff = formatUtc(
|
||||
Temporal.Instant.from(now).toZonedDateTimeISO(RETENTION_ZONE).subtract({ months: AUDIT_KEEP_MONTHS }).toInstant(),
|
||||
);
|
||||
return db.prepare('DELETE FROM audit WHERE at <= ?').run(cutoff).changes;
|
||||
}
|
||||
|
||||
function alreadyRan(db: Database.Database, localDate: string): boolean {
|
||||
const row = db.prepare('SELECT 1 AS ready FROM job_runs WHERE job = ? AND scope = ? AND local_date = ?').get(JOB, RETENTION_ZONE, localDate);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
function markRan(db: Database.Database, localDate: string, now: string): void {
|
||||
db.prepare('INSERT INTO job_runs (job, scope, local_date, ran_at) VALUES (?, ?, ?, ?)').run(JOB, RETENTION_ZONE, localDate, now);
|
||||
}
|
||||
@@ -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>;
|
||||
};
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import { chmodSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { serve } from '@hono/node-server';
|
||||
import type { ServerType } from '@hono/node-server';
|
||||
import { bootstrapAdmin } from './auth/bootstrap.js';
|
||||
import { createApp } from './app.js';
|
||||
import { ConfigError, loadConfig } from './config.js';
|
||||
import { MigrationError, openAppDatabase } from './db.js';
|
||||
import { createMailer } from './mail/driver.js';
|
||||
import { startOutboxRunner } from './mail/run.js';
|
||||
import { startDailyExpansionRunner } from './jobs/daily-expand.js';
|
||||
import { backupDirectory, startBackupRunner } from './jobs/backup.js';
|
||||
import { runRetention, startHourlyCleanupRunner, startRetentionRunner } from './jobs/retention.js';
|
||||
import { expandTemplates } from './recurrence.js';
|
||||
import { startReminderRunner } from './reminders-run.js';
|
||||
import { nowUtc } from './time.js';
|
||||
|
||||
// The database, its WAL files, and backups hold volunteer contact details. Owner only.
|
||||
process.umask(0o077);
|
||||
|
||||
async function main(): Promise<void> {
|
||||
let database: Awaited<ReturnType<typeof openAppDatabase>> | undefined;
|
||||
try {
|
||||
const config = loadConfig(process.env);
|
||||
if (config.nodeEnv === 'production' && config.trustProxy.mode === 'disabled' && config.bindHost === '0.0.0.0') {
|
||||
console.warn(
|
||||
'TRUST_PROXY is false. Behind Caddy every visitor shares one address and one set of rate limits. Set TRUST_PROXY to the proxy peer.',
|
||||
);
|
||||
}
|
||||
database = await openAppDatabase(config);
|
||||
restrictDataFiles(config.databaseFile, backupDirectory(config.dataDir));
|
||||
const startedAt = nowUtc();
|
||||
const created = bootstrapAdmin(database, config.bootstrapAdminEmail, startedAt);
|
||||
if (created.created) {
|
||||
console.log('Created the first administrator. Sign in with the address in BOOTSTRAP_ADMIN_EMAIL.');
|
||||
}
|
||||
const expanded = expandTemplates(database, startedAt);
|
||||
if (expanded.created > 0) {
|
||||
console.log(`Added ${expanded.created} weekly shifts for the next eight weeks.`);
|
||||
}
|
||||
for (const skip of expanded.skipped) console.error(skip);
|
||||
runRetention(database, startedAt);
|
||||
const app = createApp(config, database);
|
||||
const mail = startOutboxRunner(database, createMailer(config), nowUtc);
|
||||
const reminders = startReminderRunner(
|
||||
database,
|
||||
{ baseUrl: config.baseUrl, basePath: config.basePath, from: config.mail.from, replyTo: config.mail.replyTo },
|
||||
config.sessionSecret,
|
||||
nowUtc,
|
||||
);
|
||||
const refill = startDailyExpansionRunner(database, nowUtc);
|
||||
const retention = startRetentionRunner(database, nowUtc);
|
||||
const hourly = startHourlyCleanupRunner(database, nowUtc);
|
||||
const backup = startBackupRunner(database, backupDirectory(config.dataDir), nowUtc);
|
||||
const server = serve({
|
||||
fetch: app.fetch,
|
||||
port: config.port,
|
||||
hostname: config.bindHost,
|
||||
});
|
||||
console.log(`Hope Volunteer is at ${config.baseUrl}${config.basePath || '/'} (bound to ${config.bindHost}:${config.port}).`);
|
||||
waitForShutdown(server, database, () => {
|
||||
mail.stop();
|
||||
reminders.stop();
|
||||
refill.stop();
|
||||
retention.stop();
|
||||
hourly.stop();
|
||||
backup.stop();
|
||||
});
|
||||
} catch (err) {
|
||||
database?.close();
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
console.error(message);
|
||||
if (!(err instanceof ConfigError || err instanceof MigrationError) || !message.includes('Startup aborted.')) {
|
||||
console.error('Startup aborted.');
|
||||
}
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Files created before the umask above may still be readable by others. */
|
||||
function restrictDataFiles(databaseFile: string, backups: string): void {
|
||||
const files = [databaseFile, `${databaseFile}-wal`, `${databaseFile}-shm`];
|
||||
try {
|
||||
for (const entry of readdirSync(backups, { withFileTypes: true })) {
|
||||
if (entry.isFile()) files.push(path.join(backups, entry.name));
|
||||
}
|
||||
} catch {
|
||||
// No backups yet.
|
||||
}
|
||||
for (const file of files) {
|
||||
try {
|
||||
chmodSync(file, 0o600);
|
||||
} catch {
|
||||
// Missing, or owned by someone else. The host owner fixes that.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function waitForShutdown(server: ServerType, database: { close: () => void }, stopMail: () => void): void {
|
||||
let stopping = false;
|
||||
const shutdown = () => {
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
stopMail();
|
||||
let finished = false;
|
||||
const finish = () => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
database.close();
|
||||
process.exit(0);
|
||||
};
|
||||
server.close(finish);
|
||||
setTimeout(finish, 1000).unref();
|
||||
};
|
||||
server.on('error', (err: NodeJS.ErrnoException) => {
|
||||
console.error(err.message);
|
||||
console.error('Startup aborted.');
|
||||
database.close();
|
||||
process.exit(1);
|
||||
});
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Context } from 'hono';
|
||||
|
||||
/**
|
||||
* A form POST must come from this site.
|
||||
* Origin: null is an opaque origin, not a match for BASE_URL.
|
||||
* Sec-Fetch-Site is set by the browser. same-origin and none are not cross-site forgery.
|
||||
*/
|
||||
export function originAllowed(c: Context, baseUrl: string): boolean {
|
||||
const origin = c.req.header('origin');
|
||||
if (origin && origin !== 'null') return origin === baseUrl;
|
||||
const site = c.req.header('sec-fetch-site');
|
||||
if (site === 'same-origin' || site === 'none') return true;
|
||||
const referer = c.req.header('referer');
|
||||
if (!referer) return false;
|
||||
try {
|
||||
return new URL(referer).origin === baseUrl;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+841
@@ -0,0 +1,841 @@
|
||||
import type { Child } from 'hono/jsx';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { WEEKDAY_SHORT, calendarMonth, calendarToday, chooseCalendarMonth, monthStep, type CalendarDay } from './calendar.js';
|
||||
import { spotsSentence, type PublicEvent, type PublicShift } from './schedule.js';
|
||||
import type { SignupErrors, SignupValues } from './signup-form.js';
|
||||
import type { MoveTarget } from './admin/store.js';
|
||||
import type { ManageView } from './signup.js';
|
||||
import { appPath } from './url.js';
|
||||
|
||||
const PANTRY_SITE = 'https://hopefoodpantrysc.org';
|
||||
|
||||
function asset(config: AppConfig, file: string): string {
|
||||
return appPath(config, file);
|
||||
}
|
||||
|
||||
export function Layout(props: {
|
||||
config: AppConfig;
|
||||
title: string;
|
||||
path?: string;
|
||||
turnstile?: boolean;
|
||||
account?: { csrf: string } | null;
|
||||
children?: Child;
|
||||
}) {
|
||||
const home = appPath(props.config, '/');
|
||||
const privacy = appPath(props.config, '/privacy');
|
||||
const coordinator = appPath(props.config, props.account ? '/admin' : '/login');
|
||||
const logo = asset(props.config, '/img/logo.png');
|
||||
const menu = asset(props.config, '/img/icons/menu.svg');
|
||||
const close = asset(props.config, '/img/icons/close.svg');
|
||||
const facebook = asset(props.config, '/img/icons/facebook.svg');
|
||||
const instagram = asset(props.config, '/img/icons/instagram.svg');
|
||||
const wave = asset(props.config, '/img/wave-secondary.svg');
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charSet="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>{props.title}</title>
|
||||
<link rel="icon" href={asset(props.config, '/img/favicons/favicon.png')} />
|
||||
<link rel="apple-touch-icon" href={asset(props.config, '/img/favicons/favicon-apple.png')} />
|
||||
<link rel="stylesheet" href={appPath(props.config, '/brand/tokens.css')} />
|
||||
<link rel="stylesheet" href={appPath(props.config, '/css/app.css')} />
|
||||
<script src={appPath(props.config, '/js/desk.js')} />
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#content">
|
||||
Skip to content
|
||||
</a>
|
||||
<header class="site-header">
|
||||
<a class="logo-link" href={`${PANTRY_SITE}/`}>
|
||||
<img class="logo" src={logo} alt="Hope Food Pantry" />
|
||||
</a>
|
||||
<input class="nav-toggle" id="nav-toggle" type="checkbox" />
|
||||
<label class="btn-mobile-nav" for="nav-toggle">
|
||||
<img class="icon-mobile-nav icon-open" src={menu} alt="" />
|
||||
<img class="icon-mobile-nav icon-close" src={close} alt="" />
|
||||
<span class="sr-only">Menu</span>
|
||||
</label>
|
||||
<div class="header-side">
|
||||
<nav aria-label="Primary">
|
||||
<ul class="nav-links">
|
||||
<li>
|
||||
<a class="main-nav-link" href={`${PANTRY_SITE}/`}>
|
||||
Home
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="main-nav-link" href={`${PANTRY_SITE}/about.html`}>
|
||||
About
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="main-nav-link" href={`${PANTRY_SITE}/faq.html`}>
|
||||
FAQ
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="main-nav-link" href={home} aria-current={props.path === home ? 'page' : undefined}>
|
||||
Volunteering
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="main-nav-link" href={`${PANTRY_SITE}/#contact`}>
|
||||
Contact
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="btn" href="https://donorbox.org/hope-food-pantry-1">
|
||||
Donate
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
<ul class="utility-links">
|
||||
<li>
|
||||
<a href={home} aria-current={props.path === home ? 'page' : undefined}>
|
||||
Calendar
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={privacy} aria-current={props.path === privacy ? 'page' : undefined}>
|
||||
Privacy
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={coordinator}>Coordinator</a>
|
||||
</li>
|
||||
{props.account ? (
|
||||
<li>
|
||||
<form method="post" action={appPath(props.config, '/logout')} class="utility-logout">
|
||||
<input type="hidden" name="csrf" value={props.account.csrf} />
|
||||
<button type="submit">Log out</button>
|
||||
</form>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
</div>
|
||||
</header>
|
||||
<main id="content" tabIndex={-1}>
|
||||
{props.children}
|
||||
</main>
|
||||
<footer class="site-footer">
|
||||
<img class="footer-wave" src={wave} alt="" />
|
||||
<div class="footer-nav">
|
||||
<div class="footer-brand">
|
||||
<a class="logo-link" href={`${PANTRY_SITE}/`}>
|
||||
<img class="logo" src={logo} alt="Hope Food Pantry" />
|
||||
</a>
|
||||
<p class="equal-text">
|
||||
Hope Food Pantry is an{' '}
|
||||
<a href="https://www.usda.gov/sites/default/files/documents/ad-475a.pdf" target="_blank" rel="noopener noreferrer">
|
||||
equal opportunity provider.
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
<div class="footer-cell">
|
||||
<h2>Contact Us</h2>
|
||||
<p>
|
||||
<a href="tel:+17125409351">712-540-9351</a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="mailto:hopepantry@gmail.com">hopepantry@gmail.com</a>
|
||||
</p>
|
||||
<div class="social-links">
|
||||
<a href="https://www.facebook.com/schopefoodpantry" target="_blank" rel="noopener noreferrer">
|
||||
<span class="social-flex">
|
||||
<img src={facebook} alt="" />
|
||||
<span>schopefoodpantry</span>
|
||||
</span>
|
||||
</a>
|
||||
<a href="https://www.instagram.com/hopefoodpantrysc" target="_blank" rel="noopener noreferrer">
|
||||
<span class="social-flex">
|
||||
<img src={instagram} alt="" />
|
||||
<span>hopefoodpantrysc</span>
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer-cell">
|
||||
<h2>Address</h2>
|
||||
<address>
|
||||
<p>
|
||||
4155 US 75 Ave
|
||||
<br />
|
||||
Sioux Center, IA 51250
|
||||
<br />
|
||||
(Rear of Property)
|
||||
</p>
|
||||
<p>Mail to: PO Box 21</p>
|
||||
</address>
|
||||
</div>
|
||||
<div class="footer-cell">
|
||||
<h2>Navigation</h2>
|
||||
<ul class="footer-links">
|
||||
<li>
|
||||
<a href={`${PANTRY_SITE}/`}>Home</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={`${PANTRY_SITE}/about.html`}>About</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={`${PANTRY_SITE}/faq.html`}>FAQ</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={home} aria-current={props.path === home ? 'page' : undefined}>
|
||||
Volunteering
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={`${PANTRY_SITE}/#contact`}>Contact</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://donorbox.org/hope-food-pantry-1">Donate</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href={privacy} aria-current={props.path === privacy ? 'page' : undefined}>
|
||||
Privacy
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<p class="copyright-text">Hope Food Pantry, Sioux Center, Iowa</p>
|
||||
</footer>
|
||||
{props.turnstile ? <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer /> : null}
|
||||
<script src={appPath(props.config, '/js/enhance.js')} defer />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptySchedulePage() {
|
||||
return (
|
||||
<>
|
||||
<h1>Weekly pantry</h1>
|
||||
<p class="empty">No upcoming shifts are posted.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function EventPage(props: { config: AppConfig; event: PublicEvent; now: string; month?: string; path?: string }) {
|
||||
const description = props.event.description.trim();
|
||||
return (
|
||||
<>
|
||||
<h1>{props.event.title}</h1>
|
||||
{props.event.location ? <p class="location">{props.event.location}</p> : null}
|
||||
{props.event.slug === 'weekly-pantry' ? null : <p class="zone">Times are shown in {props.event.timeZone}.</p>}
|
||||
{description ? <p class="description">{description}</p> : null}
|
||||
{props.event.shifts.length === 0 ? (
|
||||
<p class="empty">No upcoming shifts are posted for this event.</p>
|
||||
) : (
|
||||
<ShiftCalendar
|
||||
config={props.config}
|
||||
event={props.event}
|
||||
now={props.now}
|
||||
month={props.month}
|
||||
path={props.path ?? `/e/${encodeURIComponent(props.event.slug)}`}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export type SignupFormView = {
|
||||
token: string;
|
||||
siteKey: string;
|
||||
values: SignupValues;
|
||||
errors: SignupErrors;
|
||||
};
|
||||
|
||||
export function ShiftPage(props: {
|
||||
config: AppConfig;
|
||||
shift: PublicShift;
|
||||
signup?: SignupFormView | null;
|
||||
notice?: string;
|
||||
}) {
|
||||
const description = props.shift.event.description.trim();
|
||||
return (
|
||||
<>
|
||||
<h1>{props.shift.role}</h1>
|
||||
{props.shift.event.location ? <p class="location">{props.shift.event.location}</p> : null}
|
||||
<ShiftWhen shift={props.shift} />
|
||||
<StatusLine shift={props.shift} />
|
||||
{description ? <p class="description">{description}</p> : null}
|
||||
{props.notice ? (
|
||||
<p class="error" role="alert">
|
||||
{props.notice}
|
||||
</p>
|
||||
) : null}
|
||||
{props.signup ? <SignupForm config={props.config} shiftId={props.shift.id} form={props.signup} /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ConfirmationPage(props: {
|
||||
config: AppConfig;
|
||||
shift: PublicShift;
|
||||
name: string | null;
|
||||
managePath: string | null;
|
||||
cancelled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<h1>{props.cancelled ? 'This signup is cancelled' : "You're signed up"}</h1>
|
||||
<p>
|
||||
{props.cancelled
|
||||
? `${props.name ? `${props.name} is no longer signed up for ` : 'This signup is no longer for '}${props.shift.role}.`
|
||||
: `${props.name ? `${props.name} is signed up for ` : 'This signup is for '}${props.shift.role}.`}
|
||||
</p>
|
||||
<ShiftWhen shift={props.shift} />
|
||||
{props.managePath ? (
|
||||
<>
|
||||
<p>
|
||||
{props.cancelled
|
||||
? 'A cancellation email is queued. This link still opens the cancelled signup.'
|
||||
: 'A confirmation email is queued. Save this link too, in case the email is delayed. It opens this signup, where you can cancel it or switch it to another open shift.'}
|
||||
</p>
|
||||
<p>
|
||||
<a href={props.managePath}>Open this signup</a>
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p>If you just signed up, the link stays in this browser for a few minutes. A confirmation email is queued.</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export type SwitchForm = {
|
||||
action: string;
|
||||
token: string;
|
||||
formToken: string;
|
||||
targets: MoveTarget[];
|
||||
};
|
||||
|
||||
export function ManagePage(props: {
|
||||
signup: ManageView;
|
||||
cancel: { action: string; token: string } | null;
|
||||
switches: SwitchForm | null;
|
||||
reminders?: { action: string; token: string } | 'off' | null;
|
||||
notice?: string;
|
||||
note?: string;
|
||||
}) {
|
||||
const signup = props.signup;
|
||||
return (
|
||||
<>
|
||||
<h1>Your signup</h1>
|
||||
<p class="status">{signup.status === 'confirmed' ? 'Confirmed' : 'Cancelled'}</p>
|
||||
<p>{signup.eventTitle}</p>
|
||||
<h2>{signup.role}</h2>
|
||||
<p class="when">
|
||||
<time dateTime={signup.when.date}>{signup.when.dateLabel}</time> {signup.when.timeLabel} {signup.when.abbreviation}
|
||||
</p>
|
||||
{signup.location ? <p class="location">{signup.location}</p> : null}
|
||||
<dl class="details">
|
||||
<div>
|
||||
<dt>Name</dt>
|
||||
<dd>{signup.name}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Email</dt>
|
||||
<dd>{signup.email}</dd>
|
||||
</div>
|
||||
{signup.phone ? (
|
||||
<div>
|
||||
<dt>Phone</dt>
|
||||
<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>
|
||||
<dd class="description">{signup.notes}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
{props.note ? <p class="status">{props.note}</p> : null}
|
||||
{props.notice ? (
|
||||
<p class="error" role="alert">
|
||||
{props.notice}
|
||||
</p>
|
||||
) : null}
|
||||
{props.switches ? (
|
||||
props.switches.targets.length === 0 ? (
|
||||
<p>There is no other open shift you can switch to.</p>
|
||||
) : (
|
||||
<form class="move-form" method="post" action={props.switches.action}>
|
||||
<p>Switch to another shift in this event. This opens your spot here and queues a change email. This link stops working, and the next page has the new one.</p>
|
||||
<input type="hidden" name="switch_token" value={props.switches.token} />
|
||||
<input type="hidden" name="form_token" value={props.switches.formToken} />
|
||||
<label for="switch-to">
|
||||
Switch to
|
||||
<select id="switch-to" name="destination" required>
|
||||
<option value="">Choose a shift</option>
|
||||
{props.switches.targets.map((target) => (
|
||||
<option value={String(target.id)} key={target.id}>
|
||||
{target.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button type="submit">Switch</button>
|
||||
</form>
|
||||
)
|
||||
) : null}
|
||||
{props.reminders === 'off' ? (
|
||||
<p>Reminder emails for this signup are off. The signup stays. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
) : null}
|
||||
<div class="manage-actions">
|
||||
{props.reminders && props.reminders !== 'off' ? (
|
||||
<form class="cancel-form" method="post" action={props.reminders.action}>
|
||||
<p>Stop reminder emails for this signup. The signup stays. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
<input type="hidden" name="reminder_token" value={props.reminders.token} />
|
||||
<button type="submit">Stop reminder emails</button>
|
||||
</form>
|
||||
) : null}
|
||||
{props.cancel ? (
|
||||
<form class="cancel-form" method="post" action={props.cancel.action}>
|
||||
<p>Cancel this signup to open the spot for someone else. A cancellation email is queued when you cancel.</p>
|
||||
<input type="hidden" name="cancel_token" value={props.cancel.token} />
|
||||
<button type="submit">Cancel this signup</button>
|
||||
</form>
|
||||
) : (
|
||||
<p>This signup is cancelled. The spot is open for someone else. A cancellation email is queued.</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// TODO(D3): The pantry still has to approve this wording, including retention and copies.
|
||||
// A blank setting keeps the unapproved message. Saved wording is shown as written, escaped, and is not a policy by itself.
|
||||
export function PrivacyPage(props: { paragraphs: string[] }) {
|
||||
return (
|
||||
<>
|
||||
<h1>Privacy</h1>
|
||||
{props.paragraphs.length === 0 ? (
|
||||
<>
|
||||
<p>Hope Volunteer does not have an approved privacy notice yet.</p>
|
||||
<p>When the pantry approves the wording, it will appear on this page. This page is not a privacy policy.</p>
|
||||
</>
|
||||
) : (
|
||||
props.paragraphs.map((paragraph, index) => <p key={index}>{paragraph}</p>)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function SwitchAlreadyPage() {
|
||||
return (
|
||||
<>
|
||||
<h1>Your signup</h1>
|
||||
<p>This signup was already switched. Use the link in the email.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReminderOffPage(props: { config: AppConfig; token: string; replyTo: string; off: boolean; error?: string }) {
|
||||
return (
|
||||
<>
|
||||
<h1>Reminder emails</h1>
|
||||
{props.error ? (
|
||||
<p class="error" role="alert">
|
||||
{props.error}
|
||||
</p>
|
||||
) : null}
|
||||
{props.off ? (
|
||||
<p>Reminder emails for this signup are off. The signup stays. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
) : (
|
||||
<form method="post" action={appPath(props.config, `/u/${props.token}`)} class="cancel-form">
|
||||
<p>This turns off reminder emails for this signup. It does not cancel the signup. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
<p>The pantry reads mail sent to {props.replyTo}. This button turns reminders off immediately.</p>
|
||||
<button type="submit">Stop reminder emails</button>
|
||||
</form>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function NotFoundPage() {
|
||||
return (
|
||||
<>
|
||||
<h1>That page is not available</h1>
|
||||
<p>The link may be out of date, or the shift is not posted.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProblemPage() {
|
||||
return (
|
||||
<>
|
||||
<h1>Something went wrong</h1>
|
||||
<p>The page could not be loaded. Try again in a little while.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function WaitPage() {
|
||||
return (
|
||||
<>
|
||||
<h1>Please wait</h1>
|
||||
<p>Too many attempts. Please wait and try again.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function monthHref(config: AppConfig, path: string, monthId: string): string {
|
||||
return `${appPath(config, path)}?month=${monthId}`;
|
||||
}
|
||||
|
||||
function MonthArrow(props: { config: AppConfig; path: string; monthId: string; direction: 'prev' | 'next' }) {
|
||||
const next = props.direction === 'next';
|
||||
return (
|
||||
<a class="month-arrow" rel={props.direction} href={monthHref(props.config, props.path, props.monthId)}>
|
||||
<span class="sr-only">{next ? 'Next month' : 'Previous month'}</span>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d={next ? 'M9.5 5.5 16 12l-6.5 6.5' : 'M14.5 5.5 8 12l6.5 6.5'} />
|
||||
</svg>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function ShiftCalendar(props: {
|
||||
config: AppConfig;
|
||||
event: PublicEvent;
|
||||
now: string;
|
||||
month?: string;
|
||||
path: string;
|
||||
}) {
|
||||
const today = calendarToday(props.event.timeZone, props.now);
|
||||
const dates = props.event.shifts.map((shift) => shift.when.date);
|
||||
const monthId = chooseCalendarMonth(props.month, dates, today);
|
||||
const month = calendarMonth(monthId);
|
||||
const step = monthStep(monthId, dates);
|
||||
const shiftsByDate = new Map<string, PublicShift[]>();
|
||||
for (const shift of props.event.shifts) {
|
||||
if (shift.when.date.slice(0, 7) !== month.id) continue;
|
||||
const listed = shiftsByDate.get(shift.when.date);
|
||||
if (listed) listed.push(shift);
|
||||
else shiftsByDate.set(shift.when.date, [shift]);
|
||||
}
|
||||
const titleId = `month-${props.event.id}-${month.id}`;
|
||||
const shiftsThisMonth = [...shiftsByDate.values()].some((listed) => listed.length > 0);
|
||||
return (
|
||||
<div class="shift-calendar">
|
||||
<section class="cal-month" aria-labelledby={titleId}>
|
||||
<div class="month-nav">
|
||||
{step.previous ? (
|
||||
<MonthArrow config={props.config} path={props.path} monthId={step.previous} direction="prev" />
|
||||
) : (
|
||||
<span class="month-nav-slot"></span>
|
||||
)}
|
||||
<h2 id={titleId} class="cal-title">
|
||||
{month.label}
|
||||
</h2>
|
||||
{step.next ? (
|
||||
<MonthArrow config={props.config} path={props.path} monthId={step.next} direction="next" />
|
||||
) : (
|
||||
<span class="month-nav-slot"></span>
|
||||
)}
|
||||
</div>
|
||||
<div class="cal-weekdays" aria-hidden="true">
|
||||
{WEEKDAY_SHORT.map((weekday) => (
|
||||
<span key={weekday}>{weekday}</span>
|
||||
))}
|
||||
</div>
|
||||
<ol class="cal-weeks">
|
||||
{month.weeks.map((week) => {
|
||||
const weekStart = week[0];
|
||||
if (!weekStart) return null;
|
||||
return (
|
||||
<li class="cal-week" key={weekStart.date}>
|
||||
<ol class="cal-week-days">
|
||||
{week.map((day) => (
|
||||
<CalendarDayCell
|
||||
key={day.date}
|
||||
config={props.config}
|
||||
day={day}
|
||||
today={today}
|
||||
weekName={`shifts-${weekStart.date}`}
|
||||
shifts={shiftsByDate.get(day.date) ?? []}
|
||||
/>
|
||||
))}
|
||||
</ol>
|
||||
<div class="week-tray"></div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
{shiftsThisMonth ? null : <p class="empty">No shifts this month.</p>}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CalendarDayCell(props: { config: AppConfig; day: CalendarDay; today: string; weekName: string; shifts: PublicShift[] }) {
|
||||
if (!props.day.inMonth) return <li class="cal-day is-outside" aria-hidden="true"></li>;
|
||||
const today = props.day.date === props.today;
|
||||
const className = ['cal-day', today ? 'is-today' : '', props.day.date < props.today ? 'is-past' : '', props.shifts.length > 0 ? 'has-shifts' : 'is-empty']
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
return (
|
||||
<li class={className} aria-current={today ? 'date' : undefined}>
|
||||
<div class="cal-day-face">
|
||||
<p class="day-label">
|
||||
<DayStamp day={props.day} today={today} />
|
||||
{today ? (
|
||||
<span class="today-flag" aria-hidden="true">
|
||||
Today
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
{props.shifts.length > 0 ? (
|
||||
<details class="day-reveal" name={props.weekName} data-date={props.day.date}>
|
||||
<summary class="day-summary">
|
||||
<DayStamp day={props.day} today={today} />
|
||||
<span class="day-markers">
|
||||
{today ? (
|
||||
<span class="today-flag" aria-hidden="true">
|
||||
Today
|
||||
</span>
|
||||
) : null}
|
||||
<span class="event-dot" aria-hidden="true"></span>
|
||||
<span class="expand-chevron" aria-hidden="true"></span>
|
||||
</span>
|
||||
<span class="sr-only">Show shifts</span>
|
||||
</summary>
|
||||
</details>
|
||||
) : null}
|
||||
{props.shifts.length > 0 ? (
|
||||
<div class="shift-drawer" data-date={props.day.date}>
|
||||
<p class="tray-label">
|
||||
{props.day.weekday} {props.day.day}
|
||||
</p>
|
||||
<ShiftList config={props.config} shifts={props.shifts} className="day-shifts" />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function DayStamp(props: { day: CalendarDay; today: boolean }) {
|
||||
return (
|
||||
<time dateTime={props.day.date}>
|
||||
<span class="day-full sr-only">{props.today ? `Today, ${props.day.label}` : props.day.label}</span>
|
||||
<span class="day-weekday" aria-hidden="true">
|
||||
{props.day.weekday}
|
||||
</span>
|
||||
<span class="day-num" aria-hidden="true">
|
||||
{props.day.day}
|
||||
</span>
|
||||
</time>
|
||||
);
|
||||
}
|
||||
|
||||
function ShiftList(props: { config: AppConfig; shifts: PublicShift[]; className: string }) {
|
||||
return (
|
||||
<ul class={props.className}>
|
||||
{props.shifts.map((shift) => (
|
||||
<li key={shift.id}>
|
||||
<CalendarShift config={props.config} shift={shift} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function CalendarShift(props: { config: AppConfig; shift: PublicShift }) {
|
||||
const shift = props.shift;
|
||||
const closed = shift.full || shift.cancelled || shift.ended;
|
||||
const action = closed ? 'View shift' : 'Sign up';
|
||||
return (
|
||||
<a class="cal-shift" href={appPath(props.config, `/s/${shift.id}`)}>
|
||||
<span class="cal-line">
|
||||
{shift.when.startLabel} {shift.role}
|
||||
</span>
|
||||
<span class="sr-only">
|
||||
{'. '}
|
||||
{action} for {shift.role} on {shift.when.dateLabel}, {shift.when.startLabel} to {shift.when.endLabel}{' '}
|
||||
{shift.when.abbreviation}. {spotsSentence(shift)}
|
||||
{shift.inProgress ? ' In progress.' : ''}
|
||||
</span>
|
||||
<div class="cal-detail" aria-hidden="true">
|
||||
<span class="cal-hold" aria-hidden="true"></span>
|
||||
<span class="role">{shift.role}</span>
|
||||
<span class="when">
|
||||
<time dateTime={shift.startsAtUtc}>{shift.when.startLabel}</time>
|
||||
{' to '}
|
||||
{shift.when.sameDay ? null : <time dateTime={shift.endsAtUtc}>{shift.when.endDateLabel} </time>}
|
||||
<time dateTime={shift.endsAtUtc}>{shift.when.endLabel}</time> {shift.when.abbreviation}
|
||||
</span>
|
||||
{shift.inProgress ? <span class="status">In progress</span> : null}
|
||||
<Spots shift={shift} />
|
||||
<span class="cal-action">{action}</span>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function ShiftWhen(props: { shift: PublicShift }) {
|
||||
const shift = props.shift;
|
||||
return (
|
||||
<p class="when">
|
||||
<time dateTime={shift.startsAtUtc}>{shift.when.startLabel}</time>
|
||||
{' to '}
|
||||
{shift.when.sameDay ? null : (
|
||||
<time dateTime={shift.endsAtUtc}>{shift.when.endDateLabel} </time>
|
||||
)}
|
||||
<time dateTime={shift.endsAtUtc}>{shift.when.endLabel}</time> {shift.when.abbreviation}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
function Spots(props: { shift: PublicShift }) {
|
||||
return <p class={props.shift.full ? 'spots is-full' : 'spots is-open'}>{spotsSentence(props.shift)}</p>;
|
||||
}
|
||||
|
||||
function SignupForm(props: { config: AppConfig; shiftId: number; form: SignupFormView }) {
|
||||
const form = props.form;
|
||||
const errors = form.errors;
|
||||
const errorEntries = Object.entries(errors).filter((entry): entry is [string, string] => Boolean(entry[1]));
|
||||
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>
|
||||
<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>
|
||||
{errorEntries.length > 0 ? (
|
||||
<div class="error" role="alert">
|
||||
<p>Check these fields:</p>
|
||||
<ul>
|
||||
{errorEntries.map(([field, message]) => (
|
||||
<li key={field}>
|
||||
<a href={`#signup-${field}`}>{message}</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
<input type="hidden" name="form_token" value={form.token} />
|
||||
<div class="hp" aria-hidden="true">
|
||||
<label>
|
||||
Company website
|
||||
<input name="company_website" type="text" tabindex={-1} autocomplete="off" value="" />
|
||||
</label>
|
||||
</div>
|
||||
<Field id="signup-name" label="Name" name="name" type="text" value={form.values.name} error={errors.name} autoComplete="name" />
|
||||
<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)"
|
||||
name="phone"
|
||||
type="tel"
|
||||
value={form.values.phone}
|
||||
error={errors.phone}
|
||||
autoComplete="tel"
|
||||
hint="We will not text you"
|
||||
/>
|
||||
<label for="signup-notes">
|
||||
Notes (optional)
|
||||
<textarea id="signup-notes" name="notes" aria-invalid={errors.notes ? 'true' : undefined} aria-describedby={errors.notes ? 'signup-notes-error' : undefined}>
|
||||
{form.values.notes}
|
||||
</textarea>
|
||||
{errors.notes ? (
|
||||
<span class="field-error" id="signup-notes-error">
|
||||
{errors.notes}
|
||||
</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>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function Field(props: {
|
||||
id: string;
|
||||
label: string;
|
||||
name: string;
|
||||
type: 'text' | 'email' | 'tel';
|
||||
value: string;
|
||||
error?: string;
|
||||
autoComplete: string;
|
||||
hint?: string;
|
||||
}) {
|
||||
const errorId = `${props.id}-error`;
|
||||
const hintId = `${props.id}-hint`;
|
||||
const describedBy = [props.hint ? hintId : '', props.error ? errorId : ''].filter(Boolean).join(' ') || undefined;
|
||||
return (
|
||||
<label for={props.id}>
|
||||
{props.label}
|
||||
<input
|
||||
id={props.id}
|
||||
name={props.name}
|
||||
type={props.type}
|
||||
value={props.value}
|
||||
autocomplete={props.autoComplete}
|
||||
aria-invalid={props.error ? 'true' : undefined}
|
||||
aria-describedby={describedBy}
|
||||
/>
|
||||
{props.hint ? (
|
||||
<span class="hint" id={hintId}>
|
||||
{props.hint}
|
||||
</span>
|
||||
) : null}
|
||||
{props.error ? (
|
||||
<span class="field-error" id={errorId}>
|
||||
{props.error}
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusLine(props: { shift: PublicShift }) {
|
||||
if (props.shift.cancelled) return <p class="status">Cancelled. This shift is closed.</p>;
|
||||
if (props.shift.ended) return <p class="status">Ended. This shift is closed.</p>;
|
||||
return (
|
||||
<>
|
||||
{props.shift.inProgress ? <p class="status">In progress</p> : null}
|
||||
<Spots shift={props.shift} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { normalizeEmail } from './email.js';
|
||||
import { formatUtc } from './time.js';
|
||||
|
||||
/** Initial public limits from the October 14, 2026 specification. */
|
||||
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;
|
||||
export const LOGIN_EMAIL_LIMIT = 3;
|
||||
export const LOGIN_IP_LIMIT = 10;
|
||||
export const LOGIN_TOKEN_LIMIT = 20;
|
||||
const LOGIN_WINDOW_MS = 60 * 60 * 1000;
|
||||
/** Longer than a local signup day, which is the longest limit window. */
|
||||
const RATE_RETENTION_MS = 2 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/** Deletes limit counters older than the retention margin. The hourly cleanup uses this too. */
|
||||
export function purgeRateHits(db: Database.Database, now: string): number {
|
||||
const cutoff = formatUtc(Temporal.Instant.from(now).subtract({ milliseconds: RATE_RETENTION_MS }));
|
||||
return db.prepare('DELETE FROM rate_hits WHERE window_start < ?').run(cutoff).changes;
|
||||
}
|
||||
|
||||
export type RateDecision = { limited: false } | { limited: true; retryAfter: number };
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function recordSwitchAttempt(
|
||||
db: Database.Database,
|
||||
secret: string,
|
||||
now: string,
|
||||
timeZone: string,
|
||||
ip: string,
|
||||
emails: string[],
|
||||
): RateDecision {
|
||||
const recipientWindow = dayWindow(now, timeZone);
|
||||
const buckets = [
|
||||
{ kind: 'switch-ip', id: ip, limit: SWITCH_IP_LIMIT, window: ipWindow(now) },
|
||||
...[...new Set(emails.map(normalizeEmail))].map((id) => ({
|
||||
kind: 'switch-recipient', id, limit: SWITCH_RECIPIENT_LIMIT, window: recipientWindow,
|
||||
})),
|
||||
].map((bucket) => ({
|
||||
...bucket,
|
||||
key: createHmac('sha256', secret).update(`${bucket.kind}\0${bucket.id}`).digest('hex'),
|
||||
}));
|
||||
return db.transaction((): RateDecision => {
|
||||
purgeRateHits(db, now);
|
||||
const read = db.prepare('SELECT count FROM rate_hits WHERE key = ? AND window_start = ?');
|
||||
let retryAfter = 0;
|
||||
for (const bucket of buckets) {
|
||||
const row = read.get(bucket.key, bucket.window.start) as { count: number } | undefined;
|
||||
if (row && row.count >= bucket.limit) retryAfter = Math.max(retryAfter, bucket.window.retryAfter);
|
||||
}
|
||||
if (retryAfter > 0) return { limited: true, retryAfter };
|
||||
const increment = db.prepare(
|
||||
`INSERT INTO rate_hits (key, window_start, count) VALUES (?, ?, 1)
|
||||
ON CONFLICT (key, window_start) DO UPDATE SET count = count + 1`,
|
||||
);
|
||||
for (const bucket of buckets) increment.run(bucket.key, bucket.window.start);
|
||||
return { limited: false };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts signup attempts. Keys are HMAC digests, so the table does not store
|
||||
* raw email addresses or IP addresses. The email allowance counts only after
|
||||
* Turnstile and field checks pass, so a failed widget cannot lock someone out
|
||||
* for the day. The IP allowance counts every signup POST.
|
||||
*/
|
||||
export function recordSignupIp(db: Database.Database, secret: string, now: string, ip: string): RateDecision {
|
||||
return record(db, secret, now, { kind: 'signup-ip', id: ip, limit: SIGNUP_IP_LIMIT, window: ipWindow(now) });
|
||||
}
|
||||
|
||||
/** Counts unknown or expired manage links. A valid link does not use this allowance. */
|
||||
export function recordInvalidManageToken(db: Database.Database, secret: string, now: string, ip: string): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'manage-token',
|
||||
id: ip,
|
||||
limit: MANAGE_TOKEN_LIMIT,
|
||||
window: ipWindow(now),
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts sign-in requests from one network. A failed check still uses this allowance. */
|
||||
export function recordLoginIp(db: Database.Database, secret: string, now: string, ip: string): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'login-ip',
|
||||
id: ip,
|
||||
limit: LOGIN_IP_LIMIT,
|
||||
window: fixedWindow(now, LOGIN_WINDOW_MS),
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts sign-in requests for one address after the check succeeds, whether or not a coordinator uses it. */
|
||||
export function recordLoginEmail(db: Database.Database, secret: string, now: string, emailNorm: string): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'login-email',
|
||||
id: emailNorm,
|
||||
limit: LOGIN_EMAIL_LIMIT,
|
||||
window: fixedWindow(now, LOGIN_WINDOW_MS),
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts invalid reminder opt-out links. A valid link does not use this allowance. */
|
||||
export function recordInvalidUnsubscribe(db: Database.Database, secret: string, now: string, ip: string): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'reminder-off',
|
||||
id: ip,
|
||||
limit: MANAGE_TOKEN_LIMIT,
|
||||
window: ipWindow(now),
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts invalid sign-in links. A valid link does not use this allowance. */
|
||||
export function recordInvalidLoginToken(db: Database.Database, secret: string, now: string, ip: string): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'login-token',
|
||||
id: ip,
|
||||
limit: LOGIN_TOKEN_LIMIT,
|
||||
window: ipWindow(now),
|
||||
});
|
||||
}
|
||||
|
||||
export function recordSignupEmail(
|
||||
db: Database.Database,
|
||||
secret: string,
|
||||
now: string,
|
||||
timeZone: string,
|
||||
emailNorm: string,
|
||||
): RateDecision {
|
||||
return record(db, secret, now, {
|
||||
kind: 'signup-email',
|
||||
id: emailNorm,
|
||||
limit: SIGNUP_EMAIL_LIMIT,
|
||||
window: dayWindow(now, timeZone),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
now: string,
|
||||
input: { kind: string; id: string; limit: number; window: { start: string; retryAfter: number } },
|
||||
): RateDecision {
|
||||
const key = createHmac('sha256', secret).update(`${input.kind}\0${input.id}`).digest('hex');
|
||||
const count = db.transaction(() => {
|
||||
purgeRateHits(db, now);
|
||||
const row = db
|
||||
.prepare(
|
||||
`INSERT INTO rate_hits (key, window_start, count) VALUES (?, ?, 1)
|
||||
ON CONFLICT (key, window_start) DO UPDATE SET count = count + 1
|
||||
RETURNING count`,
|
||||
)
|
||||
.get(key, input.window.start) as { count: number };
|
||||
return row.count;
|
||||
}).immediate();
|
||||
if (count > input.limit) return { limited: true, retryAfter: input.window.retryAfter };
|
||||
return { limited: false };
|
||||
}
|
||||
|
||||
function ipWindow(now: string): { start: string; retryAfter: number } {
|
||||
return fixedWindow(now, SIGNUP_IP_WINDOW_MS);
|
||||
}
|
||||
|
||||
function fixedWindow(now: string, windowMs: number): { start: string; retryAfter: number } {
|
||||
const epoch = Temporal.Instant.from(now).epochMilliseconds;
|
||||
const startMs = Math.floor(epoch / windowMs) * windowMs;
|
||||
const retryAfter = Math.max(1, Math.ceil((startMs + windowMs - epoch) / 1000));
|
||||
return { start: formatUtc(Temporal.Instant.fromEpochMilliseconds(startMs)), retryAfter };
|
||||
}
|
||||
|
||||
function dayWindow(now: string, timeZone: string): { start: string; retryAfter: number } {
|
||||
const zoned = Temporal.Instant.from(now).toZonedDateTimeISO(timeZone);
|
||||
const start = zoned.startOfDay();
|
||||
const next = start.add({ days: 1 });
|
||||
const retryAfter = Math.max(
|
||||
1,
|
||||
Math.ceil((next.toInstant().epochMilliseconds - zoned.epochMilliseconds) / 1000),
|
||||
);
|
||||
return { start: formatUtc(start.toInstant()), retryAfter };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { recoverCoordinator } from './auth/recover.js';
|
||||
import { loadConfig } from './config.js';
|
||||
import { openAppDatabase } from './db.js';
|
||||
import { nowUtc } from './time.js';
|
||||
|
||||
/**
|
||||
* Host recovery command. In the container:
|
||||
* docker compose exec hope-volunteer node dist/recover-coordinator.js <current-email> [--replace <new-email>]
|
||||
* The container already has its configuration, so no --env-file is needed there.
|
||||
*/
|
||||
|
||||
// Same as the server: the database is owner-only.
|
||||
process.umask(0o077);
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const email = args[0] ?? '';
|
||||
const replaceFlag = args.indexOf('--replace');
|
||||
const replaceWith = replaceFlag === -1 ? undefined : args[replaceFlag + 1];
|
||||
|
||||
if (!email || email.startsWith('--') || (replaceFlag !== -1 && (!replaceWith || replaceWith.startsWith('--')))) {
|
||||
console.error('Usage: node dist/recover-coordinator.js <current-email> [--replace <new-email>]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const config = loadConfig(process.env);
|
||||
const db = await openAppDatabase(config);
|
||||
try {
|
||||
const result = recoverCoordinator(db, { email, replaceWith, now: nowUtc() });
|
||||
const verb = replaceWith ? 'Updated the sign-in address and revoked old sessions' : 'Revoked sessions and unused sign-in links';
|
||||
console.log(`${verb} for coordinator ${result.coordinatorId}.`);
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : err);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { writeAudit } from './auth/audit.js';
|
||||
import { LocalTimeError, addLocalDays, localShiftToUtc, todayInZone } from './time.js';
|
||||
|
||||
/** How far ahead an active template fills the schedule, counted in local days. */
|
||||
export const TEMPLATE_HORIZON_DAYS = 56;
|
||||
|
||||
export type ExpandResult = {
|
||||
created: number;
|
||||
templates: number;
|
||||
skipped: string[];
|
||||
};
|
||||
|
||||
type TemplateRow = {
|
||||
id: number;
|
||||
event_id: number;
|
||||
role: string;
|
||||
weekday: number;
|
||||
start_local: string;
|
||||
end_local: string;
|
||||
capacity: number;
|
||||
starts_on: string;
|
||||
ends_on: string | null;
|
||||
revision: number;
|
||||
tz: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add missing shifts from active weekly templates. A date that already has a
|
||||
* row for that template is left alone, including a cancelled row, so generation
|
||||
* cannot recreate or overwrite it. A local time that does not exist, or that
|
||||
* happens twice, is skipped instead of moved.
|
||||
*/
|
||||
export function expandTemplates(
|
||||
db: Database.Database,
|
||||
now: string,
|
||||
options?: { eventId?: number; timeZone?: string; coordinatorId?: number | null },
|
||||
): ExpandResult {
|
||||
const coordinatorId = options?.coordinatorId ?? null;
|
||||
const eventId = options?.eventId;
|
||||
const timeZone = options?.timeZone;
|
||||
const run = db.transaction((): ExpandResult => {
|
||||
const templates = listTemplates(db, eventId, timeZone);
|
||||
let created = 0;
|
||||
const skipped: string[] = [];
|
||||
for (const template of templates) {
|
||||
const outcome = expandOne(db, template, now, coordinatorId);
|
||||
created += outcome.created;
|
||||
skipped.push(...outcome.skipped);
|
||||
}
|
||||
return { created, templates: templates.length, skipped };
|
||||
});
|
||||
return run.immediate();
|
||||
}
|
||||
|
||||
function listTemplates(db: Database.Database, eventId: number | undefined, timeZone: string | undefined): TemplateRow[] {
|
||||
const filters = ['t.active = 1'];
|
||||
const params: Array<number | string> = [];
|
||||
if (eventId !== undefined) {
|
||||
filters.push('t.event_id = ?');
|
||||
params.push(eventId);
|
||||
}
|
||||
if (timeZone !== undefined) {
|
||||
filters.push('e.tz = ?');
|
||||
params.push(timeZone);
|
||||
}
|
||||
const sql = `SELECT t.id AS id, t.event_id AS event_id, t.role AS role, t.weekday AS weekday,
|
||||
t.start_local AS start_local, t.end_local AS end_local, t.capacity AS capacity,
|
||||
t.starts_on AS starts_on, t.ends_on AS ends_on, t.revision AS revision, e.tz AS tz
|
||||
FROM shift_templates t
|
||||
JOIN events e ON e.id = t.event_id
|
||||
WHERE ${filters.join(' AND ')}
|
||||
ORDER BY t.id`;
|
||||
return db.prepare(sql).all(...params) as TemplateRow[];
|
||||
}
|
||||
|
||||
function expandOne(
|
||||
db: Database.Database,
|
||||
template: TemplateRow,
|
||||
now: string,
|
||||
coordinatorId: number | null,
|
||||
): { created: number; skipped: string[] } {
|
||||
let today: string;
|
||||
try {
|
||||
today = todayInZone(template.tz, Temporal.Instant.from(now));
|
||||
} catch (err) {
|
||||
if (err instanceof LocalTimeError) return { created: 0, skipped: [err.message] };
|
||||
throw err;
|
||||
}
|
||||
const windowEnd = addLocalDays(today, TEMPLATE_HORIZON_DAYS);
|
||||
const dates = occurrenceDates(template, today, windowEnd);
|
||||
const insert = db.prepare(
|
||||
`INSERT OR IGNORE INTO shifts (
|
||||
event_id, template_id, occurrence_date, template_revision, role,
|
||||
starts_at_utc, ends_at_utc, capacity, notes, cancelled, manually_modified, version
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '', 0, 0, 1)`,
|
||||
);
|
||||
let created = 0;
|
||||
const skipped: string[] = [];
|
||||
for (const date of dates) {
|
||||
let times: { startsAtUtc: string; endsAtUtc: string };
|
||||
try {
|
||||
times = localShiftToUtc(date, template.start_local, template.end_local, template.tz);
|
||||
} catch (err) {
|
||||
if (err instanceof LocalTimeError) {
|
||||
skipped.push(err.message);
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
const saved = insert.run(
|
||||
template.event_id,
|
||||
template.id,
|
||||
date,
|
||||
template.revision,
|
||||
template.role,
|
||||
times.startsAtUtc,
|
||||
times.endsAtUtc,
|
||||
template.capacity,
|
||||
);
|
||||
if (saved.changes === 1) created += 1;
|
||||
}
|
||||
if (created > 0) {
|
||||
writeAudit(db, coordinatorId, 'template.expand', { templateId: template.id, created }, now);
|
||||
}
|
||||
return { created, skipped };
|
||||
}
|
||||
|
||||
function occurrenceDates(template: TemplateRow, today: string, windowEnd: string): string[] {
|
||||
let start = today > template.starts_on ? today : template.starts_on;
|
||||
let end = windowEnd;
|
||||
if (template.ends_on && template.ends_on < end) end = template.ends_on;
|
||||
if (start > end) return [];
|
||||
let date = Temporal.PlainDate.from(start);
|
||||
const last = Temporal.PlainDate.from(end);
|
||||
const weekday = date.dayOfWeek % 7;
|
||||
date = date.add({ days: (template.weekday - weekday + 7) % 7 });
|
||||
const dates: string[] = [];
|
||||
while (Temporal.PlainDate.compare(date, last) <= 0) {
|
||||
dates.push(date.toString());
|
||||
date = date.add({ days: 7 });
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { getConnInfo } from '@hono/node-server/conninfo';
|
||||
import type { Context, Hono } from 'hono';
|
||||
import type { Child } from 'hono/jsx';
|
||||
import { readSession } from './auth/session.js';
|
||||
import { clientAddress } from './client-ip.js';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { Layout, NotFoundPage, ReminderOffPage, WaitPage } from './pages.js';
|
||||
import { recordInvalidUnsubscribe } from './rate-limit.js';
|
||||
import { disableReminders, readReminderOffToken } from './reminders.js';
|
||||
import { readReplyTo } from './settings.js';
|
||||
import { isBusy } from './sqlite-error.js';
|
||||
import { appPath } from './url.js';
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
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, <ReminderOffPage config={services.config} token={c.req.param('token') ?? ''} replyTo={readReplyTo(services.db, services.config.mail.replyTo)} off={off} />);
|
||||
}
|
||||
|
||||
async function submitReminderOff(
|
||||
c: Context,
|
||||
services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null },
|
||||
): Promise<Response> {
|
||||
const token = c.req.param('token') ?? '';
|
||||
const signupId = readReminderOffToken(services.config.sessionSecret, token);
|
||||
if (signupId === null || !reminderSignup(services.db, signupId)) return unavailable(c, services);
|
||||
try {
|
||||
const result = disableReminders(services.db, 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, <ReminderOffPage config={services.config} token={token} replyTo={readReplyTo(services.db, services.config.mail.replyTo)} off={false} error="This could not be saved. Please try again." />, 503);
|
||||
}
|
||||
return page(c, services, <ReminderOffPage config={services.config} token={token} replyTo={readReplyTo(services.db, services.config.mail.replyTo)} off />);
|
||||
}
|
||||
|
||||
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 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;
|
||||
}
|
||||
|
||||
function unavailable(
|
||||
c: Context,
|
||||
services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null },
|
||||
) {
|
||||
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, <WaitPage />, 429);
|
||||
}
|
||||
return page(c, services, <NotFoundPage />, 404);
|
||||
}
|
||||
|
||||
function peerAddress(c: Context, override?: (c: Context) => string | null): string | null {
|
||||
if (override) return override(c);
|
||||
try {
|
||||
return getConnInfo(c).remote.address ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function page(
|
||||
c: Context,
|
||||
services: { config: AppConfig; db: Database.Database; now: () => string },
|
||||
body: Child,
|
||||
status: 200 | 404 | 429 | 503 = 200,
|
||||
) {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
const account = readSession(services.db, c.req.header('cookie'), services.now());
|
||||
return c.html(
|
||||
<Layout config={services.config} title="Reminder emails · Hope Volunteer" path={c.req.path} account={account ? { csrf: account.csrf } : null}>
|
||||
{body}
|
||||
</Layout>,
|
||||
status,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { MailIdentity } from './mail/types.js';
|
||||
import { queueDueReminders } from './reminders.js';
|
||||
|
||||
const INTERVAL_MS = 5 * 60 * 1000;
|
||||
|
||||
/** One reminder pass every five minutes. A pass that is still running is not started again. */
|
||||
export function startReminderRunner(
|
||||
db: Database.Database,
|
||||
mail: MailIdentity,
|
||||
secret: string,
|
||||
now: () => string,
|
||||
): { stop: () => void } {
|
||||
let running = false;
|
||||
let stopped = false;
|
||||
const tick = () => {
|
||||
if (running || stopped) return;
|
||||
running = true;
|
||||
try {
|
||||
queueDueReminders(db, mail, secret, now());
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : 'Reminder queue failed.');
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
const timer = setInterval(tick, INTERVAL_MS);
|
||||
timer.unref();
|
||||
tick();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
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 { absoluteUrl } from './url.js';
|
||||
|
||||
export type ReminderPass = { queued: number; suppressed: number };
|
||||
|
||||
type DueSignup = {
|
||||
id: number;
|
||||
name: string;
|
||||
email_norm: string;
|
||||
guardian_email: string | null;
|
||||
version: number;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
role: string;
|
||||
title: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
shift_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Queues reminders that are due and still before the shift starts.
|
||||
* When more than one offset is already due, only the closest one is sent.
|
||||
* Older offsets are recorded as not sent, so a late signup does not get every missed reminder.
|
||||
* The same signup, offset, and shift version is not queued twice.
|
||||
* Offset hours and the reply-to address come from coordinator settings, or the defaults when none are saved.
|
||||
*/
|
||||
export function queueDueReminders(db: Database.Database, mail: MailIdentity, secret: string, now: string): ReminderPass {
|
||||
return db.transaction((): ReminderPass => {
|
||||
const offsets = readReminderOffsets(db);
|
||||
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,
|
||||
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
|
||||
FROM signups su
|
||||
JOIN shifts s ON s.id = su.shift_id
|
||||
JOIN events e ON e.id = s.event_id
|
||||
WHERE su.status = 'confirmed'
|
||||
AND su.reminders_off = 0
|
||||
AND su.anonymized_at IS NULL
|
||||
AND su.name IS NOT NULL
|
||||
AND su.email_norm IS NOT NULL
|
||||
AND s.cancelled = 0
|
||||
AND s.starts_at_utc > ?`,
|
||||
)
|
||||
.all(now) as DueSignup[];
|
||||
let queued = 0;
|
||||
let suppressed = 0;
|
||||
const nowInstant = Temporal.Instant.from(now);
|
||||
for (const row of rows) {
|
||||
const start = Temporal.Instant.from(row.starts_at_utc);
|
||||
const due = offsets.filter((offset) => {
|
||||
const dueAt = start.subtract({ hours: offset.hours });
|
||||
return Temporal.Instant.compare(nowInstant, dueAt) >= 0 && !alreadyQueued(db, row.id, offset.kind, row.version);
|
||||
});
|
||||
if (due.length === 0) continue;
|
||||
const nearest = due.reduce((closest, offset) => (offset.hours < closest.hours ? offset : closest));
|
||||
if (insertReminder(db, row, nearest.kind, activeMail, secret, now, 'pending')) queued += 1;
|
||||
for (const offset of due) {
|
||||
if (offset.kind === nearest.kind) continue;
|
||||
if (insertReminder(db, row, offset.kind, activeMail, secret, now, 'suppressed')) suppressed += 1;
|
||||
}
|
||||
}
|
||||
return { queued, suppressed };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
/** Turns reminders off for one signup. Confirmation, change, and cancellation mail still queue. */
|
||||
export function disableReminders(
|
||||
db: Database.Database,
|
||||
signupId: number,
|
||||
now: string,
|
||||
): { ok: true; already: boolean } | { ok: false } {
|
||||
return db.transaction((): { ok: true; already: boolean } | { ok: false } => {
|
||||
const row = db
|
||||
.prepare('SELECT reminders_off AS reminders_off FROM signups WHERE id = ? AND anonymized_at IS NULL')
|
||||
.get(signupId) as { reminders_off: number } | undefined;
|
||||
if (!row) return { ok: false };
|
||||
if (row.reminders_off !== 1) {
|
||||
db.prepare('UPDATE signups SET reminders_off = 1, updated_at = ? WHERE id = ? AND anonymized_at IS NULL').run(now, signupId);
|
||||
}
|
||||
cancelPendingReminders(db, signupId, 'Reminders were turned off before this message was sent.');
|
||||
return { ok: true, already: row.reminders_off === 1 };
|
||||
}).immediate();
|
||||
}
|
||||
|
||||
export function issueReminderOffToken(secret: string, signupId: number): string {
|
||||
const id = String(signupId);
|
||||
const mac = createHmac('sha256', secret).update(`hope-reminder-off-v1\0${id}`).digest('base64url');
|
||||
return `${id}.${mac}`;
|
||||
}
|
||||
|
||||
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('.')));
|
||||
if (!Number.isSafeInteger(id) || id <= 0) return null;
|
||||
const expected = issueReminderOffToken(secret, id);
|
||||
const left = Buffer.from(expected);
|
||||
const right = Buffer.from(token);
|
||||
if (left.length !== right.length || !timingSafeEqual(left, right)) return null;
|
||||
return id;
|
||||
}
|
||||
|
||||
function alreadyQueued(db: Database.Database, signupId: number, kind: string, version: number): boolean {
|
||||
const row = db
|
||||
.prepare('SELECT signup_id FROM reminders_sent WHERE signup_id = ? AND kind = ? AND shift_version = ?')
|
||||
.get(signupId, kind, version);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
function insertReminder(
|
||||
db: Database.Database,
|
||||
row: DueSignup,
|
||||
kind: string,
|
||||
mail: MailIdentity,
|
||||
secret: string,
|
||||
now: string,
|
||||
mode: 'pending' | 'suppressed',
|
||||
): 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);
|
||||
if (volunteerId === null) return false;
|
||||
const saved = db
|
||||
.prepare(
|
||||
`INSERT INTO reminders_sent (signup_id, kind, shift_version, outbox_id, queued_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
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;
|
||||
}
|
||||
|
||||
function insertOutbox(
|
||||
db: Database.Database,
|
||||
row: DueSignup,
|
||||
kind: string,
|
||||
recipient: string,
|
||||
audience: 'volunteer' | 'guardian',
|
||||
mail: MailIdentity,
|
||||
headers: Record<string, string>,
|
||||
unsubscribeUrl: string,
|
||||
now: string,
|
||||
mode: 'pending' | 'suppressed',
|
||||
): number | null {
|
||||
const rendered = mode === 'pending'
|
||||
? renderReminder({
|
||||
audience,
|
||||
volunteerName: row.name,
|
||||
shift: shiftFacts(row),
|
||||
unsubscribeUrl,
|
||||
replyTo: mail.replyTo,
|
||||
})
|
||||
: { subject: 'Reminder not sent', text: 'This reminder was not sent.', html: '<p>This reminder was not sent.</p>' };
|
||||
const saved = db
|
||||
.prepare(
|
||||
`INSERT INTO outbox (
|
||||
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||
headers_json, send_after, attempts, status, created_at, last_error
|
||||
) VALUES (?, ?, ?, 'reminder', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)
|
||||
ON CONFLICT (dedupe_key) DO NOTHING`,
|
||||
)
|
||||
.run(
|
||||
`reminder:v${row.version}:${row.id}:${kind}:${recipient}`,
|
||||
row.id,
|
||||
row.shift_id,
|
||||
recipient,
|
||||
rendered.subject,
|
||||
rendered.text,
|
||||
rendered.html,
|
||||
JSON.stringify({ From: mail.from, 'Reply-To': mail.replyTo, ...headers }),
|
||||
now,
|
||||
mode === 'pending' ? 'pending' : 'cancelled',
|
||||
now,
|
||||
mode === 'pending' ? null : 'A closer reminder was already due, so this one was not sent.',
|
||||
);
|
||||
if (saved.changes !== 1) return null;
|
||||
return Number(saved.lastInsertRowid);
|
||||
}
|
||||
|
||||
function reminderHeaders(mail: MailIdentity, unsubscribeUrl: string): Record<string, string> {
|
||||
const subject = encodeURIComponent('Stop reminder emails');
|
||||
return {
|
||||
'List-Unsubscribe': `<mailto:${mail.replyTo}?subject=${subject}>, <${unsubscribeUrl}>`,
|
||||
'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
|
||||
};
|
||||
}
|
||||
|
||||
function shiftFacts(row: DueSignup): { role: string; eventTitle: string; location: string; whenLabel: string } {
|
||||
const start = formatInstantInZone(row.starts_at_utc, row.tz);
|
||||
const end = formatInstantInZone(row.ends_at_utc, row.tz);
|
||||
return {
|
||||
role: row.role,
|
||||
eventTitle: row.title,
|
||||
location: row.location,
|
||||
whenLabel: `${start.dateLabel}, ${start.timeLabel} to ${end.timeLabel} ${end.abbreviation}`,
|
||||
};
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { formatInstantInZone } from './time.js';
|
||||
|
||||
export type PublicShift = {
|
||||
id: number;
|
||||
role: string;
|
||||
startsAtUtc: string;
|
||||
endsAtUtc: string;
|
||||
capacity: number;
|
||||
occupied: number;
|
||||
remaining: number;
|
||||
full: boolean;
|
||||
cancelled: boolean;
|
||||
ended: boolean;
|
||||
inProgress: boolean;
|
||||
event: {
|
||||
id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string;
|
||||
location: string;
|
||||
timeZone: string;
|
||||
};
|
||||
when: {
|
||||
date: string;
|
||||
dateLabel: string;
|
||||
endDateLabel: string;
|
||||
sameDay: boolean;
|
||||
startLabel: string;
|
||||
endLabel: string;
|
||||
abbreviation: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type PublicEvent = {
|
||||
id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string;
|
||||
location: string;
|
||||
timeZone: string;
|
||||
shifts: PublicShift[];
|
||||
};
|
||||
|
||||
type ShiftRow = {
|
||||
id: number;
|
||||
role: string;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
capacity: number;
|
||||
cancelled: number;
|
||||
event_id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
occupied: number;
|
||||
};
|
||||
|
||||
const SHIFT_COLUMNS = `
|
||||
s.id AS id,
|
||||
s.role AS role,
|
||||
s.starts_at_utc AS starts_at_utc,
|
||||
s.ends_at_utc AS ends_at_utc,
|
||||
s.capacity AS capacity,
|
||||
s.cancelled AS cancelled,
|
||||
e.id AS event_id,
|
||||
e.slug AS slug,
|
||||
e.title AS title,
|
||||
e.description AS description,
|
||||
e.location AS location,
|
||||
e.tz AS tz,
|
||||
COALESCE(SUM(CASE WHEN su.status = 'confirmed' THEN su.group_size ELSE 0 END), 0) AS occupied
|
||||
`;
|
||||
|
||||
const SHIFT_FROM = `
|
||||
FROM shifts s
|
||||
JOIN events e ON e.id = s.event_id
|
||||
LEFT JOIN signups su ON su.shift_id = s.id
|
||||
`;
|
||||
|
||||
export function getPublishedEvent(db: Database.Database, slug: string, now: string): PublicEvent | null {
|
||||
const event = db
|
||||
.prepare(
|
||||
`SELECT id, slug, title, description, location, tz, published
|
||||
FROM events WHERE slug = ?`,
|
||||
)
|
||||
.get(slug) as
|
||||
| {
|
||||
id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
published: number;
|
||||
}
|
||||
| undefined;
|
||||
if (!event || event.published !== 1) return null;
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT ${SHIFT_COLUMNS}
|
||||
${SHIFT_FROM}
|
||||
WHERE e.id = ? AND s.cancelled = 0 AND s.ends_at_utc > ?
|
||||
GROUP BY s.id
|
||||
ORDER BY s.starts_at_utc, s.role, s.id`,
|
||||
)
|
||||
.all(event.id, now) as ShiftRow[];
|
||||
return {
|
||||
id: event.id,
|
||||
slug: event.slug,
|
||||
title: event.title,
|
||||
description: event.description,
|
||||
location: event.location,
|
||||
timeZone: event.tz,
|
||||
shifts: rows.map((row) => presentShift(row, now)),
|
||||
};
|
||||
}
|
||||
|
||||
export function getPublicShift(db: Database.Database, id: number, now: string): PublicShift | null {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT ${SHIFT_COLUMNS}
|
||||
${SHIFT_FROM}
|
||||
WHERE s.id = ? AND e.published = 1
|
||||
GROUP BY s.id`,
|
||||
)
|
||||
.get(id) as ShiftRow | undefined;
|
||||
return row ? presentShift(row, now) : null;
|
||||
}
|
||||
|
||||
export function spotsSentence(shift: Pick<PublicShift, 'occupied' | 'capacity'>): string {
|
||||
const filled = Math.min(shift.capacity, Math.max(0, shift.occupied));
|
||||
return `${filled}/${shift.capacity} spots filled`;
|
||||
}
|
||||
|
||||
function presentShift(row: ShiftRow, now: string): PublicShift {
|
||||
const start = formatInstantInZone(row.starts_at_utc, row.tz);
|
||||
const end = formatInstantInZone(row.ends_at_utc, row.tz);
|
||||
const occupied = Number(row.occupied);
|
||||
const capacity = Number(row.capacity);
|
||||
const remaining = Math.max(0, capacity - occupied);
|
||||
const cancelled = row.cancelled === 1;
|
||||
const ended = row.ends_at_utc <= now;
|
||||
const inProgress = !cancelled && !ended && row.starts_at_utc <= now;
|
||||
return {
|
||||
id: row.id,
|
||||
role: row.role,
|
||||
startsAtUtc: row.starts_at_utc,
|
||||
endsAtUtc: row.ends_at_utc,
|
||||
capacity,
|
||||
occupied,
|
||||
remaining,
|
||||
full: !cancelled && !ended && remaining === 0,
|
||||
cancelled,
|
||||
ended,
|
||||
inProgress,
|
||||
event: {
|
||||
id: row.event_id,
|
||||
slug: row.slug,
|
||||
title: row.title,
|
||||
description: row.description,
|
||||
location: row.location,
|
||||
timeZone: row.tz,
|
||||
},
|
||||
when: {
|
||||
date: start.date,
|
||||
dateLabel: start.dateLabel,
|
||||
endDateLabel: end.dateLabel,
|
||||
sameDay: start.date === end.date,
|
||||
startLabel: start.timeLabel,
|
||||
endLabel: end.timeLabel,
|
||||
abbreviation: start.abbreviation,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { MiddlewareHandler } from 'hono';
|
||||
|
||||
/**
|
||||
* Baseline from the October 14, 2026 specification.
|
||||
* Signup pages load the Turnstile script in a frame. The widget also connects
|
||||
* to that same host. Do not widen this to a wildcard or unsafe-inline.
|
||||
*/
|
||||
export const CONTENT_SECURITY_POLICY = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self' https://challenges.cloudflare.com",
|
||||
'frame-src https://challenges.cloudflare.com',
|
||||
"connect-src 'self' https://challenges.cloudflare.com",
|
||||
"img-src 'self' data:",
|
||||
"style-src 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'none'",
|
||||
].join('; ');
|
||||
|
||||
/** The app uses no device features. */
|
||||
export const PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=(), payment=(), usb=()';
|
||||
|
||||
/** One year, this host only. Other pantry subdomains are not covered. */
|
||||
export const STRICT_TRANSPORT_SECURITY = 'max-age=31536000';
|
||||
|
||||
/** HSTS is sent only when BASE_URL is https. A browser ignores it over http. */
|
||||
export function securityHeaders(options: { https: boolean }): MiddlewareHandler {
|
||||
return async (c, next) => {
|
||||
await next();
|
||||
c.header('Content-Security-Policy', CONTENT_SECURITY_POLICY);
|
||||
c.header('Referrer-Policy', 'no-referrer');
|
||||
c.header('X-Content-Type-Options', 'nosniff');
|
||||
c.header('Permissions-Policy', PERMISSIONS_POLICY);
|
||||
if (options.https) c.header('Strict-Transport-Security', STRICT_TRANSPORT_SECURITY);
|
||||
};
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import { writeAudit } from './auth/audit.js';
|
||||
import { normalizeEmail } from './email.js';
|
||||
|
||||
/** Earlier reminder, then the closer one. Used when the coordinator has not saved a pair. */
|
||||
export const DEFAULT_REMINDER_HOURS = [48, 2] as const;
|
||||
export const DEFAULT_RETENTION_MONTHS = 24;
|
||||
export const MAX_REMINDER_HOURS = 336;
|
||||
export const MAX_RETENTION_MONTHS = 120;
|
||||
export const MAX_PRIVACY_TEXT = 8000;
|
||||
|
||||
const HOUR_KEY = 'reminder_hours';
|
||||
const REPLY_KEY = 'reply_to';
|
||||
const PRIVACY_KEY = 'privacy_text';
|
||||
const RETENTION_KEY = 'retention_months';
|
||||
|
||||
export type PantrySettings = {
|
||||
/** Larger hour count first, so the first reminder is the earlier one. */
|
||||
reminderHours: readonly [number, number];
|
||||
replyTo: string;
|
||||
privacyText: string;
|
||||
retentionMonths: number;
|
||||
};
|
||||
|
||||
export type SettingsForm = {
|
||||
reminderFar: string;
|
||||
reminderNear: string;
|
||||
replyTo: string;
|
||||
retentionMonths: string;
|
||||
privacyText: string;
|
||||
};
|
||||
|
||||
export type SettingsErrors = Partial<Record<keyof SettingsForm, string>>;
|
||||
|
||||
export function readRetentionMonths(db: Database.Database): number {
|
||||
return storedRetention(db);
|
||||
}
|
||||
|
||||
export function readPantrySettings(db: Database.Database, fallbackReplyTo: string): PantrySettings {
|
||||
return {
|
||||
reminderHours: storedHours(db),
|
||||
replyTo: storedReplyTo(db) ?? fallbackReplyTo,
|
||||
privacyText: storedPrivacy(db),
|
||||
retentionMonths: storedRetention(db),
|
||||
};
|
||||
}
|
||||
|
||||
/** Closest offset is first, so a late catch-up keeps the reminder nearest the shift. */
|
||||
export function readReminderOffsets(db: Database.Database): { kind: string; hours: number }[] {
|
||||
const [earlier, closer] = storedHours(db);
|
||||
return [
|
||||
{ kind: `${closer}h`, hours: closer },
|
||||
{ kind: `${earlier}h`, hours: earlier },
|
||||
];
|
||||
}
|
||||
|
||||
export function readReplyTo(db: Database.Database, fallback: string): string {
|
||||
return storedReplyTo(db) ?? fallback;
|
||||
}
|
||||
|
||||
export function privacyParagraphs(text: string): string[] {
|
||||
return text
|
||||
.split(/\n+/)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
}
|
||||
|
||||
export function settingsFormFrom(settings: PantrySettings): SettingsForm {
|
||||
return {
|
||||
reminderFar: String(settings.reminderHours[0]),
|
||||
reminderNear: String(settings.reminderHours[1]),
|
||||
replyTo: settings.replyTo,
|
||||
retentionMonths: String(settings.retentionMonths),
|
||||
privacyText: settings.privacyText,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSettingsForm(input: SettingsForm): { ok: true; value: PantrySettings } | { ok: false; errors: SettingsErrors } {
|
||||
const errors: SettingsErrors = {};
|
||||
const earlier = parseHour(input.reminderFar);
|
||||
const closer = parseHour(input.reminderNear);
|
||||
if (earlier === null) errors.reminderFar = `Enter a whole number of hours from 1 to ${MAX_REMINDER_HOURS}.`;
|
||||
if (closer === null) errors.reminderNear = `Enter a whole number of hours from 1 to ${MAX_REMINDER_HOURS}.`;
|
||||
if (earlier !== null && closer !== null && earlier === closer) {
|
||||
errors.reminderNear = 'The two reminder times have to be different.';
|
||||
}
|
||||
const reply = parseReply(input.replyTo);
|
||||
if (!reply.ok) errors.replyTo = reply.error;
|
||||
const months = parseMonths(input.retentionMonths);
|
||||
if (months === null) errors.retentionMonths = `Enter a whole number of months from 1 to ${MAX_RETENTION_MONTHS}.`;
|
||||
const privacy = parsePrivacy(input.privacyText);
|
||||
if (!privacy.ok) errors.privacyText = privacy.error;
|
||||
if (earlier === null || closer === null || earlier === closer || !reply.ok || months === null || !privacy.ok) {
|
||||
return { ok: false, errors };
|
||||
}
|
||||
const reminderHours: [number, number] = earlier > closer ? [earlier, closer] : [closer, earlier];
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
reminderHours,
|
||||
replyTo: reply.value,
|
||||
privacyText: privacy.value,
|
||||
retentionMonths: months,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the four coordinator settings. Retention is stored only.
|
||||
* This does not anonymize signups, and it does not change mail that is already queued.
|
||||
*/
|
||||
export function savePantrySettings(
|
||||
db: Database.Database,
|
||||
coordinatorId: number,
|
||||
next: PantrySettings,
|
||||
fallbackReplyTo: string,
|
||||
now: string,
|
||||
): { changed: boolean } {
|
||||
const current = readPantrySettings(db, fallbackReplyTo);
|
||||
const replyChanged = current.replyTo !== next.replyTo;
|
||||
const privacyChanged = current.privacyText !== next.privacyText;
|
||||
const hoursChanged = current.reminderHours[0] !== next.reminderHours[0] || current.reminderHours[1] !== next.reminderHours[1];
|
||||
const retentionChanged = current.retentionMonths !== next.retentionMonths;
|
||||
if (!replyChanged && !privacyChanged && !hoursChanged && !retentionChanged) return { changed: false };
|
||||
db.transaction(() => {
|
||||
writeValue(db, HOUR_KEY, [next.reminderHours[0], next.reminderHours[1]], now);
|
||||
writeValue(db, REPLY_KEY, next.replyTo, now);
|
||||
writeValue(db, PRIVACY_KEY, next.privacyText, now);
|
||||
writeValue(db, RETENTION_KEY, next.retentionMonths, now);
|
||||
writeAudit(
|
||||
db,
|
||||
coordinatorId,
|
||||
'settings.update',
|
||||
{
|
||||
reminderEarlier: next.reminderHours[0],
|
||||
reminderCloser: next.reminderHours[1],
|
||||
retentionMonths: next.retentionMonths,
|
||||
replyChanged: replyChanged ? 1 : 0,
|
||||
privacyChanged: privacyChanged ? 1 : 0,
|
||||
},
|
||||
now,
|
||||
);
|
||||
}).immediate();
|
||||
return { changed: true };
|
||||
}
|
||||
|
||||
function storedHours(db: Database.Database): readonly [number, number] {
|
||||
const value = readValue(db, HOUR_KEY);
|
||||
if (!Array.isArray(value) || value.length !== 2) return DEFAULT_REMINDER_HOURS;
|
||||
const first = value[0];
|
||||
const second = value[1];
|
||||
if (!isHour(first) || !isHour(second) || first === second) return DEFAULT_REMINDER_HOURS;
|
||||
return first > second ? [first, second] : [second, first];
|
||||
}
|
||||
|
||||
function storedReplyTo(db: Database.Database): string | null {
|
||||
const value = readValue(db, REPLY_KEY);
|
||||
if (typeof value !== 'string') return null;
|
||||
try {
|
||||
return normalizeEmail(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function storedPrivacy(db: Database.Database): string {
|
||||
const value = readValue(db, PRIVACY_KEY);
|
||||
if (typeof value !== 'string') return '';
|
||||
const parsed = parsePrivacy(value);
|
||||
return parsed.ok ? parsed.value : '';
|
||||
}
|
||||
|
||||
function storedRetention(db: Database.Database): number {
|
||||
const value = readValue(db, RETENTION_KEY);
|
||||
return isMonth(value) ? value : DEFAULT_RETENTION_MONTHS;
|
||||
}
|
||||
|
||||
function readValue(db: Database.Database, key: string): unknown {
|
||||
const row = db.prepare('SELECT value_json AS value_json FROM settings WHERE key = ?').get(key) as { value_json: string } | undefined;
|
||||
if (!row) return undefined;
|
||||
try {
|
||||
return JSON.parse(row.value_json) as unknown;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeValue(db: Database.Database, key: string, value: unknown, now: string): void {
|
||||
db.prepare(
|
||||
`INSERT INTO settings (key, value_json, updated_at) VALUES (?, ?, ?)
|
||||
ON CONFLICT (key) DO UPDATE SET value_json = excluded.value_json, updated_at = excluded.updated_at`,
|
||||
).run(key, JSON.stringify(value), now);
|
||||
}
|
||||
|
||||
function parseHour(value: string): number | null {
|
||||
const trimmed = value.trim();
|
||||
if (!/^[1-9][0-9]{0,2}$/.test(trimmed)) return null;
|
||||
const hours = Number(trimmed);
|
||||
return isHour(hours) ? hours : null;
|
||||
}
|
||||
|
||||
function parseMonths(value: string): number | null {
|
||||
const trimmed = value.trim();
|
||||
if (!/^[1-9][0-9]{0,2}$/.test(trimmed)) return null;
|
||||
const months = Number(trimmed);
|
||||
return isMonth(months) ? months : null;
|
||||
}
|
||||
|
||||
function parseReply(value: string): { ok: true; value: string } | { ok: false; error: string } {
|
||||
if (value.includes('<') || value.includes('>')) {
|
||||
return { ok: false, error: 'Enter an email address without a display name.' };
|
||||
}
|
||||
try {
|
||||
return { ok: true, value: normalizeEmail(value) };
|
||||
} catch {
|
||||
return { ok: false, error: 'Enter an email address.' };
|
||||
}
|
||||
}
|
||||
|
||||
function parsePrivacy(value: string): { ok: true; value: string } | { ok: false; error: string } {
|
||||
const cleaned = value.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/\t/g, ' ').trim();
|
||||
if (cleaned.length > MAX_PRIVACY_TEXT) return { ok: false, error: 'Keep the privacy wording under 8,000 characters.' };
|
||||
if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/.test(cleaned)) {
|
||||
return { ok: false, error: 'Remove the unusual character in the privacy wording.' };
|
||||
}
|
||||
return { ok: true, value: cleaned };
|
||||
}
|
||||
|
||||
function isHour(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_REMINDER_HOURS;
|
||||
}
|
||||
|
||||
function isMonth(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_RETENTION_MONTHS;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { z } from 'zod';
|
||||
import { EmailAddressError, normalizeEmail } from './email.js';
|
||||
|
||||
const NAME_MAX = 80;
|
||||
const PHONE_MAX = 40;
|
||||
const NOTES_MAX = 500;
|
||||
|
||||
export type SignupValues = {
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
notes: string;
|
||||
under18: boolean;
|
||||
guardianName: string;
|
||||
guardianEmail: string;
|
||||
};
|
||||
|
||||
export type SignupErrors = Partial<Record<'name' | 'email' | 'phone' | 'notes' | 'guardianName' | 'guardianEmail' | 'form', string>>;
|
||||
|
||||
export type SignupDraft = {
|
||||
name: string;
|
||||
email: string;
|
||||
emailNorm: string;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
isMinor: boolean;
|
||||
guardianName: string | null;
|
||||
guardianEmail: string | null;
|
||||
guardianEmailNorm: string | null;
|
||||
};
|
||||
|
||||
export const EMPTY_SIGNUP: SignupValues = {
|
||||
name: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
notes: '',
|
||||
under18: false,
|
||||
guardianName: '',
|
||||
guardianEmail: '',
|
||||
};
|
||||
|
||||
const controlChars = /[\u0000-\u001F\u007F]/;
|
||||
|
||||
export function parseSignupForm(
|
||||
input: SignupValues,
|
||||
voice: 'volunteer' | 'coordinator' = 'volunteer',
|
||||
): { ok: true; draft: SignupDraft } | { ok: false; errors: SignupErrors } {
|
||||
const parsed = z
|
||||
.object({
|
||||
name: z.string(),
|
||||
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.' } };
|
||||
const errors: SignupErrors = {};
|
||||
const name = parsed.data.name.normalize('NFC').trim();
|
||||
const nameLabel = voice === 'coordinator' ? 'their name' : 'your name';
|
||||
if (name.length === 0) errors.name = `Enter ${nameLabel}.`;
|
||||
else if (name.length > NAME_MAX) errors.name = `Use ${NAME_MAX} characters or fewer.`;
|
||||
else if (controlChars.test(name)) errors.name = `Enter ${nameLabel} without line breaks.`;
|
||||
|
||||
let emailNorm = '';
|
||||
try {
|
||||
emailNorm = normalizeEmail(parsed.data.email);
|
||||
} catch (err) {
|
||||
errors.email = err instanceof EmailAddressError ? err.message : 'Enter an email address.';
|
||||
}
|
||||
|
||||
const phone = parsed.data.phone.normalize('NFC').trim();
|
||||
if (phone.length > PHONE_MAX) errors.phone = `Use ${PHONE_MAX} characters or fewer.`;
|
||||
else if (controlChars.test(phone)) 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) {
|
||||
guardianName = parsed.data.guardianName.normalize('NFC').trim();
|
||||
if (guardianName.length === 0) errors.guardianName = 'Enter the guardian name.';
|
||||
else if (guardianName.length > NAME_MAX) errors.guardianName = `Use ${NAME_MAX} characters or fewer.`;
|
||||
else if (controlChars.test(guardianName)) 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 };
|
||||
return {
|
||||
ok: true,
|
||||
draft: {
|
||||
name,
|
||||
email: emailNorm,
|
||||
emailNorm,
|
||||
phone: phone.length === 0 ? null : 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,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import { getConnInfo } from '@hono/node-server/conninfo';
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { Context } from 'hono';
|
||||
import type { Hono } from 'hono';
|
||||
import type { Child } from 'hono/jsx';
|
||||
import { listMoveTargets, switchSignup } from './admin/store.js';
|
||||
import { cancelTokenMatches, issueCancelToken, issueReminderPageToken, issueSwitchToken, reminderPageTokenMatches, switchTokenMatches } from './cancel-token.js';
|
||||
import { clientAddress } from './client-ip.js';
|
||||
import { confirmationCookie, openConfirmation, sealConfirmation } from './confirm-cookie.js';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { issueFormToken, newOperationId, openFormToken, readFormToken } from './form-token.js';
|
||||
import { originAllowed } from './origin.js';
|
||||
import { readReplyTo } from './settings.js';
|
||||
import {
|
||||
ConfirmationPage,
|
||||
Layout,
|
||||
ManagePage,
|
||||
NotFoundPage,
|
||||
ShiftPage,
|
||||
SwitchAlreadyPage,
|
||||
WaitPage,
|
||||
type SignupFormView,
|
||||
type SwitchForm,
|
||||
} from './pages.js';
|
||||
import { recordInvalidManageToken, recordSignupEmail, recordSignupGuardian, 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';
|
||||
import { disableReminders } from './reminders.js';
|
||||
import { cancelSignup, confirmedOperationShift, findSignupByOperation, readManageSignup, reserveSignup } from './signup.js';
|
||||
import { verifyTurnstile, type TurnstileCheck, type TurnstileVerdict } from './turnstile.js';
|
||||
import { appPath, cookiePath } from './url.js';
|
||||
|
||||
const COULD_NOT_SAVE =
|
||||
'This signup could not be saved. If this shift is already in your confirmation, use that link.';
|
||||
const ALREADY_SIGNED_UP = 'That person is already signed up for this shift.';
|
||||
const TOO_FAST = 'Please wait a few seconds and submit the form again.';
|
||||
const CHECK_AGAIN = 'The check did not finish. Please try again.';
|
||||
const CHECK_UNAVAILABLE = 'The check could not be reached. Please try again in a little while.';
|
||||
const TOO_MANY = 'Too many signup attempts. Please wait and try again.';
|
||||
const FULL = 'This shift is full.';
|
||||
const CLOSED = 'This shift is closed.';
|
||||
const ORIGIN = 'The signup could not be sent from this page.';
|
||||
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.';
|
||||
const SWITCH_ORIGIN = 'The switch could not be sent from this page.';
|
||||
const SWITCH_REJECTED = 'The switch could not be confirmed. Please try again.';
|
||||
const SWITCH_UNAVAILABLE = 'The switch could not be saved. Please try again in a little while.';
|
||||
const SWITCH_STALE = 'This form is out of date. Submit it again.';
|
||||
const SWITCHED_NOTE = 'You are on this shift. This link replaces the earlier one. A change email is queued.';
|
||||
const EXPIRED = 'This form expired. Please submit it again.';
|
||||
|
||||
export type SignupServices = {
|
||||
config: AppConfig;
|
||||
db: Database.Database;
|
||||
now: () => string;
|
||||
clientIp?: (c: Context) => string | null;
|
||||
verifyTurnstile?: (input: TurnstileCheck) => Promise<TurnstileVerdict>;
|
||||
};
|
||||
|
||||
export function registerPublicSignup(app: Hono, services: SignupServices): void {
|
||||
const { config } = services;
|
||||
|
||||
app.get(appPath(config, '/s/:id'), (c) => {
|
||||
const shift = loadShift(services, c.req.param('id') ?? '');
|
||||
if (!shift) return html(c, config, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
return shiftResponse(c, services, shift, 200, blankForm(services, shift));
|
||||
});
|
||||
|
||||
app.post(appPath(config, '/s/:id'), (c) => submitSignup(c, services));
|
||||
|
||||
app.get(appPath(config, '/s/:id/confirmed'), (c) => {
|
||||
const shift = loadShift(services, c.req.param('id') ?? '');
|
||||
if (!shift) return html(c, config, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
const seal = openConfirmation(config.sessionSecret, c.req.header('cookie'), epochMs(services.now()));
|
||||
const manage = seal && seal.shiftId === shift.id ? readManageSignup(services.db, seal.token, services.now()) : null;
|
||||
const matches = Boolean(manage && seal && manage.signupId === seal.signupId);
|
||||
const cancelled = matches && manage?.status === 'cancelled';
|
||||
return html(
|
||||
c,
|
||||
config,
|
||||
cancelled ? 'This signup is cancelled · Hope Volunteer' : "You're signed up · Hope Volunteer",
|
||||
<ConfirmationPage
|
||||
config={config}
|
||||
shift={shift}
|
||||
name={matches && manage ? manage.name : null}
|
||||
managePath={matches && seal ? appPath(config, `/m/${seal.token}`) : null}
|
||||
cancelled={cancelled}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
app.get(appPath(config, '/m/:token'), (c) => showManage(c, services, c.req.param('token') ?? ''));
|
||||
|
||||
app.post(appPath(config, '/m/:token/switch'), (c) => submitSwitch(c, services));
|
||||
app.post(appPath(config, '/m/:token/reminders'), (c) => submitRemindersOff(c, services));
|
||||
app.post(appPath(config, '/m/:token'), (c) => submitCancel(c, services));
|
||||
}
|
||||
|
||||
async function submitSignup(c: Context, services: SignupServices): Promise<Response> {
|
||||
const { config, db } = services;
|
||||
const now = services.now();
|
||||
const shift = loadShift(services, c.req.param('id') ?? '');
|
||||
if (!shift) return html(c, config, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
const ip = clientAddress(config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for'));
|
||||
if (!originAllowed(c, config.baseUrl)) {
|
||||
return shiftResponse(c, services, shift, 403, formFor(services, shift, EMPTY_SIGNUP, {}, null), ORIGIN);
|
||||
}
|
||||
const ipLimit = recordSignupIp(db, config.sessionSecret, now, ip);
|
||||
if (ipLimit.limited) {
|
||||
return shiftResponse(c, services, shift, 429, blankForm(services, shift), TOO_MANY, ipLimit.retryAfter);
|
||||
}
|
||||
const body = await c.req.parseBody();
|
||||
const values = valuesFrom(body);
|
||||
if (textField(body, 'company_website').trim() !== '') {
|
||||
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null), COULD_NOT_SAVE);
|
||||
}
|
||||
const tokenResult = readFormToken(config.sessionSecret, textField(body, 'form_token'), shift.id, epochMs(now));
|
||||
if (!tokenResult.ok) {
|
||||
const notice = tokenResult.reason === 'too_fast' ? TOO_FAST : EXPIRED;
|
||||
const token = tokenResult.reason === 'too_fast' ? textField(body, 'form_token') : null;
|
||||
return shiftResponse(c, services, shift, 400, formFor(services, shift, values, {}, token), notice);
|
||||
}
|
||||
const parsed = parseSignupForm(values);
|
||||
if (!parsed.ok) {
|
||||
return shiftResponse(c, services, shift, 400, formFor(services, shift, values, parsed.errors, textField(body, 'form_token')), undefined);
|
||||
}
|
||||
const existing = findSignupByOperation(db, tokenResult.claims.operationId);
|
||||
if (existing && existing.shiftId === shift.id && existing.emailNorm === parsed.draft.emailNorm) {
|
||||
return redirectConfirmed(c, services, shift.id, null);
|
||||
}
|
||||
if (existing) {
|
||||
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null), COULD_NOT_SAVE);
|
||||
}
|
||||
const turnstileToken = textField(body, 'cf-turnstile-response').trim();
|
||||
const verdict = turnstileToken === ''
|
||||
? ({ ok: false, reason: 'rejected' } as const)
|
||||
: await checkTurnstile(services, turnstileToken, ip);
|
||||
if (!verdict.ok) {
|
||||
if (verdict.reason === 'duplicate') {
|
||||
const again = findSignupByOperation(db, tokenResult.claims.operationId);
|
||||
if (again && again.shiftId === shift.id && again.emailNorm === parsed.draft.emailNorm) {
|
||||
return redirectConfirmed(c, services, shift.id, null);
|
||||
}
|
||||
}
|
||||
const notice = verdict.reason === 'unavailable' ? CHECK_UNAVAILABLE : CHECK_AGAIN;
|
||||
return shiftResponse(c, services, shift, verdict.reason === 'unavailable' ? 503 : 400, formFor(services, shift, values, {}, textField(body, 'form_token')), notice);
|
||||
}
|
||||
const emailLimit = recordSignupEmail(db, config.sessionSecret, now, config.defaultTimeZone, parsed.draft.emailNorm);
|
||||
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,
|
||||
name: parsed.draft.name,
|
||||
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),
|
||||
});
|
||||
if (reserved.ok) return redirectConfirmed(c, services, shift.id, reserved.manageToken ? { signupId: reserved.signupId, token: reserved.manageToken } : null);
|
||||
if (reserved.reason === 'not_found') return html(c, config, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
if (reserved.reason === 'closed') return shiftResponse(c, services, loadShift(services, String(shift.id)) ?? shift, 400, null, CLOSED);
|
||||
if (reserved.reason === 'full') return shiftResponse(c, services, loadShift(services, String(shift.id)) ?? shift, 409, null, FULL);
|
||||
if (reserved.reason === 'duplicate') {
|
||||
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null), ALREADY_SIGNED_UP);
|
||||
}
|
||||
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null), COULD_NOT_SAVE);
|
||||
} catch (err) {
|
||||
if (!isBusy(err)) throw err;
|
||||
console.error('Signup could not lock the database.');
|
||||
return shiftResponse(c, services, shift, 503, formFor(services, shift, values, {}, textField(body, 'form_token')), CHECK_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
|
||||
function redirectConfirmed(
|
||||
c: Context,
|
||||
services: SignupServices,
|
||||
shiftId: number,
|
||||
issued: { signupId: number; token: string } | null,
|
||||
): Response {
|
||||
if (issued) {
|
||||
const sealed = sealConfirmation(services.config.sessionSecret, {
|
||||
signupId: issued.signupId,
|
||||
shiftId,
|
||||
token: issued.token,
|
||||
expiresAtMs: epochMs(services.now()) + 900 * 1000,
|
||||
});
|
||||
c.header('Set-Cookie', confirmationCookie(sealed, cookiePath(services.config), services.config.secureCookies));
|
||||
}
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.redirect(appPath(services.config, `/s/${shiftId}/confirmed`), 303);
|
||||
}
|
||||
|
||||
function shiftResponse(
|
||||
c: Context,
|
||||
services: SignupServices,
|
||||
shift: PublicShift,
|
||||
status: 200 | 400 | 403 | 409 | 429 | 503,
|
||||
signup: SignupFormView | null,
|
||||
notice?: string,
|
||||
retryAfter?: number,
|
||||
) {
|
||||
if (retryAfter !== undefined) c.header('Retry-After', String(retryAfter));
|
||||
const current = loadShift(services, String(shift.id)) ?? shift;
|
||||
const showForm = signup !== null && !current.cancelled && !current.ended && !current.full;
|
||||
return html(
|
||||
c,
|
||||
services.config,
|
||||
`${current.role} · Hope Volunteer`,
|
||||
<ShiftPage config={services.config} shift={current} signup={showForm ? signup : null} notice={notice} />,
|
||||
status,
|
||||
showForm,
|
||||
);
|
||||
}
|
||||
|
||||
function blankForm(services: SignupServices, shift: PublicShift): SignupFormView | null {
|
||||
if (shift.cancelled || shift.ended || shift.full) return null;
|
||||
return formFor(services, shift, EMPTY_SIGNUP, {}, null);
|
||||
}
|
||||
|
||||
function formFor(
|
||||
services: SignupServices,
|
||||
shift: PublicShift,
|
||||
values: SignupValues,
|
||||
errors: SignupErrors,
|
||||
token: string | null,
|
||||
): SignupFormView {
|
||||
return {
|
||||
token: token && token.length > 0 ? token : issueFormToken(services.config.sessionSecret, {
|
||||
shiftId: shift.id,
|
||||
issuedAt: epochMs(services.now()),
|
||||
operationId: newOperationId(),
|
||||
}),
|
||||
siteKey: services.config.turnstile.siteKey,
|
||||
values,
|
||||
errors,
|
||||
};
|
||||
}
|
||||
|
||||
async function checkTurnstile(services: SignupServices, token: string, remoteIp: string): Promise<TurnstileVerdict> {
|
||||
const verify = services.verifyTurnstile ?? verifyTurnstile;
|
||||
try {
|
||||
return await verify({
|
||||
secret: services.config.turnstile.secretKey,
|
||||
token,
|
||||
remoteIp,
|
||||
expectedHostname: new URL(services.config.baseUrl).hostname,
|
||||
expectedAction: 'signup',
|
||||
});
|
||||
} catch {
|
||||
return { ok: false, reason: 'unavailable' };
|
||||
}
|
||||
}
|
||||
|
||||
function loadShift(services: SignupServices, rawId: string): PublicShift | null {
|
||||
const id = parseShiftId(rawId);
|
||||
if (id === null) return null;
|
||||
return getPublicShift(services.db, id, services.now());
|
||||
}
|
||||
|
||||
function valuesFrom(body: Record<string, unknown>): SignupValues {
|
||||
return {
|
||||
name: textField(body, 'name'),
|
||||
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'),
|
||||
};
|
||||
}
|
||||
|
||||
function textField(body: Record<string, unknown>, name: string): string {
|
||||
const value = body[name];
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
function peerAddress(c: Context, override: SignupServices['clientIp']): string | null {
|
||||
if (override) return override(c);
|
||||
try {
|
||||
return getConnInfo(c).remote.address ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function showManage(c: Context, services: SignupServices, token: string, status: 200 | 400 | 403 | 429 | 503 = 200, notice?: string) {
|
||||
const signup = readManageSignup(services.db, token, services.now());
|
||||
if (!signup) return missingManage(c, services);
|
||||
const note = manageNote(c.req.query('notice'));
|
||||
return html(
|
||||
c,
|
||||
services.config,
|
||||
'Your signup · Hope Volunteer',
|
||||
<ManagePage
|
||||
signup={signup}
|
||||
cancel={cancelForm(services, token, signup.status)}
|
||||
switches={switchForm(services, token, signup)}
|
||||
reminders={reminderForm(services, token, signup)}
|
||||
notice={notice}
|
||||
note={note}
|
||||
/>,
|
||||
status,
|
||||
);
|
||||
}
|
||||
|
||||
function manageNote(notice: string | undefined): string | undefined {
|
||||
if (notice === 'switched') return SWITCHED_NOTE;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function missingManage(c: Context, services: SignupServices) {
|
||||
const ip = clientAddress(services.config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for'));
|
||||
const limit = recordInvalidManageToken(services.db, services.config.sessionSecret, services.now(), ip);
|
||||
if (limit.limited) {
|
||||
c.header('Retry-After', String(limit.retryAfter));
|
||||
return html(c, services.config, 'Please wait · Hope Volunteer', <WaitPage />, 429);
|
||||
}
|
||||
return html(c, services.config, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
|
||||
}
|
||||
|
||||
async function submitCancel(c: Context, services: SignupServices): Promise<Response> {
|
||||
const token = c.req.param('token') ?? '';
|
||||
const signup = readManageSignup(services.db, token, services.now());
|
||||
if (!signup) return missingManage(c, services);
|
||||
if (!originAllowed(c, services.config.baseUrl)) {
|
||||
return showManage(c, services, token, 403, CANCEL_ORIGIN);
|
||||
}
|
||||
const body = await c.req.parseBody();
|
||||
if (!cancelTokenMatches(services.config.sessionSecret, token, textField(body, 'cancel_token'))) {
|
||||
return showManage(c, services, token, 400, CANCEL_REJECTED);
|
||||
}
|
||||
try {
|
||||
const result = cancelSignup(services.db, token, services.now(), mailIdentity(services.db, services.config));
|
||||
if (!result.ok) return missingManage(c, services);
|
||||
} catch (err) {
|
||||
if (!isBusy(err)) throw err;
|
||||
console.error('Cancellation could not lock the database.');
|
||||
return showManage(c, services, token, 503, CANCEL_UNAVAILABLE);
|
||||
}
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.redirect(appPath(services.config, `/m/${token}`), 303);
|
||||
}
|
||||
|
||||
async function submitSwitch(c: Context, services: SignupServices): Promise<Response> {
|
||||
const token = c.req.param('token') ?? '';
|
||||
const signup = readManageSignup(services.db, token, services.now());
|
||||
if (!originAllowed(c, services.config.baseUrl)) {
|
||||
if (!signup) return html(c, services.config, 'Your signup · Hope Volunteer', <SwitchAlreadyPage />, 403);
|
||||
return showManage(c, services, token, 403, SWITCH_ORIGIN);
|
||||
}
|
||||
const body = await c.req.parseBody();
|
||||
if (!signup) return switchedAlready(c, services, token, body);
|
||||
if (!switchTokenMatches(services.config.sessionSecret, token, textField(body, 'switch_token'))) {
|
||||
return showManage(c, services, token, 400, SWITCH_REJECTED);
|
||||
}
|
||||
if (signup.status !== 'confirmed') return showManage(c, services, token, 400, 'This signup is cancelled.');
|
||||
const destination = Number(textField(body, 'destination'));
|
||||
if (!Number.isSafeInteger(destination) || destination <= 0) return showManage(c, services, token, 400, 'Choose a shift.');
|
||||
const formToken = readFormToken(services.config.sessionSecret, textField(body, 'form_token'), signup.shiftId, epochMs(services.now()), 0);
|
||||
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,
|
||||
);
|
||||
if (limit.limited) {
|
||||
c.header('Retry-After', String(limit.retryAfter));
|
||||
return showManage(c, services, token, 429, 'Too many switch attempts. Please try again later. You are still signed up for this shift.');
|
||||
}
|
||||
const result = switchSignup(services.db, signup.signupId, destination, formToken.claims.operationId, services.now(), mailIdentity(services.db, services.config));
|
||||
if (!result.ok) return showManage(c, services, token, 400, result.error);
|
||||
if (!result.manageToken) return html(c, services.config, 'Your signup · Hope Volunteer', <SwitchAlreadyPage />);
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.redirect(appPath(services.config, `/m/${result.manageToken}?notice=switched`), 303);
|
||||
} catch (err) {
|
||||
if (!isBusy(err)) throw err;
|
||||
console.error('Switch could not lock the database.');
|
||||
return showManage(c, services, token, 503, SWITCH_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
|
||||
function switchedAlready(c: Context, services: SignupServices, token: string, body: Record<string, unknown>) {
|
||||
if (!switchTokenMatches(services.config.sessionSecret, token, textField(body, 'switch_token'))) return missingManage(c, services);
|
||||
const formToken = openFormToken(services.config.sessionSecret, textField(body, 'form_token'), epochMs(services.now()), 0);
|
||||
if (!formToken.ok) return missingManage(c, services);
|
||||
const shiftId = confirmedOperationShift(services.db, formToken.claims.operationId);
|
||||
if (shiftId === null) return missingManage(c, services);
|
||||
return html(c, services.config, 'Your signup · Hope Volunteer', <SwitchAlreadyPage />);
|
||||
}
|
||||
|
||||
function switchForm(services: SignupServices, token: string, signup: { status: 'confirmed' | 'cancelled'; shiftId: number; eventId: number; name: string; email: string }): SwitchForm | null {
|
||||
if (signup.status !== 'confirmed') return null;
|
||||
const targets = listMoveTargets(services.db, signup.eventId, signup.shiftId, services.now(), {
|
||||
publishedOnly: true,
|
||||
});
|
||||
if (targets.length === 0) return { action: '', token: '', formToken: '', targets };
|
||||
return {
|
||||
action: appPath(services.config, `/m/${token}/switch`),
|
||||
token: issueSwitchToken(services.config.sessionSecret, token),
|
||||
formToken: issueFormToken(services.config.sessionSecret, {
|
||||
shiftId: signup.shiftId,
|
||||
issuedAt: epochMs(services.now()),
|
||||
operationId: newOperationId(),
|
||||
}),
|
||||
targets,
|
||||
};
|
||||
}
|
||||
|
||||
function reminderForm(
|
||||
services: SignupServices,
|
||||
token: string,
|
||||
signup: { status: 'confirmed' | 'cancelled'; remindersOff: boolean },
|
||||
): { action: string; token: string } | 'off' | null {
|
||||
if (signup.status !== 'confirmed') return null;
|
||||
if (signup.remindersOff) return 'off';
|
||||
return {
|
||||
action: appPath(services.config, `/m/${token}/reminders`),
|
||||
token: issueReminderPageToken(services.config.sessionSecret, token),
|
||||
};
|
||||
}
|
||||
|
||||
async function submitRemindersOff(c: Context, services: SignupServices): Promise<Response> {
|
||||
const token = c.req.param('token') ?? '';
|
||||
const signup = readManageSignup(services.db, token, services.now());
|
||||
if (!signup) return missingManage(c, services);
|
||||
if (!originAllowed(c, services.config.baseUrl)) {
|
||||
return showManage(c, services, token, 403, CANCEL_ORIGIN);
|
||||
}
|
||||
const body = await c.req.parseBody();
|
||||
if (!reminderPageTokenMatches(services.config.sessionSecret, token, textField(body, 'reminder_token'))) {
|
||||
return showManage(c, services, token, 400, CANCEL_REJECTED);
|
||||
}
|
||||
try {
|
||||
const result = disableReminders(services.db, signup.signupId, services.now());
|
||||
if (!result.ok) return missingManage(c, services);
|
||||
} catch (err) {
|
||||
if (!isBusy(err)) throw err;
|
||||
console.error('Reminder opt-out could not lock the database.');
|
||||
return showManage(c, services, token, 503, CANCEL_UNAVAILABLE);
|
||||
}
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.redirect(appPath(services.config, `/m/${token}`), 303);
|
||||
}
|
||||
|
||||
function cancelForm(services: SignupServices, token: string, status: 'confirmed' | 'cancelled'): { action: string; token: string } | null {
|
||||
if (status !== 'confirmed') return null;
|
||||
return {
|
||||
action: appPath(services.config, `/m/${token}`),
|
||||
token: issueCancelToken(services.config.sessionSecret, token),
|
||||
};
|
||||
}
|
||||
|
||||
function html(
|
||||
c: Context,
|
||||
config: AppConfig,
|
||||
title: string,
|
||||
body: Child,
|
||||
status: 200 | 400 | 403 | 404 | 409 | 429 | 503 = 200,
|
||||
turnstile = false,
|
||||
) {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.html(
|
||||
<Layout config={config} title={title} path={c.req.path} turnstile={turnstile}>
|
||||
{body}
|
||||
</Layout>,
|
||||
status,
|
||||
);
|
||||
}
|
||||
|
||||
function mailIdentity(db: Database.Database, config: AppConfig): MailIdentity {
|
||||
return {
|
||||
baseUrl: config.baseUrl,
|
||||
basePath: config.basePath,
|
||||
from: config.mail.from,
|
||||
replyTo: readReplyTo(db, config.mail.replyTo),
|
||||
};
|
||||
}
|
||||
|
||||
function epochMs(utc: string): number {
|
||||
return Temporal.Instant.from(utc).epochMilliseconds;
|
||||
}
|
||||
|
||||
function parseShiftId(value: string): number | null {
|
||||
return parsePositiveId(value);
|
||||
}
|
||||
|
||||
function parsePositiveId(value: string): number | null {
|
||||
if (!/^[1-9][0-9]*$/.test(value)) return null;
|
||||
const id = Number(value);
|
||||
return Number.isSafeInteger(id) ? id : null;
|
||||
}
|
||||
|
||||
function isBusy(err: unknown): boolean {
|
||||
return err instanceof Error && 'code' in err && String((err as { code: unknown }).code).includes('SQLITE_BUSY');
|
||||
}
|
||||
+419
@@ -0,0 +1,419 @@
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { normalizeEmail } from './email.js';
|
||||
import { queueCancellation, queueConfirmation, cancelPendingConfirmations, cancelPendingReminders } from './mail/queue.js';
|
||||
import type { MailIdentity } from './mail/types.js';
|
||||
import { formatInstantInZone, formatUtc, type ZonedClock } from './time.js';
|
||||
|
||||
const MANAGE_TOKEN_TTL_HOURS = 24 * 7;
|
||||
|
||||
export type ReserveInput = {
|
||||
shiftId: number;
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
isMinor: boolean;
|
||||
guardianName: string | null;
|
||||
guardianEmail: string | null;
|
||||
operationId: string;
|
||||
now: string;
|
||||
mail: MailIdentity;
|
||||
/** Public signup stays on published shifts. A coordinator can record a walk-in before the event is public. */
|
||||
audience?: 'public' | 'coordinator';
|
||||
onReserved?: (signupId: number) => void;
|
||||
};
|
||||
|
||||
export type ReserveResult =
|
||||
| { ok: true; signupId: number; manageToken: string | null; replay: boolean }
|
||||
| { ok: false; reason: 'not_found' | 'closed' | 'full' | 'duplicate' | 'conflict' };
|
||||
|
||||
export type ManageView = {
|
||||
signupId: number;
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
isMinor: boolean;
|
||||
guardianName: string | null;
|
||||
guardianEmail: string | null;
|
||||
status: 'confirmed' | 'cancelled';
|
||||
remindersOff: boolean;
|
||||
emailNorm: string;
|
||||
shiftId: number;
|
||||
eventId: number;
|
||||
role: string;
|
||||
location: string;
|
||||
eventTitle: string;
|
||||
when: ZonedClock;
|
||||
};
|
||||
|
||||
/**
|
||||
* Takes one spot only when the published shift still has room.
|
||||
* The immediate transaction is the capacity lock and also queues confirmation mail.
|
||||
* A later send failure does not undo the reservation.
|
||||
*/
|
||||
export function reserveSignup(db: Database.Database, input: ReserveInput): ReserveResult {
|
||||
const emailNorm = normalizeEmail(input.email);
|
||||
const operationKey = sha256(input.operationId);
|
||||
const attempt = db.transaction(() => placeReservation(db, input, emailNorm, operationKey));
|
||||
try {
|
||||
return attempt.immediate();
|
||||
} catch (err) {
|
||||
if (!isUniqueConstraint(err)) throw err;
|
||||
const existing = findOperation(db, operationKey);
|
||||
if (existing && existing.shiftId === input.shiftId && existing.emailNorm === emailNorm) {
|
||||
return { ok: true, signupId: existing.id, manageToken: null, replay: true };
|
||||
}
|
||||
if (confirmedPersonOnShift(db, input.shiftId, emailNorm, input.name)) return { ok: false, reason: 'duplicate' };
|
||||
return { ok: false, reason: 'conflict' };
|
||||
}
|
||||
}
|
||||
|
||||
export function findSignupByOperation(
|
||||
db: Database.Database,
|
||||
operationId: string,
|
||||
): { id: number; shiftId: number; emailNorm: string } | null {
|
||||
return findOperation(db, sha256(operationId));
|
||||
}
|
||||
|
||||
export function confirmedOperationShift(db: Database.Database, operationId: string): number | null {
|
||||
const found = findOperation(db, sha256(operationId));
|
||||
if (!found) return null;
|
||||
const row = db.prepare('SELECT status AS status FROM signups WHERE id = ?').get(found.id) as { status: string } | undefined;
|
||||
return row?.status === 'confirmed' ? found.shiftId : null;
|
||||
}
|
||||
|
||||
export type CancelResult = { ok: true; already: boolean } | { ok: false; reason: 'invalid' };
|
||||
|
||||
/**
|
||||
* Marks this signup cancelled, frees its spot, and queues cancellation mail.
|
||||
* Cancelling the same link again is the same result and does not queue a second letter.
|
||||
* A pending confirmation is cancelled in this transaction. Mail already accepted cannot be recalled.
|
||||
*/
|
||||
export function cancelSignup(db: Database.Database, token: string, now: string, mail: MailIdentity): CancelResult {
|
||||
if (!manageTokenShape(token)) return { ok: false, reason: 'invalid' };
|
||||
const hash = sha256(token);
|
||||
return db.transaction(() => cancelConfirmed(db, hash, token, now, mail)).immediate();
|
||||
}
|
||||
|
||||
export function readManageSignup(db: Database.Database, token: string, now: string): ManageView | null {
|
||||
if (!manageTokenShape(token)) return null;
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
su.id AS signup_id,
|
||||
su.name AS name,
|
||||
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,
|
||||
su.token_expires_at AS token_expires_at,
|
||||
su.shift_id AS shift_id,
|
||||
s.event_id AS event_id,
|
||||
s.role AS role,
|
||||
e.title AS title,
|
||||
e.location AS location,
|
||||
e.tz AS tz,
|
||||
s.starts_at_utc AS starts_at_utc
|
||||
FROM signups su
|
||||
JOIN shifts s ON s.id = su.shift_id
|
||||
JOIN events e ON e.id = s.event_id
|
||||
WHERE su.manage_token_hash = ? AND su.anonymized_at IS NULL`,
|
||||
)
|
||||
.get(sha256(token)) as ManageRow | undefined;
|
||||
if (!row || !row.token_expires_at || row.token_expires_at <= now) return null;
|
||||
if (row.status !== 'confirmed' && row.status !== 'cancelled') return null;
|
||||
if (!row.name || !row.email || !row.email_norm) return null;
|
||||
return {
|
||||
signupId: row.signup_id,
|
||||
name: row.name,
|
||||
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,
|
||||
shiftId: row.shift_id,
|
||||
eventId: row.event_id,
|
||||
role: row.role,
|
||||
location: row.location,
|
||||
eventTitle: row.title,
|
||||
when: formatInstantInZone(row.starts_at_utc, row.tz),
|
||||
};
|
||||
}
|
||||
|
||||
function placeReservation(db: Database.Database, input: ReserveInput, emailNorm: string, operationKey: string): ReserveResult {
|
||||
const shift = db
|
||||
.prepare(
|
||||
`SELECT s.capacity AS capacity, s.cancelled AS cancelled, s.ends_at_utc AS ends_at_utc, s.starts_at_utc AS starts_at_utc,
|
||||
s.version AS version, s.role AS role, e.published AS published, e.title AS title, e.location AS location, e.tz AS tz
|
||||
FROM shifts s
|
||||
JOIN events e ON e.id = s.event_id
|
||||
WHERE s.id = ?`,
|
||||
)
|
||||
.get(input.shiftId) as
|
||||
| {
|
||||
capacity: number;
|
||||
cancelled: number;
|
||||
ends_at_utc: string;
|
||||
starts_at_utc: string;
|
||||
version: number;
|
||||
role: string;
|
||||
published: number;
|
||||
title: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
}
|
||||
| undefined;
|
||||
const coordinator = input.audience === 'coordinator';
|
||||
if (!shift || (!coordinator && shift.published !== 1)) return { ok: false, reason: 'not_found' };
|
||||
if (shift.cancelled === 1 || shift.ends_at_utc <= input.now) return { ok: false, reason: 'closed' };
|
||||
|
||||
const existing = findOperation(db, operationKey);
|
||||
if (existing) {
|
||||
if (existing.shiftId === input.shiftId && existing.emailNorm === emailNorm) {
|
||||
return { ok: true, signupId: existing.id, manageToken: null, replay: true };
|
||||
}
|
||||
return { ok: false, reason: 'conflict' };
|
||||
}
|
||||
if (confirmedPersonOnShift(db, input.shiftId, emailNorm, input.name)) return { ok: false, reason: 'duplicate' };
|
||||
|
||||
const occupied = db
|
||||
.prepare(
|
||||
`SELECT COALESCE(SUM(group_size), 0) AS occupied
|
||||
FROM signups
|
||||
WHERE shift_id = ? AND status = 'confirmed'`,
|
||||
)
|
||||
.get(input.shiftId) as { occupied: number };
|
||||
if (Number(occupied.occupied) + 1 > shift.capacity) return { ok: false, reason: 'full' };
|
||||
|
||||
const manageToken = randomBytes(32).toString('base64url');
|
||||
const expiresAt = formatUtc(Temporal.Instant.from(shift.ends_at_utc).add({ hours: MANAGE_TOKEN_TTL_HOURS }));
|
||||
const inserted = db
|
||||
.prepare(
|
||||
`INSERT INTO signups (
|
||||
shift_id, name, email, email_norm, phone, is_minor, guardian_name, guardian_email,
|
||||
group_size, notes, status, manage_token_hash, token_expires_at, reminders_off,
|
||||
created_at, updated_at, operation_key
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, 'confirmed', ?, ?, 0, ?, ?, ?)`,
|
||||
)
|
||||
.run(
|
||||
input.shiftId,
|
||||
input.name,
|
||||
emailNorm,
|
||||
emailNorm,
|
||||
input.phone,
|
||||
input.isMinor ? 1 : 0,
|
||||
input.isMinor ? input.guardianName : null,
|
||||
input.isMinor ? input.guardianEmail : null,
|
||||
input.notes,
|
||||
sha256(manageToken),
|
||||
expiresAt,
|
||||
input.now,
|
||||
input.now,
|
||||
operationKey,
|
||||
);
|
||||
const signupId = Number(inserted.lastInsertRowid);
|
||||
queueConfirmation(db, {
|
||||
signupId,
|
||||
shiftId: input.shiftId,
|
||||
shiftVersion: shift.version,
|
||||
token: manageToken,
|
||||
volunteerName: input.name,
|
||||
volunteerEmail: emailNorm,
|
||||
guardianEmail: input.isMinor ? input.guardianEmail : null,
|
||||
shift: shiftFacts(shift).facts,
|
||||
mail: input.mail,
|
||||
now: input.now,
|
||||
});
|
||||
input.onReserved?.(signupId);
|
||||
return { ok: true, signupId, manageToken, replay: false };
|
||||
}
|
||||
|
||||
type OperationRow = { id: number; shiftId: number; emailNorm: string };
|
||||
|
||||
function findOperation(db: Database.Database, operationKey: string): OperationRow | null {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT id AS id, shift_id AS shiftId, email_norm AS emailNorm
|
||||
FROM signups
|
||||
WHERE operation_key = ? AND email_norm IS NOT NULL`,
|
||||
)
|
||||
.get(operationKey) as OperationRow | undefined;
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** True when this name and email already have a confirmed spot on the shift. */
|
||||
export function confirmedPersonOnShift(db: Database.Database, shiftId: number, emailNorm: string, name: string): boolean {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT id FROM signups
|
||||
WHERE shift_id = ? AND email_norm = ? AND name = ? COLLATE NOCASE AND status = 'confirmed'
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(shiftId, emailNorm, name);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
/** Shifts where this name and email are already confirmed. */
|
||||
export function confirmedPersonShiftIds(db: Database.Database, emailNorm: string, name: string): number[] {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT shift_id AS shift_id FROM signups
|
||||
WHERE email_norm = ? AND name = ? COLLATE NOCASE AND status = 'confirmed'`,
|
||||
)
|
||||
.all(emailNorm, name) as Array<{ shift_id: number }>;
|
||||
return rows.map((row) => row.shift_id);
|
||||
}
|
||||
|
||||
function cancelConfirmed(db: Database.Database, hash: string, token: string, now: string, mail: MailIdentity): CancelResult {
|
||||
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
|
||||
FROM signups su
|
||||
WHERE su.manage_token_hash = ?`,
|
||||
)
|
||||
.get(hash) as
|
||||
| {
|
||||
id: number;
|
||||
status: string;
|
||||
token_expires_at: string | null;
|
||||
anonymized_at: string | null;
|
||||
name: string | null;
|
||||
email_norm: string | null;
|
||||
guardian_email: string | null;
|
||||
shift_id: number;
|
||||
}
|
||||
| undefined;
|
||||
if (!row || row.anonymized_at || !row.token_expires_at || row.token_expires_at <= now) {
|
||||
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 updated = db
|
||||
.prepare(
|
||||
`UPDATE signups
|
||||
SET status = 'cancelled', updated_at = ?
|
||||
WHERE manage_token_hash = ? AND status = 'confirmed' AND anonymized_at IS NULL AND token_expires_at > ?`,
|
||||
)
|
||||
.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,
|
||||
guardianEmail: row.guardian_email,
|
||||
shift: shift.facts,
|
||||
mail,
|
||||
now,
|
||||
});
|
||||
}
|
||||
return { ok: true, already: false };
|
||||
}
|
||||
const again = db
|
||||
.prepare(`SELECT status AS status, token_expires_at AS token_expires_at FROM signups WHERE manage_token_hash = ?`)
|
||||
.get(hash) as { status: string; token_expires_at: string | null } | undefined;
|
||||
if (again?.status === 'cancelled' && again.token_expires_at && again.token_expires_at > now) {
|
||||
return { ok: true, already: true };
|
||||
}
|
||||
return { ok: false, reason: 'invalid' };
|
||||
}
|
||||
|
||||
function shiftFacts(shift: {
|
||||
role: string;
|
||||
title: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
version: number;
|
||||
}): { version: number; facts: { role: string; eventTitle: string; location: string; whenLabel: string } } {
|
||||
const start = formatInstantInZone(shift.starts_at_utc, shift.tz);
|
||||
const end = formatInstantInZone(shift.ends_at_utc, shift.tz);
|
||||
return {
|
||||
version: shift.version,
|
||||
facts: {
|
||||
role: shift.role,
|
||||
eventTitle: shift.title,
|
||||
location: shift.location,
|
||||
whenLabel: `${start.dateLabel}, ${start.timeLabel} to ${end.timeLabel} ${end.abbreviation}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function loadShiftFacts(db: Database.Database, shiftId: number) {
|
||||
const shift = db
|
||||
.prepare(
|
||||
`SELECT s.role AS role, s.version AS version, 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 shifts s
|
||||
JOIN events e ON e.id = s.event_id
|
||||
WHERE s.id = ?`,
|
||||
)
|
||||
.get(shiftId) as
|
||||
| {
|
||||
role: string;
|
||||
version: number;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
title: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
}
|
||||
| undefined;
|
||||
return shift ? shiftFacts(shift) : null;
|
||||
}
|
||||
|
||||
function manageTokenShape(token: string): boolean {
|
||||
return /^[A-Za-z0-9_-]{20,128}$/.test(token);
|
||||
}
|
||||
|
||||
function sha256(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
function isUniqueConstraint(err: unknown): boolean {
|
||||
return err instanceof Error && 'code' in err && String((err as { code: string }).code).includes('SQLITE_CONSTRAINT');
|
||||
}
|
||||
|
||||
|
||||
|
||||
type ManageRow = {
|
||||
signup_id: number;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
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;
|
||||
shift_id: number;
|
||||
event_id: number;
|
||||
role: string;
|
||||
title: string;
|
||||
location: string;
|
||||
tz: string;
|
||||
starts_at_utc: string;
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
export function isUniqueConstraint(err: unknown): boolean {
|
||||
return (
|
||||
err instanceof Error &&
|
||||
'code' in err &&
|
||||
String((err as { code: unknown }).code).includes('SQLITE_CONSTRAINT') &&
|
||||
/unique/i.test(err.message)
|
||||
);
|
||||
}
|
||||
|
||||
export function isBusy(err: unknown): boolean {
|
||||
return err instanceof Error && 'code' in err && String((err as { code: unknown }).code).includes('SQLITE_BUSY');
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
import { Temporal } from '@js-temporal/polyfill';
|
||||
|
||||
/**
|
||||
* Node 22 does not ship a stable Temporal API. @js-temporal/polyfill is the
|
||||
* timezone library for this app. It can reject a local time that falls in a
|
||||
* daylight-saving gap or overlap instead of silently moving it.
|
||||
*
|
||||
* Database instants use formatUtc(): YYYY-MM-DDTHH:mm:ss.SSSZ
|
||||
* Local dates stay YYYY-MM-DD. Local times stay HH:MM.
|
||||
* Weekday 0 is Sunday and weekday 6 is Saturday.
|
||||
*/
|
||||
|
||||
const LOCAL_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
const LOCAL_TIME = /^([01][0-9]|2[0-3]):([0-5][0-9])$/;
|
||||
const UTC_INSTANT = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$/;
|
||||
|
||||
export class LocalTimeError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'LocalTimeError';
|
||||
}
|
||||
}
|
||||
|
||||
export type ZonedClock = {
|
||||
date: string;
|
||||
time24: string;
|
||||
timeLabel: string;
|
||||
weekday: number;
|
||||
abbreviation: string;
|
||||
timeZone: string;
|
||||
dateLabel: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export function isUtcInstant(value: string): boolean {
|
||||
return UTC_INSTANT.test(value);
|
||||
}
|
||||
|
||||
export function assertUtcInstant(value: string): string {
|
||||
if (!isUtcInstant(value)) {
|
||||
throw new LocalTimeError('Expected a UTC instant like 2026-01-15T15:00:00.000Z.');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function assertValidTimeZone(timeZone: string): string {
|
||||
try {
|
||||
Temporal.Instant.from('2020-01-01T00:00:00Z').toZonedDateTimeISO(timeZone);
|
||||
return timeZone;
|
||||
} catch {
|
||||
throw new LocalTimeError(`${timeZone} is not a recognized IANA time zone.`);
|
||||
}
|
||||
}
|
||||
|
||||
export function formatUtc(instant: Temporal.Instant): string {
|
||||
const zoned = instant.toZonedDateTimeISO('UTC');
|
||||
return `${pad(zoned.year, 4)}-${pad(zoned.month)}-${pad(zoned.day)}T${pad(zoned.hour)}:${pad(zoned.minute)}:${pad(zoned.second)}.${pad(zoned.millisecond, 3)}Z`;
|
||||
}
|
||||
|
||||
export function nowUtc(now: Temporal.Instant = Temporal.Now.instant()): string {
|
||||
return formatUtc(now);
|
||||
}
|
||||
|
||||
export function localToUtc(date: string, time: string, timeZone: string): string {
|
||||
assertValidTimeZone(timeZone);
|
||||
assertCalendarDate(date);
|
||||
if (!LOCAL_TIME.test(time)) {
|
||||
throw new LocalTimeError(`${time} is not a local time. Use 24-hour HH:MM, such as 09:00 or 17:30.`);
|
||||
}
|
||||
const parts = parseDateTime(date, time);
|
||||
try {
|
||||
const zoned = Temporal.ZonedDateTime.from(
|
||||
{
|
||||
timeZone,
|
||||
year: parts.year,
|
||||
month: parts.month,
|
||||
day: parts.day,
|
||||
hour: parts.hour,
|
||||
minute: parts.minute,
|
||||
second: 0,
|
||||
millisecond: 0,
|
||||
},
|
||||
{ disambiguation: 'reject' },
|
||||
);
|
||||
return assertUtcInstant(formatUtc(zoned.toInstant()));
|
||||
} catch (err) {
|
||||
if (err instanceof LocalTimeError) throw err;
|
||||
const kind = classifyLocalTime(parts, timeZone);
|
||||
const shown = `${date} ${time} (${clockLabel(time)})`;
|
||||
if (kind === 'gap') {
|
||||
throw new LocalTimeError(
|
||||
`${shown} does not exist in ${timeZone}. Daylight saving time skips that clock time. Choose a different local time.`,
|
||||
);
|
||||
}
|
||||
if (kind === 'overlap') {
|
||||
throw new LocalTimeError(
|
||||
`${shown} happens twice in ${timeZone} because daylight saving time repeats that hour. Choose a local time outside the repeated hour.`,
|
||||
);
|
||||
}
|
||||
throw new LocalTimeError(`${shown} is not a valid local time in ${timeZone}.`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertSameDayShift(startLocal: string, endLocal: string): void {
|
||||
if (!LOCAL_TIME.test(startLocal) || !LOCAL_TIME.test(endLocal)) {
|
||||
throw new LocalTimeError('Use local times in 24-hour HH:MM form, such as 09:00 or 17:30.');
|
||||
}
|
||||
if (endLocal <= startLocal) {
|
||||
throw new LocalTimeError(
|
||||
'Shifts must start and end on the same day, with the end time after the start. Overnight shifts are not available yet.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function localShiftToUtc(
|
||||
date: string,
|
||||
startLocal: string,
|
||||
endLocal: string,
|
||||
timeZone: string,
|
||||
): { startsAtUtc: string; endsAtUtc: string } {
|
||||
assertSameDayShift(startLocal, endLocal);
|
||||
const startsAtUtc = localToUtc(date, startLocal, timeZone);
|
||||
const endsAtUtc = localToUtc(date, endLocal, timeZone);
|
||||
if (endsAtUtc <= startsAtUtc) {
|
||||
throw new LocalTimeError('The shift end must be after the start.');
|
||||
}
|
||||
return { startsAtUtc, endsAtUtc };
|
||||
}
|
||||
|
||||
export function formatInstantInZone(utc: string, timeZone: string): ZonedClock {
|
||||
assertUtcInstant(utc);
|
||||
assertValidTimeZone(timeZone);
|
||||
const instant = Temporal.Instant.from(utc);
|
||||
const zoned = instant.toZonedDateTimeISO(timeZone);
|
||||
const date = `${pad(zoned.year, 4)}-${pad(zoned.month)}-${pad(zoned.day)}`;
|
||||
const time24 = `${pad(zoned.hour)}:${pad(zoned.minute)}`;
|
||||
const timeLabel = clockLabel(time24);
|
||||
const weekday = zoned.dayOfWeek % 7;
|
||||
const dateLabel = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone,
|
||||
weekday: 'long',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
}).format(new Date(instant.epochMilliseconds));
|
||||
const abbreviation = timeZoneAbbreviation(instant, timeZone);
|
||||
return {
|
||||
date,
|
||||
time24,
|
||||
timeLabel,
|
||||
weekday,
|
||||
abbreviation,
|
||||
timeZone,
|
||||
dateLabel,
|
||||
label: `${dateLabel}, ${timeLabel} ${abbreviation}`,
|
||||
};
|
||||
}
|
||||
|
||||
export function addLocalDays(date: string, days: number): string {
|
||||
assertCalendarDate(date);
|
||||
return Temporal.PlainDate.from(date).add({ days }).toString();
|
||||
}
|
||||
|
||||
export function weekdayIndex(date: string, timeZone: string): number {
|
||||
return formatInstantInZone(localToUtc(date, '12:00', timeZone), timeZone).weekday;
|
||||
}
|
||||
|
||||
export function todayInZone(timeZone: string, now: Temporal.Instant = Temporal.Now.instant()): string {
|
||||
assertValidTimeZone(timeZone);
|
||||
const zoned = now.toZonedDateTimeISO(timeZone);
|
||||
return `${pad(zoned.year, 4)}-${pad(zoned.month)}-${pad(zoned.day)}`;
|
||||
}
|
||||
|
||||
function assertCalendarDate(date: string): void {
|
||||
if (!LOCAL_DATE.test(date)) {
|
||||
throw new LocalTimeError(`${date} is not a real calendar date. Use YYYY-MM-DD.`);
|
||||
}
|
||||
try {
|
||||
Temporal.PlainDate.from(date);
|
||||
} catch {
|
||||
throw new LocalTimeError(`${date} is not a real calendar date.`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseDateTime(date: string, time: string): {
|
||||
year: number;
|
||||
month: number;
|
||||
day: number;
|
||||
hour: number;
|
||||
minute: number;
|
||||
} {
|
||||
const dateMatch = LOCAL_DATE.exec(date);
|
||||
const timeMatch = LOCAL_TIME.exec(time);
|
||||
if (!dateMatch || !timeMatch) {
|
||||
throw new LocalTimeError(`${date} ${time} is not a valid local date and time.`);
|
||||
}
|
||||
return {
|
||||
year: Number(dateMatch[1]),
|
||||
month: Number(dateMatch[2]),
|
||||
day: Number(dateMatch[3]),
|
||||
hour: Number(timeMatch[1]),
|
||||
minute: Number(timeMatch[2]),
|
||||
};
|
||||
}
|
||||
|
||||
function classifyLocalTime(
|
||||
parts: { year: number; month: number; day: number; hour: number; minute: number },
|
||||
timeZone: string,
|
||||
): 'gap' | 'overlap' | 'unique' {
|
||||
const earlier = zonedAt(parts, timeZone, 'earlier');
|
||||
const later = zonedAt(parts, timeZone, 'later');
|
||||
const earlierMatches = sameClock(earlier, parts);
|
||||
const laterMatches = sameClock(later, parts);
|
||||
if (earlierMatches && laterMatches && earlier.offset !== later.offset) return 'overlap';
|
||||
if (!earlierMatches && !laterMatches) return 'gap';
|
||||
return 'unique';
|
||||
}
|
||||
|
||||
function zonedAt(
|
||||
parts: { year: number; month: number; day: number; hour: number; minute: number },
|
||||
timeZone: string,
|
||||
disambiguation: 'earlier' | 'later',
|
||||
): Temporal.ZonedDateTime {
|
||||
return Temporal.ZonedDateTime.from(
|
||||
{
|
||||
timeZone,
|
||||
year: parts.year,
|
||||
month: parts.month,
|
||||
day: parts.day,
|
||||
hour: parts.hour,
|
||||
minute: parts.minute,
|
||||
second: 0,
|
||||
millisecond: 0,
|
||||
},
|
||||
{ disambiguation },
|
||||
);
|
||||
}
|
||||
|
||||
function sameClock(
|
||||
zoned: Temporal.ZonedDateTime,
|
||||
parts: { hour: number; minute: number },
|
||||
): boolean {
|
||||
return zoned.hour === parts.hour && zoned.minute === parts.minute;
|
||||
}
|
||||
|
||||
function clockLabel(time: string): string {
|
||||
const match = LOCAL_TIME.exec(time);
|
||||
if (!match) return time;
|
||||
const hour = Number(match[1]);
|
||||
const minute = Number(match[2]);
|
||||
const suffix = hour < 12 ? 'AM' : 'PM';
|
||||
const hour12 = hour % 12 === 0 ? 12 : hour % 12;
|
||||
return `${hour12}:${pad(minute)} ${suffix}`;
|
||||
}
|
||||
|
||||
function timeZoneAbbreviation(instant: Temporal.Instant, timeZone: string): string {
|
||||
const parts = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone,
|
||||
timeZoneName: 'short',
|
||||
hour: 'numeric',
|
||||
}).formatToParts(new Date(instant.epochMilliseconds));
|
||||
const name = parts.find((part) => part.type === 'timeZoneName')?.value;
|
||||
return name && name.length > 0 ? name : timeZone;
|
||||
}
|
||||
|
||||
function pad(value: number, width = 2): string {
|
||||
return String(value).padStart(width, '0');
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { isTurnstileTestKey } from './config.js';
|
||||
|
||||
export type TurnstileVerdict = { ok: true } | { ok: false; reason: 'rejected' | 'duplicate' | 'unavailable' };
|
||||
|
||||
export type TurnstileCheck = {
|
||||
secret: string;
|
||||
token: string;
|
||||
remoteIp: string;
|
||||
expectedHostname: string;
|
||||
expectedAction: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
};
|
||||
|
||||
/**
|
||||
* Server-side Turnstile check. A spent token is not sent again.
|
||||
* Network failure and an unexpected hostname or action fail closed.
|
||||
*/
|
||||
export async function verifyTurnstile(input: TurnstileCheck): Promise<TurnstileVerdict> {
|
||||
const body = new URLSearchParams({
|
||||
secret: input.secret,
|
||||
response: input.token,
|
||||
remoteip: input.remoteIp,
|
||||
});
|
||||
let response: Response;
|
||||
try {
|
||||
response = await (input.fetchImpl ?? fetch)('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body,
|
||||
});
|
||||
} catch {
|
||||
return { ok: false, reason: 'unavailable' };
|
||||
}
|
||||
if (!response.ok) return { ok: false, reason: 'unavailable' };
|
||||
let payload: SiteverifyResponse;
|
||||
try {
|
||||
payload = (await response.json()) as SiteverifyResponse;
|
||||
} catch {
|
||||
return { ok: false, reason: 'unavailable' };
|
||||
}
|
||||
if (payload.success !== true) {
|
||||
const codes = payload['error-codes'] ?? [];
|
||||
if (codes.includes('timeout-or-duplicate')) return { ok: false, reason: 'duplicate' };
|
||||
return { ok: false, reason: 'rejected' };
|
||||
}
|
||||
// Cloudflare's documented test keys succeed with hostname example.com and no action.
|
||||
if (payload.metadata?.result_with_testing_key === true && isTurnstileTestKey(input.secret)) {
|
||||
return { ok: true };
|
||||
}
|
||||
if (payload.hostname !== input.expectedHostname) return { ok: false, reason: 'rejected' };
|
||||
if (payload.action !== input.expectedAction) return { ok: false, reason: 'rejected' };
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
type SiteverifyResponse = {
|
||||
success?: boolean;
|
||||
hostname?: string;
|
||||
action?: string;
|
||||
'error-codes'?: string[];
|
||||
metadata?: { result_with_testing_key?: boolean };
|
||||
};
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import type { AppConfig } from './config.js';
|
||||
|
||||
/** Prefix an app path with BASE_PATH. The path must start with /. */
|
||||
export function appPath(config: Pick<AppConfig, 'basePath'>, pathname: string): string {
|
||||
if (!pathname.startsWith('/')) {
|
||||
throw new Error(`App paths must start with /. Received ${pathname}.`);
|
||||
}
|
||||
if (pathname === '/') return config.basePath === '' ? '/' : config.basePath;
|
||||
return `${config.basePath}${pathname}`;
|
||||
}
|
||||
|
||||
/** Absolute public URL for redirects, assets, cookies' companion links, and mail. */
|
||||
export function absoluteUrl(config: Pick<AppConfig, 'baseUrl' | 'basePath'>, pathname: string): string {
|
||||
return `${config.baseUrl}${appPath(config, pathname)}`;
|
||||
}
|
||||
|
||||
/** Cookie Path attribute. An empty mount prefix uses the site root. */
|
||||
export function cookiePath(config: Pick<AppConfig, 'basePath'>): string {
|
||||
return config.basePath === '' ? '/' : config.basePath;
|
||||
}
|
||||
Reference in new issue
Block a user