@semics-tech/emdash-events 0.0.0-stage → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +83 -2
  3. package/dist/index.d.mts +5 -0
  4. package/dist/index.mjs +416 -0
  5. package/dist/manifest.json +425 -0
  6. package/dist/plugin.d.mts +11 -0
  7. package/dist/plugin.mjs +7 -0
  8. package/dist/ts/astro/lib/call.d.ts +54 -0
  9. package/dist/ts/astro/lib/call.js +121 -0
  10. package/dist/ts/integration/index.d.ts +48 -0
  11. package/dist/ts/integration/index.js +76 -0
  12. package/dist/ts/ui/index.d.ts +6 -0
  13. package/dist/ts/ui/index.js +46 -0
  14. package/emdash-plugin.jsonc +222 -0
  15. package/package.json +78 -3
  16. package/src/astro/AddToCalendar.astro +47 -0
  17. package/src/astro/AttendeeList.astro +157 -0
  18. package/src/astro/BookingBlock.astro +30 -0
  19. package/src/astro/BookingPage.astro +230 -0
  20. package/src/astro/BookingStatus.astro +112 -0
  21. package/src/astro/BookingWidget.astro +776 -0
  22. package/src/astro/CheckIn.astro +186 -0
  23. package/src/astro/DoorSignPage.astro +62 -0
  24. package/src/astro/EventCard.astro +81 -0
  25. package/src/astro/EventList.astro +83 -0
  26. package/src/astro/OptOutPage.astro +58 -0
  27. package/src/astro/PaymentReturn.astro +96 -0
  28. package/src/astro/TicketPass.astro +95 -0
  29. package/src/astro/checkout-endpoint.ts +11 -0
  30. package/src/astro/index.js +18 -0
  31. package/src/astro/lib/attendees.ts +170 -0
  32. package/src/astro/lib/call.ts +185 -0
  33. package/src/astro/lib/checkout-form.ts +271 -0
  34. package/src/astro/lib/list.ts +99 -0
  35. package/src/astro/lib/opt-out.ts +49 -0
  36. package/src/astro/lib/pass.ts +35 -0
  37. package/src/astro/lib/payment.ts +73 -0
  38. package/src/astro/lib/picker.ts +245 -0
  39. package/src/astro/lib/promo.ts +162 -0
  40. package/src/astro/lib/questions.ts +107 -0
  41. package/src/astro/lib/receipt.ts +132 -0
  42. package/src/astro/lib/waitlist.ts +72 -0
  43. package/src/astro/lib/widget.ts +299 -0
  44. package/src/astro/promo-endpoint.ts +11 -0
  45. package/src/astro/virtual.d.ts +16 -0
  46. package/src/astro/waitlist-endpoint.ts +12 -0
  47. package/src/client/booking.ts +190 -0
  48. package/src/client/checkin.ts +260 -0
  49. package/src/client/payment.ts +76 -0
  50. package/src/client/picker.ts +143 -0
  51. package/src/client/receipt.ts +75 -0
  52. package/src/i18n/ar.ts +251 -0
  53. package/src/i18n/en.ts +255 -0
  54. package/src/i18n/index.ts +121 -0
