Merge branch 'cursor/private-party-size-3d9f'
This commit is contained in:
commit
63dc675a19
6 files changed
+373
-6
No files matched your search
@@ -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');
|
||||
}
|
||||
|
||||
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 {
|
||||
return tokenMatches(issueCancelToken(secret, manageToken), received);
|
||||
}
|
||||
@@ -28,6 +32,10 @@ export function reminderPageTokenMatches(secret: string, manageToken: string, re
|
||||
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 {
|
||||
if (!/^[A-Za-z0-9_-]{20,128}$/.test(received)) return false;
|
||||
const left = Buffer.from(expected);
|
||||
|
||||
@@ -357,10 +357,19 @@ export type SwitchForm = {
|
||||
targets: MoveTarget[];
|
||||
};
|
||||
|
||||
export type PartyForm = {
|
||||
action: string;
|
||||
token: string;
|
||||
value: string;
|
||||
remaining: number;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export function ManagePage(props: {
|
||||
signup: ManageView;
|
||||
cancel: { action: string; token: string } | null;
|
||||
switches: SwitchForm | null;
|
||||
party?: PartyForm | null;
|
||||
reminders?: { action: string; token: string } | 'off' | null;
|
||||
notice?: string;
|
||||
note?: string;
|
||||
@@ -408,6 +417,14 @@ export function ManagePage(props: {
|
||||
{props.notice}
|
||||
</p>
|
||||
) : 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.targets.length === 0 ? (
|
||||
<p>
|
||||
|
||||
@@ -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 } {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) return { value: 1 };
|
||||
|
||||
+69
-4
@@ -6,7 +6,7 @@ import type { Hono } from 'hono';
|
||||
import type { Child } from 'hono/jsx';
|
||||
import { listMoveTargets, switchSignup } from './admin/store.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 { confirmationCookie, openConfirmation, sealConfirmation } from './confirm-cookie.js';
|
||||
import type { AppConfig } from './config.js';
|
||||
@@ -21,16 +21,17 @@ import {
|
||||
ShiftPage,
|
||||
SwitchAlreadyPage,
|
||||
WaitPage,
|
||||
type PartyForm,
|
||||
type SignupFormView,
|
||||
type SwitchForm,
|
||||
} from './pages.js';
|
||||
import { recordInvalidManageToken, recordSignupEmail, recordSignupIp, recordSwitchAttempt } from './rate-limit.js';
|
||||
import { getPublicShift, type PublicShift } from './schedule.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 { 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 { 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_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 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.';
|
||||
|
||||
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.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'), (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());
|
||||
if (!signup) return missingManage(c, services);
|
||||
const note = manageNote(c.req.query('notice'));
|
||||
@@ -321,6 +334,7 @@ function showManage(c: Context, services: SignupServices, token: string, status:
|
||||
signup={signup}
|
||||
cancel={cancelForm(services, token, signup.status)}
|
||||
switches={switchForm(services, token, signup)}
|
||||
party={partyForm(services, token, signup, partyError)}
|
||||
reminders={reminderForm(services, token, signup)}
|
||||
notice={notice}
|
||||
note={note}
|
||||
@@ -331,6 +345,7 @@ function showManage(c: Context, services: SignupServices, token: string, status:
|
||||
|
||||
function manageNote(notice: string | undefined): string | undefined {
|
||||
if (notice === 'switched') return SWITCHED_NOTE;
|
||||
if (notice === 'party') return PARTY_NOTE;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -414,6 +429,56 @@ function switchedAlready(c: Context, services: SignupServices, token: string, bo
|
||||
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 {
|
||||
if (signup.status !== 'confirmed') return null;
|
||||
const targets = listMoveTargets(services.db, signup.eventId, signup.shiftId, services.now(), {
|
||||
|
||||
@@ -98,6 +98,28 @@ export function cancelSignup(db: Database.Database, token: string, now: string,
|
||||
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 {
|
||||
if (!manageTokenShape(token)) return null;
|
||||
const row = db
|
||||
@@ -295,6 +317,67 @@ export function confirmedPersonShiftIds(db: Database.Database, emailNorm: string
|
||||
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 {
|
||||
const row = db
|
||||
.prepare(
|
||||
|
||||
Reference in new issue
Block a user