Merge branch 'cursor/private-party-size-3d9f'

This commit is contained in:
blake committed 2026-10-29 11:52:07 -05:00
commit 63dc675a19
6 files changed
+373 -6

No files matched your search

+8
View File
@@ -16,6 +16,10 @@ export function issueReminderPageToken(secret: string, manageToken: string): str
return createHmac('sha256', secret).update(`hope-reminder-page-v1\0${manageToken}`).digest('base64url'); return createHmac('sha256', secret).update(`hope-reminder-page-v1\0${manageToken}`).digest('base64url');
} }
export function issuePartyToken(secret: string, manageToken: string): string {
return createHmac('sha256', secret).update(`hope-party-v1\0${manageToken}`).digest('base64url');
}
export function cancelTokenMatches(secret: string, manageToken: string, received: string): boolean { export function cancelTokenMatches(secret: string, manageToken: string, received: string): boolean {
return tokenMatches(issueCancelToken(secret, manageToken), received); return tokenMatches(issueCancelToken(secret, manageToken), received);
} }
@@ -28,6 +32,10 @@ export function reminderPageTokenMatches(secret: string, manageToken: string, re
return tokenMatches(issueReminderPageToken(secret, manageToken), received); return tokenMatches(issueReminderPageToken(secret, manageToken), received);
} }
export function partyTokenMatches(secret: string, manageToken: string, received: string): boolean {
return tokenMatches(issuePartyToken(secret, manageToken), received);
}
function tokenMatches(expected: string, received: string): boolean { function tokenMatches(expected: string, received: string): boolean {
if (!/^[A-Za-z0-9_-]{20,128}$/.test(received)) return false; if (!/^[A-Za-z0-9_-]{20,128}$/.test(received)) return false;
const left = Buffer.from(expected); const left = Buffer.from(expected);
+17
View File
@@ -357,10 +357,19 @@ export type SwitchForm = {
targets: MoveTarget[]; targets: MoveTarget[];
}; };
export type PartyForm = {
action: string;
token: string;
value: string;
remaining: number;
error?: string;
};
export function ManagePage(props: { export function ManagePage(props: {
signup: ManageView; signup: ManageView;
cancel: { action: string; token: string } | null; cancel: { action: string; token: string } | null;
switches: SwitchForm | null; switches: SwitchForm | null;
party?: PartyForm | null;
reminders?: { action: string; token: string } | 'off' | null; reminders?: { action: string; token: string } | 'off' | null;
notice?: string; notice?: string;
note?: string; note?: string;
@@ -408,6 +417,14 @@ export function ManagePage(props: {
{props.notice} {props.notice}
</p> </p>
) : null} ) : null}
{props.party ? (
<form class="move-form" method="post" action={props.party.action}>
<p>Change how many people are coming. The signup stays, and the name stays the same.</p>
<input type="hidden" name="party_token" value={props.party.token} />
<PartySizeField idPrefix="manage" value={props.party.value} error={props.party.error} remaining={props.party.remaining} />
<button type="submit">Save the number of people</button>
</form>
) : null}
{props.switches ? ( {props.switches ? (
props.switches.targets.length === 0 ? ( props.switches.targets.length === 0 ? (
<p> <p>
+10
View File
@@ -140,6 +140,16 @@ export function parseSignupForm(
}; };
} }
/** The people control. An empty value means one person, the same as a new signup. */
export function parsePartySize(
raw: string,
voice: 'volunteer' | 'coordinator' = 'volunteer',
): { ok: true; groupSize: number } | { ok: false; error: string } {
const party = readPartySize(raw, voice);
if (party.error) return { ok: false, error: party.error };
return { ok: true, groupSize: party.value };
}
function readPartySize(raw: string, voice: 'volunteer' | 'coordinator'): { value: number; error?: string } { function readPartySize(raw: string, voice: 'volunteer' | 'coordinator'): { value: number; error?: string } {
const trimmed = raw.trim(); const trimmed = raw.trim();
if (trimmed.length === 0) return { value: 1 }; if (trimmed.length === 0) return { value: 1 };
+69 -4
View File
@@ -6,7 +6,7 @@ import type { Hono } from 'hono';
import type { Child } from 'hono/jsx'; import type { Child } from 'hono/jsx';
import { listMoveTargets, switchSignup } from './admin/store.js'; import { listMoveTargets, switchSignup } from './admin/store.js';
import { readSession } from './auth/session.js'; import { readSession } from './auth/session.js';
import { cancelTokenMatches, issueCancelToken, issueReminderPageToken, issueSwitchToken, reminderPageTokenMatches, switchTokenMatches } from './cancel-token.js'; import { cancelTokenMatches, issueCancelToken, issuePartyToken, issueReminderPageToken, issueSwitchToken, partyTokenMatches, reminderPageTokenMatches, switchTokenMatches } from './cancel-token.js';
import { clientAddress } from './client-ip.js'; import { clientAddress } from './client-ip.js';
import { confirmationCookie, openConfirmation, sealConfirmation } from './confirm-cookie.js'; import { confirmationCookie, openConfirmation, sealConfirmation } from './confirm-cookie.js';
import type { AppConfig } from './config.js'; import type { AppConfig } from './config.js';
@@ -21,16 +21,17 @@ import {
ShiftPage, ShiftPage,
SwitchAlreadyPage, SwitchAlreadyPage,
WaitPage, WaitPage,
type PartyForm,
type SignupFormView, type SignupFormView,
type SwitchForm, type SwitchForm,
} from './pages.js'; } from './pages.js';
import { recordInvalidManageToken, recordSignupEmail, recordSignupIp, recordSwitchAttempt } from './rate-limit.js'; import { recordInvalidManageToken, recordSignupEmail, recordSignupIp, recordSwitchAttempt } from './rate-limit.js';
import { getPublicShift, type PublicShift } from './schedule.js'; import { getPublicShift, type PublicShift } from './schedule.js';
import { SIGNUP_TOO_EARLY } from './signup-window.js'; import { SIGNUP_TOO_EARLY } from './signup-window.js';
import { EMPTY_SIGNUP, parseSignupForm, spotsLeftMessage, type SignupErrors, type SignupValues } from './signup-form.js'; import { EMPTY_SIGNUP, parsePartySize, parseSignupForm, spotsLeftMessage, type SignupErrors, type SignupValues } from './signup-form.js';
import type { MailIdentity } from './mail/types.js'; import type { MailIdentity } from './mail/types.js';
import { disableReminders } from './reminders.js'; import { disableReminders } from './reminders.js';
import { cancelSignup, confirmedOperationShift, findSignupByOperation, readManageSignup, reserveSignup } from './signup.js'; import { cancelSignup, changePartySize, confirmedOperationShift, findSignupByOperation, managePartyLimit, readManageSignup, reserveSignup } from './signup.js';
import { verifyTurnstile, type TurnstileCheck, type TurnstileVerdict } from './turnstile.js'; import { verifyTurnstile, type TurnstileCheck, type TurnstileVerdict } from './turnstile.js';
import { appPath, cookiePath } from './url.js'; import { appPath, cookiePath } from './url.js';
@@ -53,6 +54,10 @@ 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_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 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 SWITCHED_NOTE = 'You are on this shift. This link replaces the earlier one. A change email is queued.';
const PARTY_ORIGIN = 'The update could not be sent from this page.';
const PARTY_REJECTED = 'The update could not be confirmed. Please try again.';
const PARTY_UNAVAILABLE = 'The update could not be saved. Please try again in a little while.';
const PARTY_NOTE = 'The number of people on this signup is saved. The signup stays.';
const EXPIRED = 'This form expired. Please submit it again.'; const EXPIRED = 'This form expired. Please submit it again.';
export type SignupServices = { export type SignupServices = {
@@ -99,6 +104,7 @@ export function registerPublicSignup(app: Hono, services: SignupServices): void
app.get(appPath(config, '/m/:token'), (c) => showManage(c, services, c.req.param('token') ?? '')); 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/switch'), (c) => submitSwitch(c, services));
app.post(appPath(config, '/m/:token/party'), (c) => submitParty(c, services));
app.post(appPath(config, '/m/:token/reminders'), (c) => submitRemindersOff(c, services)); app.post(appPath(config, '/m/:token/reminders'), (c) => submitRemindersOff(c, services));
app.post(appPath(config, '/m/:token'), (c) => submitCancel(c, services)); app.post(appPath(config, '/m/:token'), (c) => submitCancel(c, services));
} }
@@ -309,7 +315,14 @@ function peerAddress(c: Context, override: SignupServices['clientIp']): string |
} }
} }
function showManage(c: Context, services: SignupServices, token: string, status: 200 | 400 | 403 | 429 | 503 = 200, notice?: string) { function showManage(
c: Context,
services: SignupServices,
token: string,
status: 200 | 400 | 403 | 409 | 429 | 503 = 200,
notice?: string,
partyError?: string,
) {
const signup = readManageSignup(services.db, token, services.now()); const signup = readManageSignup(services.db, token, services.now());
if (!signup) return missingManage(c, services); if (!signup) return missingManage(c, services);
const note = manageNote(c.req.query('notice')); const note = manageNote(c.req.query('notice'));
@@ -321,6 +334,7 @@ function showManage(c: Context, services: SignupServices, token: string, status:
signup={signup} signup={signup}
cancel={cancelForm(services, token, signup.status)} cancel={cancelForm(services, token, signup.status)}
switches={switchForm(services, token, signup)} switches={switchForm(services, token, signup)}
party={partyForm(services, token, signup, partyError)}
reminders={reminderForm(services, token, signup)} reminders={reminderForm(services, token, signup)}
notice={notice} notice={notice}
note={note} note={note}
@@ -331,6 +345,7 @@ function showManage(c: Context, services: SignupServices, token: string, status:
function manageNote(notice: string | undefined): string | undefined { function manageNote(notice: string | undefined): string | undefined {
if (notice === 'switched') return SWITCHED_NOTE; if (notice === 'switched') return SWITCHED_NOTE;
if (notice === 'party') return PARTY_NOTE;
return undefined; return undefined;
} }
@@ -414,6 +429,56 @@ function switchedAlready(c: Context, services: SignupServices, token: string, bo
return html(c, services, 'Your signup · Hope Volunteer', <SwitchAlreadyPage />); return html(c, services, 'Your signup · Hope Volunteer', <SwitchAlreadyPage />);
} }
function partyForm(
services: SignupServices,
token: string,
signup: { status: 'confirmed' | 'cancelled'; shiftId: number; groupSize: number },
error?: string,
): PartyForm | null {
if (signup.status !== 'confirmed') return null;
return {
action: appPath(services.config, `/m/${token}/party`),
token: issuePartyToken(services.config.sessionSecret, token),
value: String(signup.groupSize),
remaining: managePartyLimit(services.db, signup.shiftId, signup.groupSize),
error,
};
}
async function submitParty(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, PARTY_ORIGIN);
}
const body = await c.req.parseBody();
if (!partyTokenMatches(services.config.sessionSecret, token, textField(body, 'party_token'))) {
return showManage(c, services, token, 400, PARTY_REJECTED);
}
if (signup.status !== 'confirmed') return showManage(c, services, token, 400, 'This signup is cancelled.');
const raw = textField(body, 'party_size');
const parsed = raw.trim().length === 0
? { ok: false as const, error: 'Choose how many people are coming.' }
: parsePartySize(raw);
if (!parsed.ok) return showManage(c, services, token, 400, undefined, parsed.error);
try {
const result = changePartySize(services.db, token, parsed.groupSize, services.now());
if (!result.ok && result.reason === 'cancelled') return showManage(c, services, token, 400, 'This signup is cancelled.');
if (!result.ok && result.reason === 'full') {
const spotsLeft = result.spotsLeft ?? 0;
return showManage(c, services, token, 409, undefined, spotsLeft > 0 ? spotsLeftMessage(spotsLeft) : FULL);
}
if (!result.ok) return showManage(c, services, token, 400, PARTY_REJECTED);
} catch (err) {
if (!isBusy(err)) throw err;
console.error('Head count could not lock the database.');
return showManage(c, services, token, 503, PARTY_UNAVAILABLE);
}
c.header('Cache-Control', 'no-store');
return c.redirect(appPath(services.config, `/m/${token}?notice=party`), 303);
}
function switchForm(services: SignupServices, token: string, signup: { status: 'confirmed' | 'cancelled'; shiftId: number; eventId: number; name: string; email: string; groupSize: number }): SwitchForm | null { function switchForm(services: SignupServices, token: string, signup: { status: 'confirmed' | 'cancelled'; shiftId: number; eventId: number; name: string; email: string; groupSize: number }): SwitchForm | null {
if (signup.status !== 'confirmed') return null; if (signup.status !== 'confirmed') return null;
const targets = listMoveTargets(services.db, signup.eventId, signup.shiftId, services.now(), { const targets = listMoveTargets(services.db, signup.eventId, signup.shiftId, services.now(), {
+83
View File
@@ -98,6 +98,28 @@ export function cancelSignup(db: Database.Database, token: string, now: string,
return db.transaction(() => cancelConfirmed(db, hash, token, now, mail)).immediate(); return db.transaction(() => cancelConfirmed(db, hash, token, now, mail)).immediate();
} }
export type PartySizeResult =
| { ok: true; groupSize: number; changed: boolean }
| { ok: false; reason: 'invalid' | 'cancelled' | 'full'; spotsLeft?: number };
/**
* Changes how many spots this one signup holds. The signup stays confirmed, under the same name.
* A smaller count frees the difference. A larger count is saved only when the shift still has room
* and the new count is within the stored maximum. Saving the current count does not write again.
*/
export function changePartySize(db: Database.Database, token: string, groupSize: number, now: string): PartySizeResult {
if (!manageTokenShape(token)) return { ok: false, reason: 'invalid' };
return db.transaction(() => writePartySize(db, sha256(token), groupSize, now)).immediate();
}
/** How many people this signup may offer, including the spots it already holds. */
export function managePartyLimit(db: Database.Database, shiftId: number, groupSize: number): number {
const room = partyRoom(db, shiftId, groupSize);
const held = Math.min(MAX_PARTY_SIZE, Math.max(1, groupSize));
if (!room) return held;
return Math.min(MAX_PARTY_SIZE, Math.max(held, room.room));
}
export function readManageSignup(db: Database.Database, token: string, now: string): ManageView | null { export function readManageSignup(db: Database.Database, token: string, now: string): ManageView | null {
if (!manageTokenShape(token)) return null; if (!manageTokenShape(token)) return null;
const row = db const row = db
@@ -295,6 +317,67 @@ export function confirmedPersonShiftIds(db: Database.Database, emailNorm: string
return rows.map((row) => row.shift_id); return rows.map((row) => row.shift_id);
} }
function writePartySize(db: Database.Database, hash: string, groupSize: number, now: string): PartySizeResult {
const row = db
.prepare(
`SELECT id AS id, status AS status, token_expires_at AS token_expires_at, anonymized_at AS anonymized_at,
shift_id AS shift_id, group_size AS group_size, name AS name
FROM signups
WHERE manage_token_hash = ?`,
)
.get(hash) as
| {
id: number;
status: string;
token_expires_at: string | null;
anonymized_at: string | null;
shift_id: number;
group_size: number;
name: string | null;
}
| undefined;
if (!row || row.anonymized_at || !row.token_expires_at || row.token_expires_at <= now || !row.name) {
return { ok: false, reason: 'invalid' };
}
if (row.status === 'cancelled') return { ok: false, reason: 'cancelled' };
if (row.status !== 'confirmed') return { ok: false, reason: 'invalid' };
if (!Number.isInteger(groupSize) || groupSize < 1 || groupSize > MAX_PARTY_SIZE) return { ok: false, reason: 'invalid' };
const current = Number(row.group_size);
const room = partyRoom(db, row.shift_id, current);
if (!room) return { ok: false, reason: 'invalid' };
if (groupSize > current && groupSize > room.room) return { ok: false, reason: 'full', spotsLeft: room.spotsLeft };
if (groupSize === current) return { ok: true, groupSize: current, changed: false };
const updated = db
.prepare(
`UPDATE signups
SET group_size = ?, updated_at = ?
WHERE id = ? AND status = 'confirmed' AND anonymized_at IS NULL AND token_expires_at > ? AND group_size = ?`,
)
.run(groupSize, now, row.id, now, current);
if (updated.changes !== 1) return { ok: false, reason: 'invalid' };
return { ok: true, groupSize, changed: true };
}
function partyRoom(
db: Database.Database,
shiftId: number,
groupSize: number,
): { room: number; spotsLeft: number } | null {
const shift = db.prepare('SELECT capacity AS capacity FROM shifts WHERE id = ?').get(shiftId) as { capacity: number } | undefined;
if (!shift) return null;
const occupied = db
.prepare(
`SELECT COALESCE(SUM(group_size), 0) AS occupied
FROM signups
WHERE shift_id = ? AND status = 'confirmed'`,
)
.get(shiftId) as { occupied: number };
const spotsLeft = Math.max(0, Number(shift.capacity) - Number(occupied.occupied));
return { room: spotsLeft + groupSize, spotsLeft };
}
function cancelConfirmed(db: Database.Database, hash: string, token: string, now: string, mail: MailIdentity): CancelResult { function cancelConfirmed(db: Database.Database, hash: string, token: string, now: string, mail: MailIdentity): CancelResult {
const row = db const row = db
.prepare( .prepare(
+186 -2
View File
@@ -5,7 +5,7 @@ import path from 'node:path';
import { Temporal } from '@js-temporal/polyfill'; import { Temporal } from '@js-temporal/polyfill';
import { afterEach, describe, expect, it } from 'vitest'; import { afterEach, describe, expect, it } from 'vitest';
import { createApp } from '../src/app.js'; import { createApp } from '../src/app.js';
import { issueCancelToken } from '../src/cancel-token.js'; import { issueCancelToken, issuePartyToken } from '../src/cancel-token.js';
import { loadConfig } from '../src/config.js'; import { loadConfig } from '../src/config.js';
import { openAppDatabase } from '../src/db.js'; import { openAppDatabase } from '../src/db.js';
import { issueFormToken } from '../src/form-token.js'; import { issueFormToken } from '../src/form-token.js';
@@ -313,6 +313,155 @@ describe('manage-link switch', () => {
}); });
}); });
describe('manage-link party size', () => {
it('lowers the head count without cancelling and keeps one name', async () => {
const { app, db, shiftId } = await buildApp({ capacity: 6 });
const saved = await postSignup(app, shiftId, { name: 'Pat Party', email: 'pat.party@example.invalid', partySize: '4' }, '203.0.113.110');
const confirmed = await app.request(saved.headers.get('location') ?? '', {
headers: { cookie: (saved.headers.get('set-cookie') ?? '').split(';')[0] ?? '' },
});
const managePath = (await confirmed.text()).match(/href="(\/m\/[^"]+)"/)?.[1] ?? '';
const before = db.prepare('SELECT name, group_size, status, manage_token_hash, updated_at FROM signups').get() as {
name: string;
group_size: number;
status: string;
manage_token_hash: string;
updated_at: string;
};
db.prepare("UPDATE signups SET updated_at = '2026-10-14T17:00:00.000Z'").run();
const viewed = await app.request(managePath);
const html = await viewed.text();
expect(viewed.status).toBe(200);
expect(html).toContain('How many people?');
expect(html).toContain('This signup holds that many spots.');
expect(html).toContain('You don&#39;t need to add their names.');
expect(html).toContain('Change how many people are coming. The signup stays, and the name stays the same.');
expect(html).toContain('Save the number of people');
expect(partyOptions(html)).toEqual(['1', '2', '3', '4', '5', '6']);
expect(html).toContain('<dd>4</dd>');
expect(db.prepare('SELECT group_size, updated_at FROM signups').get()).toEqual({
group_size: 4,
updated_at: '2026-10-14T17:00:00.000Z',
});
const same = await postParty(app, managePath, html, '4');
expect(same.status).toBe(303);
expect(same.headers.get('location')).toBe(`${managePath}?notice=party`);
expect(db.prepare('SELECT group_size, updated_at FROM signups').get()).toEqual({
group_size: 4,
updated_at: '2026-10-14T17:00:00.000Z',
});
const lowered = await postParty(app, managePath, html, '1');
expect(lowered.status).toBe(303);
expect(lowered.headers.get('location')).toBe(`${managePath}?notice=party`);
const page = await app.request(lowered.headers.get('location') ?? '');
const next = await page.text();
expect(page.status).toBe(200);
expect(next).toContain('The number of people on this signup is saved. The signup stays.');
expect(next).toContain('Confirmed');
expect(next).toContain('Pat Party');
expect(next).toContain('<dd>1</dd>');
expect(next).toContain('Cancel this signup');
expect(db.prepare('SELECT name, group_size, status, manage_token_hash, updated_at FROM signups').all()).toEqual([{
name: 'Pat Party',
group_size: 1,
status: 'confirmed',
manage_token_hash: before.manage_token_hash,
updated_at: before.updated_at,
}]);
expect(db.prepare('SELECT COUNT(*) AS n FROM contacts').get()).toEqual({ n: 1 });
expect(db.prepare("SELECT kind, status FROM outbox").all()).toEqual([{ kind: 'confirmation', status: 'pending' }]);
expect(await (await app.request(`/s/${shiftId}`)).text()).toContain('1/6 spots filled');
const board = await (await app.request('/?view=calendar')).text();
expect(board).toContain('Pat Party');
expect(board).not.toContain('Pat Party (4 people)');
expect(board).not.toContain('pat.party@example.invalid');
});
it('does not raise the head count past the spots left or 20', async () => {
const tight = await buildApp({ capacity: 4 });
const first = await postSignup(tight.app, tight.shiftId, { name: 'Pat Party', email: 'pat.party@example.invalid', partySize: '2' }, '203.0.113.120');
const managePath = await managePathFrom(tight.app, first);
await postSignup(tight.app, tight.shiftId, { name: 'Sam Other', email: 'sam.other@example.invalid', partySize: '1' }, '203.0.113.121');
const html = await (await tight.app.request(managePath)).text();
expect(partyOptions(html)).toEqual(['1', '2', '3']);
const tooMany = await postParty(tight.app, managePath, html, '4');
expect(tooMany.status).toBe(409);
expect(await tooMany.text()).toContain('This shift has 1 spot left.');
expect(tight.db.prepare("SELECT name, group_size, status FROM signups WHERE email_norm = 'pat.party@example.invalid'").get()).toEqual({
name: 'Pat Party',
group_size: 2,
status: 'confirmed',
});
const raised = await postParty(tight.app, managePath, html, '3');
expect(raised.status).toBe(303);
expect(tight.db.prepare('SELECT name, group_size FROM signups ORDER BY id').all()).toEqual([
{ name: 'Pat Party', group_size: 3 },
{ name: 'Sam Other', group_size: 1 },
]);
expect(await (await tight.app.request(`/s/${tight.shiftId}`)).text()).toContain('4/4 spots filled');
const wide = await buildApp({ capacity: 25 });
const opened = await postSignup(wide.app, wide.shiftId, { name: 'Pat Party', email: 'pat.wide@example.invalid', partySize: '1' }, '203.0.113.122');
const widePath = await managePathFrom(wide.app, opened);
const wideHtml = await (await wide.app.request(widePath)).text();
expect(partyOptions(wideHtml)).toContain('20');
expect(partyOptions(wideHtml)).not.toContain('21');
const overMax = await postParty(wide.app, widePath, wideHtml, '21');
expect(overMax.status).toBe(400);
expect(await overMax.text()).toContain('Choose 20 people or fewer.');
const zero = await postParty(wide.app, widePath, wideHtml, '0');
expect(zero.status).toBe(400);
expect(await zero.text()).toContain('Choose how many people are coming.');
expect(wide.db.prepare('SELECT group_size, status FROM signups').get()).toEqual({ group_size: 1, status: 'confirmed' });
const toTwenty = await postParty(wide.app, widePath, wideHtml, '20');
expect(toTwenty.status).toBe(303);
expect(wide.db.prepare('SELECT name, group_size, status FROM signups').all()).toEqual([{
name: 'Pat Party',
group_size: 20,
status: 'confirmed',
}]);
expect(await (await wide.app.request(`/s/${wide.shiftId}`)).text()).toContain('20/25 spots filled');
});
it('refuses a party update that did not come from this signup page', async () => {
const { app, db, shiftId } = await buildApp({ capacity: 6 });
const saved = await postSignup(app, shiftId, { name: 'Pat Party', email: 'pat.keep@example.invalid', partySize: '3' }, '203.0.113.130');
const managePath = await managePathFrom(app, saved);
const html = await (await app.request(managePath)).text();
const crossSite = await postParty(app, managePath, html, '1', { origin: 'https://evil.example' });
expect(crossSite.status).toBe(403);
expect(await crossSite.text()).toContain('could not be sent from this page');
const missing = await postParty(app, managePath, html, '1', { token: '' });
expect(missing.status).toBe(400);
expect(await missing.text()).toContain('could not be confirmed');
const tampered = field(html, 'party_token');
const bad = await postParty(app, managePath, html, '1', {
token: `${tampered.slice(0, -1)}${tampered.endsWith('a') ? 'b' : 'a'}`,
});
expect(bad.status).toBe(400);
const mismatched = await postParty(app, managePath, html, '1', { token: issuePartyToken(SECRET, 'another-manage-token-value') });
expect(mismatched.status).toBe(400);
expect(db.prepare('SELECT group_size, status FROM signups').get()).toEqual({ group_size: 3, status: 'confirmed' });
const cancelled = await postCancel(app, managePath, field(html, 'cancel_token'), { ip: '203.0.113.131' });
expect(cancelled.status).toBe(303);
const gone = await app.request(managePath);
expect(await gone.text()).not.toContain('name="party_size"');
const again = await postParty(app, managePath, html, '1', { ip: '203.0.113.132' });
expect(again.status).toBe(400);
expect(await again.text()).toContain('This signup is cancelled');
expect(db.prepare('SELECT name, group_size, status FROM signups').all()).toEqual([{
name: 'Pat Party',
group_size: 3,
status: 'cancelled',
}]);
});
});
async function buildApp(options?: { capacity?: number }) { async function buildApp(options?: { capacity?: number }) {
const root = mkdtempSync(path.join(tmpdir(), 'hope-cancel-')); const root = mkdtempSync(path.join(tmpdir(), 'hope-cancel-'));
dirs.push(root); dirs.push(root);
@@ -358,7 +507,7 @@ async function openManage(app: ReturnType<typeof createApp>, shiftId: number, em
async function postSignup( async function postSignup(
app: ReturnType<typeof createApp>, app: ReturnType<typeof createApp>,
shiftId: number, shiftId: number,
fields: { name: string; email: string }, fields: { name: string; email: string; partySize?: string },
ip: string, ip: string,
) { ) {
const body = new URLSearchParams({ const body = new URLSearchParams({
@@ -372,6 +521,7 @@ async function postSignup(
email: fields.email, email: fields.email,
phone: '712-555-0100', phone: '712-555-0100',
notes: '', notes: '',
party_size: fields.partySize ?? '',
company_website: '', company_website: '',
'cf-turnstile-response': 'widget-token', 'cf-turnstile-response': 'widget-token',
}); });
@@ -426,6 +576,40 @@ function field(html: string, name: string): string {
return /value="([^"]*)"/.exec(tag)?.[1] ?? ''; return /value="([^"]*)"/.exec(tag)?.[1] ?? '';
} }
async function managePathFrom(app: ReturnType<typeof createApp>, saved: Response): Promise<string> {
const confirmed = await app.request(saved.headers.get('location') ?? '', {
headers: { cookie: (saved.headers.get('set-cookie') ?? '').split(';')[0] ?? '' },
});
return (await confirmed.text()).match(/href="(\/m\/[^"]+)"/)?.[1] ?? '';
}
function partyOptions(html: string): string[] {
const select = /<select\b[^>]*\bname="party_size"[^>]*>([\s\S]*?)<\/select>/.exec(html)?.[1] ?? '';
return [...select.matchAll(/value="(\d+)"/g)].map((match) => match[1] ?? '');
}
function postParty(
app: ReturnType<typeof createApp>,
managePath: string,
html: string,
partySize: string,
options?: { origin?: string; token?: string; ip?: string },
) {
const body = new URLSearchParams();
const token = options?.token ?? field(html, 'party_token');
if (token) body.set('party_token', token);
body.set('party_size', partySize);
return app.request(`${managePath}/party`, {
method: 'POST',
headers: {
origin: options?.origin ?? 'http://127.0.0.1:3000',
'content-type': 'application/x-www-form-urlencoded',
'x-test-ip': options?.ip ?? '203.0.113.140',
},
body,
});
}
function postCancel( function postCancel(
app: ReturnType<typeof createApp>, app: ReturnType<typeof createApp>,
managePath: string, managePath: string,