@@ -0,0 +1,18 @@
1
+ // Astro component exports for the Events UI. Auto-wired through componentsEntry.
2
+ import AddToCalendar from "./AddToCalendar.astro";
3
+ import BookingBlock from "./BookingBlock.astro";
4
+ import BookingStatus from "./BookingStatus.astro";
5
+ import BookingWidget from "./BookingWidget.astro";
6
+ import EventCard from "./EventCard.astro";
7
+ import EventList from "./EventList.astro";
8
+ import PaymentReturn from "./PaymentReturn.astro";
9
+ import TicketPass from "./TicketPass.astro";
10
+
11
+ export const blockComponents = {
12
+ "events-booking": BookingBlock,
13
+ "events-list": EventList,
14
+ };
15
+
16
+ // The only way UI code calls the core (in-process public routes, fetch fallback).
17
+ export { callPublicRoute, EVENTS_PLUGIN_ID } from "./lib/call.ts";
18
+ export { AddToCalendar, BookingBlock, BookingStatus, BookingWidget, EventCard, EventList, PaymentReturn, TicketPass };
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The booking page's attendee signing list (T133, R95; Suite Pro). Events Pro's `public/booking`
3
+ * describes each seat of a waiver booking (`seat`, `signing`, `signs`, `email`, `minor`) and whether
4
+ * names may still be changed (`signingList.editable`, until `attendeeEditCutoffHours` before the
5
+ * start); Free sends none of it, so `signingRows` is null and the page shows nothing new.
6
+ *
7
+ * The list's forms post back to `/booking` (no JavaScript needed). `handleAttendeeAction` calls the
8
+ * Pro routes with the cookie's access token, never a form field, and redeems what they mint with
9
+ * e-sign in-process:
10
+ *
11
+ * - Sign now (`intent=sign-now`): `public/booking/attendees/sign` mints one inline intent for the
12
+ * seat (the attendee signs for themselves on this device; a minor's guardian signs for them), which
13
+ * `startDoorSigning` redeems before sending the browser to e-sign's signing page.
14
+ * - Resend (`intent=resend`, emailed adults): `public/booking/attendees/resend` mints a `resend`
15
+ * intent; e-sign emails the open envelope's invitation again (rate limited by Events Pro).
16
+ * - Save (`intent=attendees`): `public/booking/attendees` stores the corrected names and emails and
17
+ * mints, per changed seat, a `replace` intent (e-sign voids the old envelope) and, for an emailed
18
+ * adult, the new invitation's intent, redeemed in that order.
19
+ *
20
+ * Every outcome is a redirect to `/booking?ref=` with a code, never a typed value. Web APIs only (R35).
21
+ */
22
+ import { callPublicRoute, type PublicRouteContext } from "./call";
23
+ import { BOOKING_PATH } from "./checkout-form";
24
+ import { type ReceiptOptions, startDoorSigning } from "./receipt";
25
+ import type { BookingView } from "./widget";
26
+
27
+ /** What Events Pro adds to each attendee of a waiver booking's `public/booking` answer. */
28
+ export interface SigningAttendee {
29
+ name: string;
30
+ seat?: string;
31
+ email?: string;
32
+ minor?: boolean;
33
+ signing?: "signed" | "waiting";
34
+ /** `email`: an adult e-sign invites by email; `inline`: signed on the buyer's device. */
35
+ signs?: "inline" | "email";
36
+ }
37
+
38
+ export interface SigningRow {
39
+ seat: string;
40
+ name: string;
41
+ email: string;
42
+ minor: boolean;
43
+ signed: boolean;
44
+ canSign: boolean;
45
+ canResend: boolean;
46
+ canEdit: boolean;
47
+ }
48
+
49
+ export interface AttendeeEdit {
50
+ seat: string;
51
+ name: string;
52
+ email?: string;
53
+ }
54
+
55
+ /** Statuses in which a waiver can still be signed: the hold's, and a confirmed booking's pending seats. */
56
+ const OPEN = ["awaiting_signature", "awaiting_payment", "confirmed"];
57
+ const SEAT = /^[0-9]{1,3}$/;
58
+ const CODE = /^[A-Z_]{1,40}$/;
59
+ const MAX_TEXT = 254;
60
+ /** Issue codes of a refused save the page explains itself; any other issue is an invalid entry. */
61
+ const ISSUE_CODES = ["ATTENDEE_SIGNED", "WAIVER_EMAIL_REQUIRED", "WAIVER_TOO_MANY_EMAILS", "RATE_LIMITED"];
62
+
63
+ /** The list's rows, or null when the answer has no signing list (Free, or not a waiver booking). */
64
+ export function signingRows(booking: BookingView): SigningRow[] | null {
65
+ const list = booking.signingList;
66
+ if (!list) return null;
67
+ const open = OPEN.includes(booking.status);
68
+ const rows: SigningRow[] = [];
69
+ for (const a of booking.attendees as SigningAttendee[]) {
70
+ if (typeof a.seat !== "string" || !SEAT.test(a.seat) || !a.signing) continue;
71
+ const signed = a.signing === "signed";
72
+ const waiting = open && !signed;
73
+ rows.push({
74
+ seat: a.seat,
75
+ name: a.name,
76
+ email: a.email ?? "",
77
+ minor: a.minor === true,
78
+ signed,
79
+ canSign: waiting,
80
+ canResend: waiting && a.signs === "email",
81
+ canEdit: waiting && list.editable === true,
82
+ });
83
+ }
84
+ return rows.length > 0 ? rows : null;
85
+ }
86
+
87
+ const text = (form: FormData, key: string): string | undefined => {
88
+ const value = form.get(key);
89
+ return typeof value === "string" ? value.trim().slice(0, MAX_TEXT) : undefined;
90
+ };
91
+
92
+ /** The edit form's values for the editable seats (`name:<seat>`, `email:<seat>`); a minor has no email. */
93
+ export function readAttendeeEdits(form: FormData, rows: readonly SigningRow[]): AttendeeEdit[] {
94
+ return rows
95
+ .filter((r) => r.canEdit)
96
+ .map((r) => {
97
+ const name = text(form, `name:${r.seat}`) ?? r.name;
98
+ if (r.minor) return { seat: r.seat, name };
99
+ return { seat: r.seat, name, email: text(form, `email:${r.seat}`) ?? r.email };
100
+ });
101
+ }
102
+
103
+ const post = <T>(ctx: PublicRouteContext, pluginId: string | undefined, path: string, body: unknown) =>
104
+ callPublicRoute<T>(ctx, { method: "POST", path, body, ...(pluginId ? { pluginId } : {}) });
105
+
106
+ function back(ref: string, key: "error" | "attendees", value: string): { location: string } {
107
+ const query = new URLSearchParams({ ref });
108
+ query.set(key, key === "error" && !CODE.test(value) ? "INTERNAL" : value);
109
+ return { location: `${BOOKING_PATH}?${query}` };
110
+ }
111
+
112
+ interface Minted {
113
+ intent?: unknown;
114
+ lookup?: unknown;
115
+ intents?: Array<{ token?: unknown }>;
116
+ }
117
+
118
+ /**
119
+ * Handles the list's posts (`intent` = `sign-now`, `resend` or `attendees`); null for any other
120
+ * form. `booking` is the page's fresh `public/booking` answer, so only offered actions are sent.
121
+ */
122
+ export async function handleAttendeeAction(
123
+ ctx: PublicRouteContext,
124
+ form: FormData,
125
+ access: { ref: string; token: string },
126
+ options: ReceiptOptions,
127
+ booking: BookingView,
128
+ ): Promise<{ location: string } | null> {
129
+ const intent = form.get("intent");
130
+ if (intent !== "sign-now" && intent !== "resend" && intent !== "attendees") return null;
131
+ const { ref } = access;
132
+ if (!options.esignPluginId) return back(ref, "error", "ESIGN_NOT_CONFIGURED");
133
+ const rows = signingRows(booking) ?? [];
134
+ const auth = { bookingRef: ref, accessToken: access.token };
135
+
136
+ if (intent === "attendees") {
137
+ const attendees = readAttendeeEdits(form, rows);
138
+ if (attendees.length === 0) return back(ref, "error", "ATTENDEES_LOCKED");
139
+ const saved = await post<Minted>(ctx, options.pluginId, "public/booking/attendees", { ...auth, attendees });
140
+ if (!saved.ok) {
141
+ const issue = saved.error.issues?.find((i) => ISSUE_CODES.includes(String(i.code)));
142
+ if (issue) return back(ref, "error", String(issue.code));
143
+ return back(ref, "error", saved.error.code === "BAD_REQUEST" ? "ATTENDEE_INVALID" : saved.error.code);
144
+ }
145
+ // In order: each changed seat's `replace` (void the old envelope) before its new invitation.
146
+ for (const minted of saved.data.intents ?? []) {
147
+ const redeemed = await post(ctx, options.esignPluginId, "public/envelopes/from-intent", {
148
+ intent: minted.token,
149
+ });
150
+ if (!redeemed.ok) return back(ref, "error", "ATTENDEES_UNSENT");
151
+ }
152
+ return back(ref, "attendees", "saved");
153
+ }
154
+
155
+ const seat = form.get("seat");
156
+ const row = rows.find((r) => r.seat === seat);
157
+ if (!row || !(intent === "resend" ? row.canResend : row.canSign)) return back(ref, "error", "BAD_REQUEST");
158
+ if (intent === "resend") {
159
+ const minted = await post<Minted>(ctx, options.pluginId, "public/booking/attendees/resend", { ...auth, seat });
160
+ if (!minted.ok) return back(ref, "error", minted.error.code);
161
+ const sent = await post(ctx, options.esignPluginId, "public/envelopes/from-intent", { intent: minted.data.intent });
162
+ return sent.ok ? back(ref, "attendees", "resent") : back(ref, "error", "SIGNING_UNAVAILABLE");
163
+ }
164
+ const minted = await post<Minted>(ctx, options.pluginId, "public/booking/attendees/sign", { ...auth, seat });
165
+ if (!minted.ok) return back(ref, "error", minted.error.code);
166
+ const started = await startDoorSigning(ctx, minted.data.intent, options, minted.data.lookup);
167
+ if ("location" in started) return started;
168
+ if ("signed" in started) return { location: `${BOOKING_PATH}?ref=${ref}&waiver=signed` };
169
+ return back(ref, "error", started.error);
170
+ }
@@ -0,0 +1,185 @@
1
+ // i18n-ignore-file: these errors are for developers (the UI shows its own text by error code, T102).
2
+ import { getPublicPluginApiRouteHandler, type PublicPluginRuntimeLocals } from "emdash/plugin-utils";
3
+
4
+ /** Plugin ID (manifest slug) of the sandboxed Events core. */
5
+ export const EVENTS_PLUGIN_ID = "semics-events";
6
+
7
+ export type PublicRouteMethod = "GET" | "POST";
8
+
9
+ export interface PublicRouteCall {
10
+ /** Route name as declared in the core, e.g. `public/events`. A leading slash is ignored. */
11
+ path: string;
12
+ /** Defaults to GET. */
13
+ method?: PublicRouteMethod;
14
+ /** JSON body for POST; query parameters for GET. */
15
+ body?: unknown;
16
+ /** Defaults to the Events core. */
17
+ pluginId?: string;
18
+ }
19
+
20
+ /** The parts of the Astro global the helper needs; pass `Astro` itself. */
21
+ export interface PublicRouteContext {
22
+ locals: PublicPluginRuntimeLocals | null | undefined;
23
+ url: URL;
24
+ /**
25
+ * The visitor's request (`Astro.request`). Only its client-IP headers (and Cloudflare's `cf`)
26
+ * are passed on, so the core's per-IP limits see the visitor rather than one shared unknown
27
+ * address; the host still decides which of them to trust. Cookies and credentials never are.
28
+ */
29
+ request?: Request;
30
+ /** Injected for tests. Defaults to the global `fetch`. */
31
+ fetch?: typeof fetch;
32
+ }
33
+
34
+ export interface PublicRouteIssue {
35
+ path: string;
36
+ code: string;
37
+ }
38
+
39
+ export interface PublicRouteError {
40
+ code: string;
41
+ message: string;
42
+ /** Input validation issues, when the route reported them (`BAD_REQUEST`). */
43
+ issues?: PublicRouteIssue[];
44
+ }
45
+
46
+ export type PublicRouteResult<T> =
47
+ | { ok: true; data: T; via: "in-process" | "fetch" }
48
+ | { ok: false; error: PublicRouteError; via: "in-process" | "fetch" };
49
+
50
+ interface Envelope {
51
+ success?: boolean;
52
+ data?: unknown;
53
+ error?: { code?: unknown; message?: unknown };
54
+ }
55
+
56
+ /**
57
+ * The only way UI code calls the core. Dispatches in-process through
58
+ * `getPublicPluginApiRouteHandler(Astro.locals)` (Spike S2: reaches sandboxed public routes on the
59
+ * workerd runner), and falls back to `fetch(Astro.url.origin + route)` when the in-process handler
60
+ * isn't on `locals`. Never throws: every failure comes back as `{ ok: false, error }` so components
61
+ * can render a defined error state.
62
+ */
63
+ export async function callPublicRoute<T = unknown>(
64
+ ctx: PublicRouteContext,
65
+ call: PublicRouteCall,
66
+ ): Promise<PublicRouteResult<T>> {
67
+ const method = call.method ?? "GET";
68
+ const path = call.path.replace(/^\/+/, "");
69
+ const pluginId = call.pluginId ?? EVENTS_PLUGIN_ID;
70
+ const handler = getPublicPluginApiRouteHandler(ctx.locals);
71
+ const via = handler ? "in-process" : "fetch";
72
+
73
+ const unsafeKey = method === "GET" ? tokenLikeKey(call.body) : undefined;
74
+ if (unsafeKey !== undefined) {
75
+ return {
76
+ ok: false,
77
+ error: {
78
+ code: "TOKEN_IN_QUERY",
79
+ message: `"${unsafeKey}" looks like a token; send it with POST, never in a URL`,
80
+ },
81
+ via,
82
+ };
83
+ }
84
+ const request = buildRequest(ctx.url.origin, pluginId, method, path, call.body, ctx.request);
85
+
86
+ if (handler) {
87
+ try {
88
+ return toResult<T>(await handler(pluginId, method, path, request), "in-process");
89
+ } catch (error) {
90
+ return failure(error, "in-process");
91
+ }
92
+ }
93
+
94
+ try {
95
+ const response = await (ctx.fetch ?? fetch)(request);
96
+ const envelope = (await response.json().catch(() => ({}))) as Envelope;
97
+ if (!response.ok && envelope.success !== false) {
98
+ return {
99
+ ok: false,
100
+ error: { code: `HTTP_${response.status}`, message: response.statusText || "Request failed" },
101
+ via: "fetch",
102
+ };
103
+ }
104
+ return toResult<T>(envelope, "fetch");
105
+ } catch (error) {
106
+ return failure(error, "fetch");
107
+ }
108
+ }
109
+
110
+ /** Tokens must never travel in URLs (BUILD-PLAN R10), so GET bodies may not carry token-like keys. */
111
+ const TOKEN_LIKE = /^(t|.*token.*|.*receipt.*|.*secret.*|.*otp.*)$/i;
112
+
113
+ function tokenLikeKey(body: unknown): string | undefined {
114
+ if (!body || typeof body !== "object") return undefined;
115
+ return Object.keys(body).find((key) => TOKEN_LIKE.test(key));
116
+ }
117
+
118
+ /** Headers that carry the visitor's address; the host trusts them per its own configuration. */
119
+ const CLIENT_IP_HEADERS = ["cf-connecting-ip", "x-forwarded-for", "x-real-ip", "true-client-ip", "fly-client-ip"];
120
+
121
+ function clientInit(incoming: Request | undefined): { headers: Headers; cf?: unknown } {
122
+ const headers = new Headers();
123
+ if (!incoming) return { headers };
124
+ for (const name of CLIENT_IP_HEADERS) {
125
+ const value = incoming.headers.get(name);
126
+ if (value) headers.set(name, value);
127
+ }
128
+ const cf = (incoming as Request & { cf?: unknown }).cf;
129
+ return cf === undefined ? { headers } : { headers, cf };
130
+ }
131
+
132
+ function buildRequest(
133
+ origin: string,
134
+ pluginId: string,
135
+ method: string,
136
+ path: string,
137
+ body: unknown,
138
+ incoming?: Request,
139
+ ): Request {
140
+ const url = new URL(`/_emdash/api/plugins/${encodeURIComponent(pluginId)}/${path}`, origin);
141
+ const init = clientInit(incoming);
142
+ if (method === "GET") {
143
+ if (body && typeof body === "object") {
144
+ for (const [key, value] of Object.entries(body)) {
145
+ for (const item of Array.isArray(value) ? value : [value]) {
146
+ if (item !== undefined && item !== null) url.searchParams.append(key, String(item));
147
+ }
148
+ }
149
+ }
150
+ return new Request(url, { ...init, method });
151
+ }
152
+ init.headers.set("content-type", "application/json");
153
+ return new Request(url, {
154
+ ...init,
155
+ method,
156
+ body: body === undefined ? undefined : JSON.stringify(body),
157
+ });
158
+ }
159
+
160
+ /** A sandboxed route's own refusal (`{ ok: false, error, issues? }`), which the host wraps as a success. */
161
+ function refusal(data: unknown): PublicRouteError | undefined {
162
+ if (!data || typeof data !== "object") return undefined;
163
+ const body = data as { ok?: unknown; error?: { code?: unknown; message?: unknown }; issues?: unknown };
164
+ if (body.ok !== false || typeof body.error?.code !== "string") return undefined;
165
+ return {
166
+ code: body.error.code,
167
+ message: typeof body.error.message === "string" ? body.error.message : "Request failed",
168
+ ...(Array.isArray(body.issues) ? { issues: body.issues as PublicRouteIssue[] } : {}),
169
+ };
170
+ }
171
+
172
+ function toResult<T>(envelope: Envelope, via: "in-process" | "fetch"): PublicRouteResult<T> {
173
+ if (envelope.success === true) {
174
+ const refused = refusal(envelope.data);
175
+ return refused ? { ok: false, error: refused, via } : { ok: true, data: envelope.data as T, via };
176
+ }
177
+ const code = typeof envelope.error?.code === "string" ? envelope.error.code : "ROUTE_CALL_FAILED";
178
+ const message = typeof envelope.error?.message === "string" ? envelope.error.message : "Request failed";
179
+ return { ok: false, error: { code, message }, via };
180
+ }
181
+
182
+ function failure<T>(error: unknown, via: "in-process" | "fetch"): PublicRouteResult<T> {
183
+ const message = error instanceof Error ? error.message : "Request failed";
184
+ return { ok: false, error: { code: "ROUTE_CALL_FAILED", message }, via };
185
+ }
@@ -0,0 +1,271 @@
1
+ import { callPublicRoute, type PublicRouteContext } from "./call";
2
+ import { isPayUrl } from "./payment";
3
+ import { answersFromForm } from "./questions";
4
+ import {
5
+ fieldsFromIssues,
6
+ newIdempotencyKey,
7
+ promoRefusal,
8
+ safeReturnTo,
9
+ validateCheckoutFields,
10
+ type WidgetField,
11
+ widgetErrorLocation,
12
+ } from "./widget";
13
+
14
+ export interface CheckoutFormOptions {
15
+ /** The core's plugin id. Defaults to the slug; registry installs pass their `r_…` id. */
16
+ pluginId?: string;
17
+ /** Injected for tests: makes the idempotency key when the form carries none. */
18
+ newKey?: () => string;
19
+ }
20
+
21
+ export interface CheckoutRedirect {
22
+ location: string;
23
+ /** The booking's access token, for an HttpOnly cookie scoped to `/booking`. Never in a URL. */
24
+ cookie?: { name: string; value: string };
25
+ }
26
+
27
+ export const BOOKING_PATH = "/booking";
28
+ /** Where the booking widget's form posts (injected by `eventsIntegration`). */
29
+ export const CHECKOUT_PATH = "/_events/checkout";
30
+ export const bookingCookieName = (ref: string) => `semics_booking_${ref}`;
31
+
32
+ export const QTY_PREFIX = "qty:";
33
+
34
+ /** The booking cookie: HttpOnly, scoped to the booking page, 30 days. */
35
+ export function bookingCookieOptions(url: URL) {
36
+ return {
37
+ path: BOOKING_PATH,
38
+ httpOnly: true,
39
+ sameSite: "lax" as const,
40
+ secure: url.protocol === "https:",
41
+ maxAge: 60 * 60 * 24 * 30,
42
+ };
43
+ }
44
+
45
+ /**
46
+ * True for a form post another site made (CSRF): the browser says so in `Sec-Fetch-Site`, or, from
47
+ * older browsers, an `Origin` that is not this site's. The booking forms check this themselves so
48
+ * they stay safe on a site that turns off Astro's `security.checkOrigin`; the SameSite=Lax cookie
49
+ * alone would still let another site start bookings in a visitor's name. Safe methods and clients
50
+ * that send neither header (not browsers) pass.
51
+ */
52
+ export function isCrossSiteRequest(request: Request, url: URL): boolean {
53
+ if (request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") return false;
54
+ const site = request.headers.get("sec-fetch-site");
55
+ if (site) return site !== "same-origin" && site !== "none";
56
+ const origin = request.headers.get("origin");
57
+ if (origin === null || origin === url.origin) return false;
58
+ // Astro builds `url` from `localhost` unless the host is in `security.allowedDomains`; the Host
59
+ // the browser sent is the site it posted to, and another site cannot set it.
60
+ try {
61
+ return new URL(origin).host !== request.headers.get("host");
62
+ } catch {
63
+ return true;
64
+ }
65
+ }
66
+
67
+ /** The answer to a refused cross-site post (another site's form, not a page a visitor reads). */
68
+ export const crossSiteResponse = () =>
69
+ // i18n-ignore
70
+ new Response("Cross-site form submissions are not allowed.", {
71
+ status: 403,
72
+ headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
73
+ });
74
+
75
+ const REF_PATTERN = /^[0-9A-HJKMNP-TV-Z]{10}$/;
76
+ /** What the booking page shows for an emailed link that is malformed, expired or already used. */
77
+ export const LINK_INVALID = "LINK_INVALID";
78
+
79
+ /**
80
+ * The emailed link (`/booking?ref=&k=<one-time code>`, R34): only ever called from the booking
81
+ * page's POST (its "Open my booking" button), never on GET, so a mail scanner that prefetches the
82
+ * link cannot use up the code. Swaps the code for a fresh access token through
83
+ * `public/booking/redeem` and lands on `/booking?ref=` without `k`, the token in the cookie.
84
+ */
85
+ export async function redeemBookingLink(
86
+ ctx: PublicRouteContext,
87
+ link: { ref: string; code: string },
88
+ options: Pick<CheckoutFormOptions, "pluginId">,
89
+ ): Promise<CheckoutRedirect> {
90
+ if (!REF_PATTERN.test(link.ref)) return fail(LINK_INVALID);
91
+ if (!link.code) return fail(LINK_INVALID, link.ref);
92
+ const redeemed = await callPublicRoute<{ bookingRef: string; accessToken: string }>(ctx, {
93
+ method: "POST",
94
+ path: "public/booking/redeem",
95
+ pluginId: options.pluginId,
96
+ body: { bookingRef: link.ref, code: link.code },
97
+ });
98
+ if (!redeemed.ok || !redeemed.data.accessToken) return fail(LINK_INVALID, link.ref);
99
+ return {
100
+ location: `${BOOKING_PATH}?ref=${encodeURIComponent(link.ref)}`,
101
+ cookie: { name: bookingCookieName(link.ref), value: redeemed.data.accessToken },
102
+ };
103
+ }
104
+
105
+ /** What the booking page shows for a waitlist offer link that lapsed, was used, or is not an offer. */
106
+ export const OFFER_INVALID = "OFFER_INVALID";
107
+
108
+ /**
109
+ * The emailed waitlist offer (`/booking?ref=&k=<one-time code>&offer=1`, T081): like the booking link,
110
+ * only ever from the page's POST ("Claim my tickets"). Claims it through `public/waitlist/claim`, keeps
111
+ * the fresh token in the cookie and continues the booking as "Pay now" does: a free booking is
112
+ * confirmed, a paid one goes to the payment page.
113
+ */
114
+ export async function claimOfferLink(
115
+ ctx: PublicRouteContext,
116
+ link: { ref: string; code: string },
117
+ options: Pick<CheckoutFormOptions, "pluginId">,
118
+ ): Promise<CheckoutRedirect> {
119
+ const ref = REF_PATTERN.test(link.ref) ? link.ref : "";
120
+ if (!ref || !link.code) return fail(OFFER_INVALID, ref);
121
+ const claimed = await callPublicRoute<{ accessToken: string }>(ctx, {
122
+ method: "POST",
123
+ path: "public/waitlist/claim",
124
+ pluginId: options.pluginId,
125
+ body: { bookingRef: ref, code: link.code },
126
+ });
127
+ if (!claimed.ok || !claimed.data.accessToken) return fail(OFFER_INVALID, ref);
128
+ const token = claimed.data.accessToken;
129
+ const next = await resumePayment(ctx, { ref, token }, options);
130
+ return { ...next, cookie: { name: bookingCookieName(ref), value: token } };
131
+ }
132
+
133
+ function text(form: FormData, key: string): string {
134
+ const value = form.get(key);
135
+ return typeof value === "string" ? value.trim() : "";
136
+ }
137
+
138
+ function fail(code: string, ref?: string, cookie?: CheckoutRedirect["cookie"]): CheckoutRedirect {
139
+ const query = new URLSearchParams();
140
+ if (ref) query.set("ref", ref);
141
+ query.set("error", code);
142
+ return { location: `${BOOKING_PATH}?${query}`, ...(cookie ? { cookie } : {}) };
143
+ }
144
+
145
+ /**
146
+ * The no-JS checkout (`POST /_events/checkout`): reserve, then continue, through the public routes
147
+ * only. The access token goes back as a cookie value, never in the redirect URL.
148
+ *
149
+ * A form from the booking widget carries `returnTo` (its own page): anything refused before a
150
+ * booking exists goes back there with the error code and the names of the fields to fix, never
151
+ * the values typed. Without a usable `returnTo`, refusals land on the booking page as before.
152
+ */
153
+ export async function handleCheckoutForm(
154
+ ctx: PublicRouteContext,
155
+ form: FormData,
156
+ options: CheckoutFormOptions,
157
+ ): Promise<CheckoutRedirect> {
158
+ const pluginId = options.pluginId;
159
+ const lines: Array<{ ticketTypeId: string; qty: number }> = [];
160
+ for (const [key, value] of form.entries()) {
161
+ if (!key.startsWith(QTY_PREFIX) || typeof value !== "string") continue;
162
+ const qty = Number.parseInt(value, 10);
163
+ if (qty > 0) lines.push({ ticketTypeId: key.slice(QTY_PREFIX.length), qty });
164
+ }
165
+ const eventId = text(form, "eventId");
166
+ const returnTo = safeReturnTo(text(form, "returnTo"), ctx.url.origin);
167
+ const refuse = (code: string, fields: WidgetField[] = []) =>
168
+ returnTo && eventId ? { location: widgetErrorLocation(returnTo, eventId, code, fields) } : fail(code);
169
+ if (!eventId) return fail("BAD_REQUEST");
170
+
171
+ const occurrenceId = text(form, "occurrenceId");
172
+ const buyer = { name: text(form, "name"), email: text(form, "email") };
173
+ const invalid = validateCheckoutFields({
174
+ ...buyer,
175
+ lines: lines.length,
176
+ needsOccurrence: form.get("needsOccurrence") === "1",
177
+ occurrenceId,
178
+ });
179
+ if (invalid.length > 0) return refuse("BAD_REQUEST", invalid);
180
+
181
+ const turnstileToken = text(form, "cf-turnstile-response");
182
+ // Only a typed code is sent: Free's reserve refuses unknown keys, and only Pro offers the field.
183
+ const promoCode = text(form, "promoCode");
184
+ // Likewise answers: only a widget that showed questions (Pro's `public/event` lists them) sends any.
185
+ const answers = answersFromForm(form);
186
+ const reserved = await callPublicRoute<{ bookingRef: string; accessToken?: string }>(ctx, {
187
+ method: "POST",
188
+ path: "public/checkout/reserve",
189
+ pluginId,
190
+ body: {
191
+ eventId,
192
+ ...(occurrenceId ? { occurrenceId } : {}),
193
+ lines,
194
+ buyer,
195
+ idempotencyKey: text(form, "idempotencyKey") || (options.newKey ?? newIdempotencyKey)(),
196
+ ...(turnstileToken ? { turnstileToken } : {}),
197
+ ...(promoCode ? { promoCode } : {}),
198
+ ...(answers ? { answers } : {}),
199
+ },
200
+ });
201
+ if (!reserved.ok) {
202
+ const { issues } = reserved.error;
203
+ const code = promoCode ? promoRefusal(reserved.error.code) : reserved.error.code;
204
+ const fields: WidgetField[] = code.startsWith("PROMO_") ? ["promo"] : [];
205
+ return refuse(code, code === "BAD_REQUEST" ? fieldsFromIssues(issues) : fields);
206
+ }
207
+
208
+ const { bookingRef, accessToken } = reserved.data;
209
+ const done = `${BOOKING_PATH}?ref=${encodeURIComponent(bookingRef)}`;
210
+ // A resubmit of a booking that is already confirmed gets no new token: this browser has its cookie.
211
+ if (!accessToken) return { location: done };
212
+ const cookie = { name: bookingCookieName(bookingRef), value: accessToken };
213
+ const next = await callPublicRoute<{ next?: { type?: string; url?: string } }>(ctx, {
214
+ method: "POST",
215
+ path: "public/checkout/continue",
216
+ pluginId,
217
+ body: { bookingRef, accessToken },
218
+ });
219
+ if (!next.ok) return fail(next.error.code, bookingRef, cookie);
220
+
221
+ const step = next.data.next;
222
+ if (step?.type === "pay")
223
+ return isPayUrl(step.url) ? { location: step.url, cookie } : fail("PAYMENT_FAILED", bookingRef, cookie);
224
+ return { location: done, cookie };
225
+ }
226
+
227
+ /**
228
+ * "Pay now" on the booking page (EU-FR-09): continues the held or awaiting-payment booking again
229
+ * with the cookie's token (Events Pro answers with the payment page again, or a new one) and follows
230
+ * the `pay` step. Anything else lands on the booking page, which shows the booking as it is.
231
+ */
232
+ export async function resumePayment(
233
+ ctx: PublicRouteContext,
234
+ input: { ref: string; token: string },
235
+ options: Pick<CheckoutFormOptions, "pluginId">,
236
+ ): Promise<{ location: string }> {
237
+ if (!REF_PATTERN.test(input.ref)) return { location: BOOKING_PATH };
238
+ const page = `${BOOKING_PATH}?ref=${encodeURIComponent(input.ref)}`;
239
+ if (!input.token) return { location: page };
240
+ const next = await callPublicRoute<{ next?: { type?: string; url?: unknown } }>(ctx, {
241
+ method: "POST",
242
+ path: "public/checkout/continue",
243
+ pluginId: options.pluginId,
244
+ body: { bookingRef: input.ref, accessToken: input.token },
245
+ });
246
+ if (!next.ok) return fail(next.error.code, input.ref);
247
+ const step = next.data.next;
248
+ if (step?.type === "pay") return isPayUrl(step.url) ? { location: step.url } : fail("PAYMENT_FAILED", input.ref);
249
+ return { location: page };
250
+ }
251
+
252
+ /** What `POST /_events/checkout` gets from Astro. */
253
+ export interface CheckoutEndpointContext {
254
+ request: Request;
255
+ url: URL;
256
+ locals: PublicRouteContext["locals"];
257
+ redirect(location: string, status?: number): Response;
258
+ cookies: { set(name: string, value: string, options: Record<string, unknown>): void };
259
+ }
260
+
261
+ /** `POST /_events/checkout`: refuse cross-site posts, then run the form and redirect (303). */
262
+ export async function handleCheckoutRequest(
263
+ { request, url, locals, redirect, cookies }: CheckoutEndpointContext,
264
+ options: CheckoutFormOptions,
265
+ ): Promise<Response> {
266
+ if (isCrossSiteRequest(request, url)) return crossSiteResponse();
267
+ const form = await request.formData().catch(() => new FormData());
268
+ const result = await handleCheckoutForm({ locals, url, request }, form, options);
269
+ if (result.cookie) cookies.set(result.cookie.name, result.cookie.value, bookingCookieOptions(url));
270
+ return redirect(result.location, 303);
271
+ }