@composable-os/pack-forms 0.0.0-stage → 0.1.0-beta.12

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.
@@ -0,0 +1,634 @@
1
+ // The form page (stage 29 step 4, ADR 0728): a form drawn as plain HTML by the server, for a link
2
+ // or a QR code (`/f/<slug>`) and for a personal link from an email (`/form?t=<token>`). It is a web
3
+ // skin over the headless entry's logic (`../client`), with no framework and no build step: the
4
+ // host serves it on its own address (apps/app), and a business's web app serves it on its own
5
+ // site by forwarding these two paths to the host over its binding (the client template's
6
+ // `formPageRoute`). It works without JavaScript: the form posts to its own address and the answer
7
+ // is the next page. The little script it has only takes a personal link's token out of the
8
+ // address bar and hides the questions shown only if an earlier answer says so.
9
+ //
10
+ // It holds no rules. It reaches the host through the typed client only (`x.forms.form`,
11
+ // `x.forms.submit`): whether the form is open to the caller, the spam checks, the caps, who may
12
+ // answer and once only are the door's; the page shows the host's answer. Before sending, the
13
+ // answers are checked with the same `checkAnswers` the host runs, for the words beside each
14
+ // question; the host checks them again.
15
+ //
16
+ // A personal link's page (ADR 0723, the security review of PR #458):
17
+ // - is sent with `Referrer-Policy: no-referrer`, so the token never leaves as a referrer;
18
+ // - loads no script from anywhere else (no Turnstile: a link skips it at the host), by its
19
+ // Content-Security-Policy too;
20
+ // - takes the token out of the address bar once loaded (`history.replaceState`), keeping it only
21
+ // in the page, in the form's hidden field, for the send;
22
+ // - and opening it (a GET, a mail scanner's) uses nothing: only the send uses the link.
23
+ //
24
+ // Every page is never cached, never framed (`frame-ancestors 'none'`), sets no cookie and keeps
25
+ // nothing a person typed: what they typed is in the request and, when something needs another
26
+ // look, in the page drawn back to them, and nowhere else.
27
+ import { createClient } from "@composable-os/client";
28
+ import { PERSONAL_LINK_PARAM, PERSONAL_LINK_PATH } from "@composable-os/sdk";
29
+ import { answersFrom, checkDraft, draftFromFields, FORMS_OPERATIONS, fieldName, formQuestions, HONEYPOT_FIELD, isAsked, ratingLabel, ratingValues, refusalOf, } from "./index.js";
30
+ /** Where a form's own page is: `/f/<slug>`. */
31
+ export const FORM_PAGE_PREFIX = "/f/";
32
+ /** Where a personal link opens (the SDK's PERSONAL_LINK_PATH): `/form?t=<token>`. */
33
+ export const LINK_PAGE_PATH = PERSONAL_LINK_PATH;
34
+ /** Turnstile's script and frames come from here, on a public form's page only. */
35
+ export const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
36
+ const TURNSTILE_SCRIPT = `${TURNSTILE_ORIGIN}/turnstile/v0/api.js`;
37
+ /** Whether `pathname` is one of the form page's: `/form`, or `/f/<one part>`. */
38
+ export function isFormPagePath(pathname) {
39
+ if (pathname === LINK_PAGE_PATH)
40
+ return true;
41
+ return pathname.startsWith(FORM_PAGE_PREFIX) && !pathname.slice(3).includes("/");
42
+ }
43
+ /**
44
+ * The page's client over a host: the typed client of the two operations, calling the HTTP surface
45
+ * through `fetch` (the host's own surface in-process, or a binding) with `headers` (the visitor's
46
+ * session cookie, and nothing else). It never retries: a send is the person's to make again.
47
+ */
48
+ export function formPageClient(options) {
49
+ return createClient(FORMS_OPERATIONS, {
50
+ baseUrl: "https://host",
51
+ fetch: options.fetch,
52
+ ...(options.headers ? { headers: options.headers } : {}),
53
+ retries: 0,
54
+ });
55
+ }
56
+ /**
57
+ * Whether a browser's POST comes from the page's own origin (ADR 0728, review of PR #461): an
58
+ * allow-list. With `Sec-Fetch-Site`, only `same-origin` (or `none`, a person's own action); a
59
+ * sibling subdomain is `same-site` and is refused, as a customer's cookie still goes with it.
60
+ * Without it (an older browser), `Origin` must be the page's own, or `null` (the page's own
61
+ * no-referrer policy makes a browser send `null`).
62
+ */
63
+ export function sameOriginPost(headers, pageOrigin) {
64
+ const site = headers.get("sec-fetch-site");
65
+ if (site !== null)
66
+ return site === "same-origin" || site === "none";
67
+ const origin = headers.get("origin");
68
+ return origin === "null" || origin === pageOrigin;
69
+ }
70
+ /**
71
+ * A request's body as text, read only up to `max` bytes: null when it says (`content-length`) or
72
+ * turns out to be longer, so a large body is never held whole.
73
+ */
74
+ export async function cappedText(request, max) {
75
+ const declared = Number(request.headers.get("content-length") ?? "");
76
+ if (Number.isFinite(declared) && declared > max)
77
+ return null;
78
+ if (!request.body)
79
+ return "";
80
+ const reader = request.body.getReader();
81
+ const chunks = [];
82
+ let size = 0;
83
+ for (;;) {
84
+ const { done, value } = await reader.read();
85
+ if (done)
86
+ break;
87
+ size += value.byteLength;
88
+ if (size > max) {
89
+ await reader.cancel().catch(() => undefined);
90
+ return null;
91
+ }
92
+ chunks.push(value);
93
+ }
94
+ const bytes = new Uint8Array(size);
95
+ let at = 0;
96
+ for (const chunk of chunks) {
97
+ bytes.set(chunk, at);
98
+ at += chunk.byteLength;
99
+ }
100
+ return new TextDecoder().decode(bytes);
101
+ }
102
+ // Each answer is an id in the page, so its label, help and error are tied to it.
103
+ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
104
+ const TOKEN = /^[A-Za-z0-9_-]{43}$/;
105
+ const KEY = /^[A-Za-z0-9._:-]{16,128}$/;
106
+ /** The most a posted form may be, in bytes: the answers' 20 KB, URL-encoded, and the page's own fields. */
107
+ export const MAX_BODY = 131_072;
108
+ /** The one script the page runs, inline and allowed by its hash alone. */
109
+ export const PAGE_SCRIPT = `(function () {
110
+ var url = new URL(location.href);
111
+ if (url.searchParams.has("${PERSONAL_LINK_PARAM}")) {
112
+ url.searchParams.delete("${PERSONAL_LINK_PARAM}");
113
+ history.replaceState(null, "", url.pathname + url.search + url.hash);
114
+ }
115
+ var form = document.querySelector("form[data-form]");
116
+ if (!form) return;
117
+ function values(key) {
118
+ var out = [];
119
+ form.querySelectorAll('[name="a.' + key + '"]').forEach(function (field) {
120
+ if (field.type === "radio" || field.type === "checkbox" ? field.checked : field.value !== "")
121
+ out.push(field.value);
122
+ });
123
+ return out;
124
+ }
125
+ function sync() {
126
+ form.querySelectorAll("[data-show-q]").forEach(function (item) {
127
+ var on = values(item.getAttribute("data-show-q")).indexOf(item.getAttribute("data-show-is")) >= 0;
128
+ item.hidden = !on;
129
+ item.querySelectorAll("input, select, textarea").forEach(function (field) {
130
+ field.disabled = !on;
131
+ });
132
+ });
133
+ }
134
+ form.addEventListener("change", sync);
135
+ sync();
136
+ form.addEventListener("submit", function () {
137
+ var button = form.querySelector('button[type="submit"]');
138
+ if (button) setTimeout(function () { button.disabled = true; }, 0);
139
+ });
140
+ })();`;
141
+ let scriptHash = null;
142
+ /** The script's CSP source: `'sha256-…'`. */
143
+ export function pageScriptSource() {
144
+ scriptHash ??= crypto.subtle
145
+ .digest("SHA-256", new TextEncoder().encode(PAGE_SCRIPT))
146
+ .then((digest) => {
147
+ let s = "";
148
+ for (const b of new Uint8Array(digest))
149
+ s += String.fromCharCode(b);
150
+ return `'sha256-${btoa(s)}'`;
151
+ });
152
+ return scriptHash;
153
+ }
154
+ /** The headers of every page: never cached, framed or sent on; Turnstile only where asked. */
155
+ async function pageHeaders(turnstile) {
156
+ const script = await pageScriptSource();
157
+ const policy = [
158
+ "default-src 'none'",
159
+ `script-src ${script}${turnstile ? ` ${TURNSTILE_ORIGIN}` : ""}`,
160
+ ...(turnstile ? [`frame-src ${TURNSTILE_ORIGIN}`, `connect-src ${TURNSTILE_ORIGIN}`] : []),
161
+ "style-src 'unsafe-inline'",
162
+ "form-action 'self'",
163
+ "frame-ancestors 'none'",
164
+ "base-uri 'none'",
165
+ ].join("; ");
166
+ return new Headers({
167
+ "content-type": "text/html; charset=utf-8",
168
+ "cache-control": "no-store",
169
+ "referrer-policy": "no-referrer",
170
+ "x-frame-options": "DENY",
171
+ "x-content-type-options": "nosniff",
172
+ "content-security-policy": policy,
173
+ "permissions-policy": "camera=(), microphone=(), geolocation=()",
174
+ });
175
+ }
176
+ const esc = (text) => text
177
+ .replaceAll("&", "&amp;")
178
+ .replaceAll("<", "&lt;")
179
+ .replaceAll(">", "&gt;")
180
+ .replaceAll('"', "&quot;")
181
+ .replaceAll("'", "&#39;");
182
+ const STYLE = `
183
+ :root { color-scheme: light dark; --fg: #18181b; --muted: #52525b; --bg: #ffffff; --line: #a1a1aa;
184
+ --accent: #1d4ed8; --danger: #b91c1c; --surface: #f4f4f5; }
185
+ @media (prefers-color-scheme: dark) { :root { --fg: #f4f4f5; --muted: #d4d4d8; --bg: #18181b;
186
+ --line: #71717a; --accent: #93c5fd; --danger: #fca5a5; --surface: #27272a; } }
187
+ * { box-sizing: border-box; }
188
+ body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.5 system-ui, sans-serif; }
189
+ main { max-width: 40rem; margin: 0 auto; padding: 2rem 1rem 4rem; }
190
+ h1 { font-size: 1.75rem; line-height: 1.25; margin: 0 0 1.5rem; }
191
+ h2 { font-size: 1.25rem; margin: 1.5rem 0 0.5rem; }
192
+ .q { margin: 0 0 1.5rem; border: 0; padding: 0; min-width: 0; }
193
+ .q > label, .q > legend { display: block; font-weight: 600; margin-bottom: 0.25rem; padding: 0; }
194
+ .req { font-weight: 400; color: var(--muted); }
195
+ .help, .when { color: var(--muted); margin: 0 0 0.5rem; }
196
+ .when { font-size: 0.875rem; }
197
+ .error { color: var(--danger); font-weight: 600; margin: 0 0 0.5rem; }
198
+ input[type=text], input[type=email], input[type=tel], input[type=number], input[type=date],
199
+ textarea, select { display: block; width: 100%; min-height: 2.75rem; padding: 0.5rem 0.75rem;
200
+ font: inherit; color: inherit; background: var(--bg); border: 1px solid var(--line);
201
+ border-radius: 0.375rem; }
202
+ textarea { min-height: 8rem; resize: vertical; }
203
+ [aria-invalid=true] { border-color: var(--danger); border-width: 2px; }
204
+ .option { display: flex; align-items: flex-start; gap: 0.5rem; min-height: 2.75rem; padding: 0.5rem 0; }
205
+ .option input { width: 1.25rem; height: 1.25rem; margin: 0.125rem 0 0; flex: none; }
206
+ .scale { display: flex; flex-wrap: wrap; gap: 0.5rem; }
207
+ .scale .option { border: 1px solid var(--line); border-radius: 0.375rem; padding: 0.5rem 0.75rem; }
208
+ :focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
209
+ button { min-height: 2.75rem; padding: 0.5rem 1.25rem; font: inherit; font-weight: 600;
210
+ color: var(--bg); background: var(--fg); border: 0; border-radius: 0.375rem; cursor: pointer; }
211
+ button[disabled] { opacity: 0.6; }
212
+ .summary { border: 2px solid var(--danger); border-radius: 0.375rem; padding: 0.75rem 1rem;
213
+ margin: 0 0 1.5rem; }
214
+ .summary h2 { margin-top: 0; font-size: 1.125rem; }
215
+ .summary a { color: var(--danger); }
216
+ .note { background: var(--surface); border-radius: 0.375rem; padding: 0.75rem 1rem; margin: 0 0 1.5rem; }
217
+ .hp { position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden; }
218
+ `;
219
+ async function page(status, title, body, { turnstile = false } = {}) {
220
+ const html = `<!doctype html>
221
+ <html lang="en">
222
+ <head>
223
+ <meta charset="utf-8">
224
+ <meta name="viewport" content="width=device-width, initial-scale=1">
225
+ <meta name="robots" content="noindex, nofollow">
226
+ <meta name="referrer" content="no-referrer">
227
+ <title>${esc(title)}</title>
228
+ <style>${STYLE}</style>
229
+ ${turnstile ? `<script src="${TURNSTILE_SCRIPT}" async defer></script>` : ""}
230
+ </head>
231
+ <body>
232
+ <main>
233
+ ${body}
234
+ </main>
235
+ <script>${PAGE_SCRIPT}</script>
236
+ </body>
237
+ </html>`;
238
+ return new Response(html, { status, headers: await pageHeaders(turnstile) });
239
+ }
240
+ /** A page with one heading and one line: not found, used, thanks, try later. */
241
+ function notice(status, title, line, role = "status") {
242
+ return page(status, title, `<h1>${esc(title)}</h1>\n<p role="${role}">${esc(line)}</p>`);
243
+ }
244
+ const notOpen = () => notice(404, "This form is not open", "This form is not taking answers just now.");
245
+ // --- Drawing a form ------------------------------------------------------------------------------
246
+ /** Rich text's inline runs as HTML: text, bold, italic, code, links of the schemes it allows. */
247
+ function inlines(content) {
248
+ if (!Array.isArray(content))
249
+ return "";
250
+ return content
251
+ .map((run) => {
252
+ if (run?.type === "break")
253
+ return "<br>";
254
+ if (run?.type !== "text" || typeof run.text !== "string")
255
+ return "";
256
+ let html = esc(run.text);
257
+ if (run.code)
258
+ html = `<code>${html}</code>`;
259
+ if (run.italic)
260
+ html = `<em>${html}</em>`;
261
+ if (run.bold)
262
+ html = `<strong>${html}</strong>`;
263
+ if (typeof run.href === "string" && /^(?:https?:|mailto:)/i.test(run.href)) {
264
+ html = `<a href="${esc(run.href)}" rel="noopener noreferrer nofollow">${html}</a>`;
265
+ }
266
+ return html;
267
+ })
268
+ .join("");
269
+ }
270
+ const id = (prefix, key) => `${prefix}-${key}`;
271
+ /** The `aria-describedby` of a question: its help and its error, where it has them. */
272
+ function described(item, error) {
273
+ const ids = [item.help ? id("h", item.key) : null, error ? id("e", item.key) : null].filter(Boolean);
274
+ return ids.length ? ` aria-describedby="${ids.join(" ")}"` : "";
275
+ }
276
+ function helpAndError(item, error) {
277
+ return ((item.help ? `<p class="help" id="${id("h", item.key)}">${esc(item.help)}</p>` : "") +
278
+ (error ? `<p class="error" id="${id("e", item.key)}">${esc(error)}</p>` : ""));
279
+ }
280
+ const AUTOCOMPLETE = { name: "name", email: "email", phone: "tel" };
281
+ /** One item of the form, with what was typed (drawn back after a refusal) and its error. */
282
+ function itemHtml(item, questions, value, error) {
283
+ // Shown only if an earlier answer has a value: the script hides it until then; without
284
+ // JavaScript it says when to answer it, and an answer to it is not sent while it does not hold.
285
+ const condition = item.showIf
286
+ ? ` data-show-q="${esc(item.showIf.question)}" data-show-is="${esc(item.showIf.is)}"`
287
+ : "";
288
+ const target = item.showIf ? questions.items.find((q) => q.key === item.showIf?.question) : null;
289
+ const when = item.showIf && (target?.kind === "yesNo" || target?.kind === "choice")
290
+ ? `<p class="when">Answer this only if you answered “${esc(target.kind === "yesNo" ? (item.showIf.is === "yes" ? "Yes" : "No") : item.showIf.is)}” to “${esc(target.label)}”.</p>`
291
+ : "";
292
+ if (item.kind === "heading")
293
+ return `<h2${condition}>${esc(item.text)}</h2>`;
294
+ if (item.kind === "paragraph")
295
+ return `<p${condition}>${inlines(item.content)}</p>`;
296
+ const field = esc(fieldName(item.key));
297
+ const input = esc(id("f", item.key));
298
+ const invalid = error ? ` aria-invalid="true"` : "";
299
+ const required = item.required ? " required" : "";
300
+ const requiredWords = item.required ? ` <span class="req">(required)</span>` : "";
301
+ // A question shown only if another holds is never required by the browser: it may be hidden.
302
+ const native = item.showIf ? "" : required;
303
+ if (item.kind === "consent") {
304
+ const ticked = value === true ? " checked" : "";
305
+ return `<div class="q" id="${esc(id("q", item.key))}"${condition}>${when}${helpAndError(item, error)}
306
+ <div class="option"><input type="checkbox" id="${input}" name="${field}" value="yes"${ticked}${native}${invalid}${described(item, error)}>
307
+ <label for="${input}">${esc(item.words).replaceAll("\n", "<br>")}${requiredWords}</label></div></div>`;
308
+ }
309
+ const label = `${esc(item.label)}${requiredWords}`;
310
+ const options = (choices, type) => choices
311
+ .map((c, i) => `<div class="option"><input type="${type}" id="${input}-${i}" name="${field}" value="${esc(c.value)}"${c.checked ? " checked" : ""}${type === "radio" ? native : ""}${invalid}><label for="${input}-${i}">${esc(c.label)}</label></div>`)
312
+ .join("\n");
313
+ const group = (inner, scale = false) => `<fieldset class="q" id="${esc(id("q", item.key))}"${condition}${described(item, error)}><legend>${label}</legend>${when}${helpAndError(item, error)}${scale ? `<div class="scale">${inner}</div>` : inner}</fieldset>`;
314
+ switch (item.kind) {
315
+ case "choice": {
316
+ const chosen = Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
317
+ return group(options(item.options.map((o) => ({ value: o, label: o, checked: chosen.includes(o) })), item.multiple ? "checkbox" : "radio"));
318
+ }
319
+ case "rating":
320
+ return group(options(ratingValues(item).map((n) => ({
321
+ value: String(n),
322
+ label: ratingLabel(item, n),
323
+ checked: value === n,
324
+ })), "radio"), true);
325
+ case "yesNo":
326
+ return group(options([
327
+ { value: "yes", label: "Yes", checked: value === true },
328
+ { value: "no", label: "No", checked: value === false },
329
+ ], "radio"), true);
330
+ default: {
331
+ const text = typeof value === "string" ? value : "";
332
+ const auto = item.map?.to === "person" ? AUTOCOMPLETE[item.map.field] : undefined;
333
+ const common = `id="${input}" name="${field}"${native}${invalid}${described(item, error)}${auto ? ` autocomplete="${auto}"` : ""}`;
334
+ let control;
335
+ if (item.kind === "text" && item.long) {
336
+ control = `<textarea ${common} rows="6" maxlength="${item.max ?? 5000}">${esc(text)}</textarea>`;
337
+ }
338
+ else {
339
+ const attrs = item.kind === "text"
340
+ ? `type="text" maxlength="${item.max ?? 200}"`
341
+ : item.kind === "email"
342
+ ? `type="email" maxlength="320" inputmode="email"${auto ? "" : ` autocomplete="email"`}`
343
+ : item.kind === "phone"
344
+ ? `type="tel" maxlength="40" inputmode="tel"${auto ? "" : ` autocomplete="tel"`}`
345
+ : item.kind === "number"
346
+ ? `type="number" inputmode="decimal" step="${item.integer ? "1" : "any"}"${item.min !== undefined ? ` min="${item.min}"` : ""}${item.max !== undefined ? ` max="${item.max}"` : ""}`
347
+ : `type="date"`;
348
+ control = `<input ${attrs} ${common} value="${esc(text)}">`;
349
+ }
350
+ return `<div class="q" id="${esc(id("q", item.key))}"${condition}><label for="${input}">${label}</label>${when}${helpAndError(item, error)}${control}</div>`;
351
+ }
352
+ }
353
+ }
354
+ function skeletonOf(questions) {
355
+ return questions.items.map((item) => ({
356
+ k: item.key,
357
+ t: item.kind,
358
+ ...(item.kind === "choice" && item.multiple ? { m: 1 } : {}),
359
+ ...(item.kind === "text" && item.long ? { l: 1 } : {}),
360
+ ...(item.showIf ? { s: [item.showIf.question, item.showIf.is] } : {}),
361
+ }));
362
+ }
363
+ /** The questions a skeleton stands for, or null when it is not one. */
364
+ function questionsOfSkeleton(text) {
365
+ try {
366
+ const parsed = JSON.parse(text ?? "");
367
+ if (!Array.isArray(parsed) || parsed.length > 60)
368
+ return null;
369
+ const items = parsed.map((raw) => {
370
+ const r = raw;
371
+ if (typeof r.k !== "string" || typeof r.t !== "string")
372
+ throw new Error("not a skeleton");
373
+ const show = Array.isArray(r.s) && typeof r.s[0] === "string" && typeof r.s[1] === "string"
374
+ ? { showIf: { question: r.s[0], is: r.s[1] } }
375
+ : {};
376
+ return {
377
+ key: r.k,
378
+ kind: r.t,
379
+ label: "",
380
+ options: [],
381
+ ...(r.m ? { multiple: true } : {}),
382
+ ...(r.l ? { long: true } : {}),
383
+ ...show,
384
+ };
385
+ });
386
+ return { items };
387
+ }
388
+ catch {
389
+ return null;
390
+ }
391
+ }
392
+ function formPageOf(d) {
393
+ const questions = formQuestions(d.opened);
394
+ const errors = d.errors ?? {};
395
+ const title = d.opened.title ?? "Form";
396
+ // A personal link skips the spam check at the host: its page loads nothing from anywhere else.
397
+ const turnstile = !d.link && d.opened.turnstile;
398
+ const canCheck = turnstile && Boolean(d.turnstileSiteKey);
399
+ const faults = questions.items.filter((item) => errors[item.key]);
400
+ const summary = faults.length || d.problem
401
+ ? `<div class="summary" role="alert" tabindex="-1" autofocus><h2>${faults.length ? "Some answers need another look" : "Your answers were not sent"}</h2>${d.problem ? `<p>${esc(d.problem)}</p>` : ""}${faults.length
402
+ ? `<ul>${faults
403
+ .map((item) => {
404
+ const name = isAsked(item)
405
+ ? item.kind === "consent"
406
+ ? item.words
407
+ : item.label
408
+ : "";
409
+ const grouped = ["choice", "rating", "yesNo"].includes(item.kind);
410
+ const field = `${id("f", item.key)}${grouped ? "-0" : ""}`;
411
+ return `<li><a href="#${esc(field)}">${esc(name.slice(0, 120))}: ${esc(errors[item.key] ?? "")}</a></li>`;
412
+ })
413
+ .join("")}</ul>`
414
+ : ""}</div>`
415
+ : "";
416
+ const items = questions.items
417
+ .map((item) => itemHtml(item, questions, d.draft && Object.hasOwn(d.draft, item.key) ? d.draft[item.key] : undefined, errors[item.key]))
418
+ .join("\n");
419
+ const hidden = [
420
+ ["_id", d.opened.id],
421
+ ["_version", String(d.opened.version)],
422
+ ...(d.opened.shown && !d.link ? [["_shown", d.opened.shown]] : []),
423
+ // One key for this page's send: a second press, or the browser posting it again, is the
424
+ // same send to the host, which answers it once.
425
+ ["_key", crypto.randomUUID()],
426
+ ...(d.link
427
+ ? [
428
+ ["_link", d.link],
429
+ ["_q", JSON.stringify(skeletonOf(questions))],
430
+ ]
431
+ : []),
432
+ ]
433
+ .map(([name, value]) => `<input type="hidden" name="${name}" value="${esc(value ?? "")}">`)
434
+ .join("\n");
435
+ const cannotCheck = turnstile && !canCheck
436
+ ? `<p class="note" role="note">This form cannot be sent from this page just now. Please try again later.</p>`
437
+ : "";
438
+ const body = `<h1>${esc(title)}</h1>
439
+ ${summary}${cannotCheck}
440
+ <form method="post" action="${esc(d.action)}" data-form>
441
+ ${hidden}
442
+ <div class="hp" aria-hidden="true"><label for="f-${HONEYPOT_FIELD}">Leave this empty</label><input type="text" id="f-${HONEYPOT_FIELD}" name="${HONEYPOT_FIELD}" tabindex="-1" autocomplete="off"></div>
443
+ ${items}
444
+ ${canCheck
445
+ ? `<div class="cf-turnstile" data-sitekey="${esc(d.turnstileSiteKey ?? "")}"></div>
446
+ <noscript><p class="note">This form needs JavaScript for its spam check.</p></noscript>`
447
+ : ""}
448
+ <p><button type="submit">Send</button></p>
449
+ </form>`;
450
+ return page(d.problem || faults.length ? 422 : 200, title, body, { turnstile: canCheck });
451
+ }
452
+ // --- The routes ----------------------------------------------------------------------------------
453
+ function slugOf(pathname) {
454
+ let slug;
455
+ try {
456
+ slug = decodeURIComponent(pathname.slice(FORM_PAGE_PREFIX.length));
457
+ }
458
+ catch {
459
+ return null;
460
+ }
461
+ return slug.length <= 200 && SLUG.test(slug) ? slug : null;
462
+ }
463
+ /** The status a refusal is answered with. */
464
+ function statusOf(refusal) {
465
+ switch (refusal.kind) {
466
+ case "answers":
467
+ return 422;
468
+ case "reload":
469
+ return 409;
470
+ case "later":
471
+ return 429;
472
+ case "offline":
473
+ return 503;
474
+ default:
475
+ return 400;
476
+ }
477
+ }
478
+ /**
479
+ * Serves one request to the form page: GET (or HEAD) draws the form, POST sends it. A path that is
480
+ * not the page's is not found. Never throws.
481
+ */
482
+ export async function formPage(request, options) {
483
+ const url = new URL(request.url);
484
+ const isLink = url.pathname === LINK_PAGE_PATH;
485
+ const slug = isLink ? null : slugOf(url.pathname);
486
+ if (!isLink && !slug)
487
+ return notOpen();
488
+ if (request.method === "GET" || request.method === "HEAD") {
489
+ const response = await show(url, isLink, slug, options);
490
+ return request.method === "HEAD"
491
+ ? new Response(null, { status: response.status, headers: response.headers })
492
+ : response;
493
+ }
494
+ if (request.method !== "POST") {
495
+ const refused = await notice(405, "Not allowed", "Open this page with its link.");
496
+ refused.headers.set("allow", "GET, HEAD, POST");
497
+ return refused;
498
+ }
499
+ // A send comes from this page: never another site's form, nor a sibling subdomain's.
500
+ if ((options.sameOrigin ?? "page") === "page" && !sameOriginPost(request.headers, url.origin)) {
501
+ return notice(403, "Not sent", "Answers are sent from this page only.", "alert");
502
+ }
503
+ const type = request.headers.get("content-type") ?? "";
504
+ if (!/^application\/x-www-form-urlencoded\b/i.test(type)) {
505
+ return notice(415, "Not sent", "Answers are sent from this page's form.", "alert");
506
+ }
507
+ const text = await cappedText(request, MAX_BODY);
508
+ if (text === null) {
509
+ return notice(413, "Not sent", "The answers are too long to send: shorten them.", "alert");
510
+ }
511
+ return send(new URLSearchParams(text), isLink, slug, options);
512
+ }
513
+ async function open(options, isLink, slug, link) {
514
+ try {
515
+ // Opening a form by its link uses nothing: only the send does (ADR 0723).
516
+ return await options.client.call("x.forms.form", isLink ? { link: link ?? "" } : { slug: slug ?? "" });
517
+ }
518
+ catch (error) {
519
+ return refusalOf(error);
520
+ }
521
+ }
522
+ const isRefusal = (value) => "kind" in value;
523
+ async function cannotOpen(refusal, isLink) {
524
+ if (refusal.kind === "offline" || refusal.kind === "later" || refusal.kind === "other") {
525
+ return notice(503, "Try again shortly", "This form could not be opened just now.", "alert");
526
+ }
527
+ if (isLink) {
528
+ return notice(404, "This link cannot be used", "It may have been used already or have expired. Nothing more is needed from you.");
529
+ }
530
+ return notOpen();
531
+ }
532
+ async function show(url, isLink, slug, options) {
533
+ const token = isLink ? url.searchParams.get(PERSONAL_LINK_PARAM) : null;
534
+ if (isLink && !(token && TOKEN.test(token))) {
535
+ return notice(404, "This link is not complete", "Open the link from your email again, or copy all of it into the address bar.");
536
+ }
537
+ const opened = await open(options, isLink, slug, token);
538
+ if (isRefusal(opened))
539
+ return cannotOpen(opened, isLink);
540
+ return formPageOf({
541
+ opened,
542
+ action: isLink ? LINK_PAGE_PATH : `${FORM_PAGE_PREFIX}${slug}`,
543
+ ...(token ? { link: token } : {}),
544
+ turnstileSiteKey: options.turnstileSiteKey ?? null,
545
+ });
546
+ }
547
+ /** The thanks for a send the host already took, when the form cannot be opened again. */
548
+ const sentAlready = () => page(200, "Thank you", `<h1>Thank you</h1>\n<p role="status">${esc("Thank you. Your answers were sent.")}</p>`);
549
+ /**
550
+ * A link's send again (a reload after it went): the same answers, by the page's `_q`, under the
551
+ * page's key, so the host's stored reply answers. Null when it does not (a link used another way,
552
+ * or never by this page): the page then says the link cannot be used.
553
+ */
554
+ async function replay(posted, token, options) {
555
+ const key = posted.get("_key") ?? "";
556
+ const id = posted.get("_id") ?? "";
557
+ const version = Number(posted.get("_version"));
558
+ const questions = questionsOfSkeleton(posted.get("_q"));
559
+ if (!KEY.test(key) || !id || !Number.isInteger(version) || version < 1 || !questions)
560
+ return null;
561
+ const answers = answersFrom(questions, draftFromFields(questions, (name) => posted.getAll(name)));
562
+ const honeypot = posted.get(HONEYPOT_FIELD);
563
+ try {
564
+ await options.client.call("x.forms.submit", { id, version, answers, link: token, ...(honeypot ? { honeypot } : {}) }, { idempotencyKey: key });
565
+ return sentAlready();
566
+ }
567
+ catch {
568
+ return null;
569
+ }
570
+ }
571
+ async function send(posted, isLink, slug, options) {
572
+ const token = isLink ? posted.get("_link") : null;
573
+ if (isLink && !(token && TOKEN.test(token))) {
574
+ return notice(404, "This link cannot be used", "Open the link from your email again.");
575
+ }
576
+ // The form as it is now, for its questions: the version the person saw is sent with the
577
+ // answers, and the host says "load it again" when it changed.
578
+ const opened = await open(options, isLink, slug, token);
579
+ if (isRefusal(opened)) {
580
+ // A link used by this very page's send (a reload of the thanks): its stored reply answers.
581
+ if (isLink && opened.kind === "gone" && token) {
582
+ const replayed = await replay(posted, token, options);
583
+ if (replayed)
584
+ return replayed;
585
+ }
586
+ return cannotOpen(opened, isLink);
587
+ }
588
+ const questions = formQuestions(opened);
589
+ const draft = draftFromFields(questions, (name) => posted.getAll(name));
590
+ // The time the person was first shown the form travels with every redraw, so a quick correction
591
+ // is not taken for a bot and silently dropped (review of PR #461). Only a form that changed is
592
+ // shown afresh, with its new time.
593
+ const postedShown = posted.get("_shown");
594
+ const again = (problem, errors = {}, status, fresh = false) => formPageOf({
595
+ opened: fresh || !postedShown ? opened : { ...opened, shown: postedShown },
596
+ action: isLink ? LINK_PAGE_PATH : `${FORM_PAGE_PREFIX}${slug}`,
597
+ ...(token ? { link: token } : {}),
598
+ draft,
599
+ errors,
600
+ problem,
601
+ turnstileSiteKey: options.turnstileSiteKey ?? null,
602
+ }).then((response) => status ? new Response(response.body, { status, headers: response.headers }) : response);
603
+ const checked = checkDraft(questions, draft);
604
+ if (!checked.ok)
605
+ return again(checked.general, checked.byKey);
606
+ const version = Number(posted.get("_version"));
607
+ const key = posted.get("_key") ?? "";
608
+ const turnstileToken = posted.get("cf-turnstile-response");
609
+ const shown = posted.get("_shown");
610
+ const honeypot = posted.get(HONEYPOT_FIELD);
611
+ try {
612
+ await options.client.call("x.forms.submit", {
613
+ id: opened.id,
614
+ version: Number.isInteger(version) && version > 0 ? version : opened.version,
615
+ answers: checked.answers,
616
+ ...(token ? { link: token } : { via: "page" }),
617
+ ...(!token && shown ? { shown } : {}),
618
+ ...(!token && turnstileToken ? { turnstileToken } : {}),
619
+ ...(honeypot ? { honeypot } : {}),
620
+ }, KEY.test(key) ? { idempotencyKey: key } : {});
621
+ }
622
+ catch (error) {
623
+ const refusal = refusalOf(error, questions);
624
+ if (refusal.kind === "gone")
625
+ return cannotOpen(refusal, isLink);
626
+ return again(refusal.kind === "answers"
627
+ ? null
628
+ : refusal.kind === "reload"
629
+ ? "This form changed since you opened it: check your answers and send them again."
630
+ : refusal.message, refusal.kind === "answers" ? refusal.byKey : {}, statusOf(refusal), refusal.kind === "reload");
631
+ }
632
+ const title = opened.title ?? "Form";
633
+ return page(200, title, `<h1>${esc(title)}</h1>\n<p role="status">${esc(opened.thanks ?? "Thank you. Your answers were sent.")}</p>`);
634
+ }