@tansy/forms 0.0.0-stage → 0.1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ What changed in each release of `@tansy/forms`. Releases up to 0.1.0 went out with every other package
4
+ on one version and are described in [tansy's changelog](../../CHANGELOG.md).
5
+
6
+ ## 0.1.1 — 2026-11-22
7
+
8
+ No changes of its own. Released beside `tansy` 0.1.1, from which every package moves on its own
9
+ version, and it now requires it: the `tansy` peer range is ^0.1.1.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Salah
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @tansy/forms
4
+
5
+ Contact forms and other forms for tansy: built from field blocks, kept as submissions, emailed to you, and guarded against spam.
6
+
7
+ ```bash
8
+ npm install @tansy/forms
9
+ ```
10
+
11
+ Add it to `tansy.config.ts`. See [the forms plugin documentation](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/plugins/forms.md) for what it adds and the options it takes.
12
+
13
+ A first-party plugin for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
package/admin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ declare const _default: import("tansy/admin").AdminPluginParts;
2
+ export default _default;
package/admin.js ADDED
@@ -0,0 +1,36 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Badge, defineAdminPlugin, PageHeader } from "tansy/admin";
3
+ import { getT } from "tansy/server";
4
+ import { FORMS, SUBMISSIONS } from "./schema";
5
+ import { SetupStatus } from "./status";
6
+ /** An envelope with a pencil's line, in the navigation's 16 by 16 box. */
7
+ const FORM_ICON = {
8
+ paths: ["M3 1.5A1.5 1.5 0 0 0 1.5 3v10A1.5 1.5 0 0 0 3 14.5h10a1.5 1.5 0 0 0 1.5-1.5V3A1.5 1.5 0 0 0 13 1.5H3Zm0 1.5h10v10H3V3Zm1.5 1.75a.75.75 0 0 0 0 1.5h7a.75.75 0 0 0 0-1.5h-7Zm0 3a.75.75 0 0 0 0 1.5h7a.75.75 0 0 0 0-1.5h-7Zm0 3a.75.75 0 0 0 0 1.5h4a.75.75 0 0 0 0-1.5h-4Z"],
9
+ fillRule: "evenodd",
10
+ };
11
+ /** As the signed-in person: someone who can't read submissions sees no counts rather than someone else's. */
12
+ async function newCount(records, form) {
13
+ try {
14
+ return (await records.list(SUBMISSIONS, { filter: `form = ${form} && state = "new"`, perPage: 1, fields: "id" })).totalItems;
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ async function Overview({ records, user }) {
21
+ const { t } = await getT(user.id);
22
+ const forms = await records.list(FORMS, { perPage: 200, sort: "title", fields: "id,title,status" }).then((list) => list.items).catch(() => null);
23
+ const counts = forms ? await Promise.all(forms.map((form) => newCount(records, form.id))) : [];
24
+ return (_jsxs("div", { className: "cms-gutter", children: [_jsx(PageHeader, { title: t("ext.forms.pages.forms"), description: t("ext.forms.overview.description") }), _jsx(SetupStatus, {}), !forms ? _jsx("p", { className: "cms-empty", children: t("ext.forms.overview.cantRead") })
25
+ : !forms.length ? _jsx("p", { className: "cms-empty", children: t("ext.forms.overview.empty") })
26
+ : (_jsx("ul", { className: "cms-panel cms-feed", children: forms.map((form, index) => (_jsxs("li", { className: "cms-feed-row", children: [_jsx("span", { className: "cms-feed-main", children: _jsx("span", { className: "cms-feed-title", children: String(form.title ?? "") }) }), form.status !== "published" && _jsx(Badge, { tone: "warning", children: t("ext.forms.overview.draft") }), counts[index] !== null && _jsx(Badge, { tone: counts[index] ? "success" : "info", children: t("ext.forms.overview.new", { count: counts[index] ?? 0 }) })] }, String(form.id)))) }))] }));
27
+ }
28
+ export default defineAdminPlugin({
29
+ // Only for people who may list the forms: the page shows nothing to anyone else.
30
+ pages: [{ path: "forms", title: "Overview", permission: "dashboard:access", collection: FORMS, component: Overview }],
31
+ section: {
32
+ title: "Forms",
33
+ icon: FORM_ICON,
34
+ items: [{ page: "forms" }, { collection: FORMS }, { collection: SUBMISSIONS }, { settings: true }],
35
+ },
36
+ });
package/form.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { type SiteWords } from "tansy/react";
2
+ export interface FormViewProps {
3
+ /** The form's record id, in the forms-forms collection. */
4
+ form: number;
5
+ /** The CMS's API, such as https://cms.example.com/api, for a site on another address. This app's own when left out. */
6
+ api?: string;
7
+ /** The page's words, `pickWords(words, "forms")` from a template or block: the form is read, checked and worded in the page's language. English without them. */
8
+ words?: SiteWords;
9
+ }
10
+ /**
11
+ * A form from the Forms plugin, filled in and sent through its routes. Works on any page,
12
+ * and on a headless site given `api`. Everything it shows comes from the form's public
13
+ * route, and the server checks every answer again.
14
+ */
15
+ export declare function FormView({ form, api, words }: FormViewProps): import("react").JSX.Element | null;
package/form.js ADDED
@@ -0,0 +1,101 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useId, useState } from "react";
4
+ import { apiPath, CaptchaWidget, contentLocale, siteWords } from "tansy/react";
5
+ import { siteMessages } from "./site-messages";
6
+ const ENGLISH = { locale: "en", messages: siteMessages.en };
7
+ function Input({ field, id, value, error, onChange, choose }) {
8
+ const described = [field.help && `${id}-help`, error && `${id}-error`].filter(Boolean).join(" ") || undefined;
9
+ const common = { id, name: field.name, required: field.required, "aria-invalid": error ? true : undefined, "aria-describedby": described };
10
+ const text = typeof value === "string" ? value : "";
11
+ if (field.kind === "checkbox") {
12
+ return (_jsxs("label", { className: "fm-check", children: [_jsx("input", { type: "checkbox", ...common, checked: value === true, onChange: (event) => onChange(event.target.checked) }), _jsx("span", { children: field.label })] }));
13
+ }
14
+ if (field.kind === "textarea")
15
+ return _jsx("textarea", { ...common, rows: 5, maxLength: field.maxLength, placeholder: field.placeholder || undefined, value: text, onChange: (event) => onChange(event.target.value) });
16
+ if (field.kind === "select") {
17
+ return (_jsxs("select", { ...common, value: text, onChange: (event) => onChange(event.target.value), children: [_jsx("option", { value: "", children: field.placeholder || choose }), field.options?.map((option) => _jsx("option", { value: option, children: option }, option))] }));
18
+ }
19
+ const type = field.kind === "email" ? "email" : field.kind === "number" ? "number" : "text";
20
+ return _jsx("input", { ...common, type: type, min: field.min, max: field.max, maxLength: field.maxLength, placeholder: field.placeholder || undefined, autoComplete: field.kind === "email" ? "email" : field.name === "name" ? "name" : undefined, value: text, onChange: (event) => onChange(event.target.value) });
21
+ }
22
+ /**
23
+ * A form from the Forms plugin, filled in and sent through its routes. Works on any page,
24
+ * and on a headless site given `api`. Everything it shows comes from the form's public
25
+ * route, and the server checks every answer again.
26
+ */
27
+ export function FormView({ form, api, words }) {
28
+ const { t } = siteWords(words ?? ENGLISH);
29
+ const locale = contentLocale(words);
30
+ const base = (api ?? apiPath("")).replace(/\/+$/, "");
31
+ const id = useId();
32
+ const [loaded, setLoaded] = useState(null);
33
+ const [missing, setMissing] = useState(false);
34
+ const [values, setValues] = useState({});
35
+ const [trap, setTrap] = useState("");
36
+ const [answer, setAnswer] = useState(null);
37
+ const [attempt, setAttempt] = useState(0);
38
+ const [errors, setErrors] = useState({});
39
+ const [problem, setProblem] = useState(null);
40
+ const [sent, setSent] = useState(null);
41
+ const [sending, setSending] = useState(false);
42
+ // Raised to fetch the form again, for a fresh token once it has expired.
43
+ const [version, setVersion] = useState(0);
44
+ useEffect(() => {
45
+ let active = true;
46
+ fetch(`${base}/ext/forms/forms/${form}${locale ? `?locale=${encodeURIComponent(locale)}` : ""}`, { cache: "no-store" })
47
+ .then(async (response) => {
48
+ if (!active)
49
+ return;
50
+ if (!response.ok)
51
+ return setMissing(true);
52
+ setLoaded(await response.json());
53
+ })
54
+ .catch(() => { if (active)
55
+ setMissing(true); });
56
+ return () => { active = false; };
57
+ }, [base, form, version, locale]);
58
+ if (missing)
59
+ return null;
60
+ if (!loaded)
61
+ return _jsx("div", { className: "fm-form fm-loading", "aria-busy": "true" });
62
+ if (sent !== null)
63
+ return _jsx("p", { className: "fm-success", role: "status", children: sent });
64
+ async function submit(event) {
65
+ event.preventDefault();
66
+ if (!loaded)
67
+ return;
68
+ setSending(true);
69
+ setProblem(null);
70
+ setErrors({});
71
+ try {
72
+ const response = await fetch(`${base}/ext/forms/forms/${form}/submit`, {
73
+ method: "POST",
74
+ headers: { "content-type": "application/json" },
75
+ body: JSON.stringify({ values, token: loaded.token, page: window.location.pathname, website: trap, ...(answer ? { answer } : {}), ...(locale ? { locale } : {}) }),
76
+ });
77
+ const json = await response.json().catch(() => null);
78
+ // The route words its answers in the page's language.
79
+ if (response.ok)
80
+ return setSent(json?.message ?? t("forms.thanks"));
81
+ setProblem(response.status === 429 ? t("forms.tooMany") : json?.error?.message ?? t("forms.failed"));
82
+ if (json?.fields)
83
+ setErrors(json.fields);
84
+ if (json?.error?.code === "FORM_EXPIRED")
85
+ setVersion((value) => value + 1);
86
+ // An answer works once, so a new one is needed after any refusal the CAPTCHA saw.
87
+ if (loaded.captcha)
88
+ setAttempt((value) => value + 1);
89
+ }
90
+ catch {
91
+ setProblem(t("forms.offline"));
92
+ }
93
+ finally {
94
+ setSending(false);
95
+ }
96
+ }
97
+ return (_jsxs("form", { className: "fm-form", onSubmit: submit, noValidate: false, children: [loaded.fields.map((field) => {
98
+ const fieldId = `${id}-${field.name}`;
99
+ return (_jsxs("div", { className: "fm-field", children: [field.kind !== "checkbox" && _jsxs("label", { htmlFor: fieldId, children: [field.label, field.required && _jsx("span", { "aria-hidden": true, children: " *" })] }), _jsx(Input, { field: field, id: fieldId, value: values[field.name], error: errors[field.name], onChange: (value) => setValues((current) => ({ ...current, [field.name]: value })), choose: t("forms.choose") }), field.help && _jsx("p", { id: `${fieldId}-help`, className: "fm-help", children: field.help }), errors[field.name] && _jsx("p", { id: `${fieldId}-error`, className: "fm-error", children: errors[field.name] })] }, field.name));
100
+ }), _jsxs("div", { className: "fm-trap", "aria-hidden": "true", children: [_jsx("label", { htmlFor: `${id}-website`, children: t("forms.trap") }), _jsx("input", { id: `${id}-website`, name: "website", tabIndex: -1, autoComplete: "off", value: trap, onChange: (event) => setTrap(event.target.value) })] }), loaded.captcha && _jsx(CaptchaWidget, { config: loaded.captcha, attempt: attempt, onAnswer: setAnswer }), problem && _jsx("p", { className: "fm-error", role: "alert", children: problem }), _jsx("p", { className: "fm-actions", children: _jsx("button", { type: "submit", disabled: sending || (loaded.captcha !== null && !answer), children: sending ? t("forms.sending") : loaded.submitLabel }) })] }));
101
+ }
package/forms.css ADDED
@@ -0,0 +1,35 @@
1
+ /* Forms on the public site. Colours, fonts and radii come from the active theme's --site-* tokens, with plain fallbacks. */
2
+ .fm-page {
3
+ max-width: var(--site-size-measure, 42rem);
4
+ margin: 0 auto;
5
+ padding: var(--site-space-section, 3rem) 1rem;
6
+ color: var(--site-color-text, inherit);
7
+ font-family: var(--site-font-body, inherit);
8
+ }
9
+ .fm-page h1 { font-size: 2.25rem; line-height: 1.2; margin: 0 0 1.5rem; }
10
+ .fm-form { display: grid; gap: 1rem; max-width: 36rem; }
11
+ .fm-loading { min-height: 12rem; }
12
+ .fm-field { display: grid; gap: 0.375rem; }
13
+ .fm-field > label { font-weight: 600; }
14
+ .fm-form input:not([type="checkbox"]), .fm-form textarea, .fm-form select {
15
+ font: inherit;
16
+ padding: 0.5rem 0.625rem;
17
+ border: 1px solid var(--site-color-border, #ccc);
18
+ border-radius: var(--site-radius-control, 0.375rem);
19
+ background: transparent;
20
+ color: inherit;
21
+ width: 100%;
22
+ box-sizing: border-box;
23
+ }
24
+ .fm-form [aria-invalid="true"] { border-color: #c53030; }
25
+ .fm-check { display: flex; gap: 0.5rem; align-items: flex-start; }
26
+ .fm-check input { margin-top: 0.3rem; }
27
+ .fm-help { margin: 0; font-size: 0.875rem; color: var(--site-color-muted, #666); }
28
+ .fm-error { margin: 0; color: #c53030; font-size: 0.875rem; }
29
+ .fm-success { padding: 0.75rem 1rem; border-radius: var(--site-radius-card, 0.5rem); border: 1px solid var(--site-color-border, #ddd); }
30
+ .fm-actions { margin: 0; }
31
+ .fm-form button { font: inherit; padding: 0.5rem 1.25rem; border-radius: var(--site-radius-control, 0.375rem); border: 0; background: var(--site-color-accent, #222); color: var(--site-color-on-accent, #fff); cursor: pointer; }
32
+ .fm-form button:disabled { opacity: 0.6; cursor: default; }
33
+ /* Off screen rather than display: none, which some scripts know to skip. */
34
+ .fm-trap { position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden; }
35
+ .fm-preview { pointer-events: none; }
package/index.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export { fieldsOf, type FormField } from "./logic";
2
+ export interface FormsOptions {
3
+ /** Who gets each submission, separated by commas, until changed under Forms → Settings. A form can name its own. */
4
+ notify?: string;
5
+ }
6
+ /**
7
+ * Forms visitors fill in, such as a contact form: built from field blocks, put on any page
8
+ * with the Form block, kept as submissions only staff read, and emailed to whoever the form
9
+ * names. Spam is kept out by a trap field, a minimum time to fill in, a rate limit per
10
+ * address and, once one is set up, the site's CAPTCHA. See docs/plugins/forms.md.
11
+ */
12
+ export declare function forms(options?: FormsOptions): import("tansy/plugin").CmsPlugin;
package/index.js ADDED
@@ -0,0 +1,233 @@
1
+ import { z } from "zod";
2
+ import { definePlugin, defineRoute, wordsIn } from "tansy/plugin";
3
+ import { check, duplicateNames, fieldsOf, issueToken, newKey, notification, pageOf, recipients, tokenProblem } from "./logic";
4
+ import { COLLECTIONS, CONTRACT, FIELD_BLOCKS, FORMS, formsSchema, SUBMISSIONS } from "./schema";
5
+ import { BLOCK_FIELD_LABELS, COLLECTION_LABELS, FIELD_LABELS, messages } from "./messages";
6
+ import { siteMessages } from "./site-messages";
7
+ export { fieldsOf } from "./logic";
8
+ const optionsSchema = z.strictObject({ notify: z.string().max(1000) });
9
+ const settingsOf = async (context) => (await context.settings.get());
10
+ const idOf = (value) => {
11
+ const id = typeof value === "string" && /^\d{1,15}$/.test(value) ? Number(value) : value;
12
+ return typeof id === "number" && Number.isSafeInteger(id) && id > 0 ? id : null;
13
+ };
14
+ const str = (value) => (typeof value === "string" ? value : "");
15
+ const refuse = (status, code, message, extra = {}) => Response.json({ error: { code, message }, ...extra }, { status });
16
+ /** The key that signs forms' tokens, made once and kept in the plugin's store. Of two first requests, one key wins. */
17
+ async function signingKey(context) {
18
+ const existing = await context.store.get("signing-key");
19
+ if (typeof existing === "string")
20
+ return existing;
21
+ await context.store.claim("signing-key", newKey());
22
+ return String(await context.store.get("signing-key"));
23
+ }
24
+ /**
25
+ * The visitor's language, from `locale`, when the site is published in more than one: the
26
+ * form is read in it and its answers checked in it. Otherwise the default language, in English words.
27
+ */
28
+ async function visitorLanguage(context, asked) {
29
+ const languages = await context.schema.languages();
30
+ const locale = asked && languages.items.length > 1 && languages.items.some((item) => item.code === asked) ? asked : null;
31
+ return { read: locale ? { locale } : {}, t: wordsIn(siteMessages, locale ?? "en").t };
32
+ }
33
+ /** The form as the caller may see it, in their language: published, unless they're staff who can read drafts. Null when they can't. */
34
+ async function readForm(context, id, read = {}) {
35
+ return context.records.get(FORMS, id, read).catch(() => null);
36
+ }
37
+ const FORM_REASON = "Visitors fill in forms signed out. It serves only a form the collection's view rule shows the caller, without its hidden fields.";
38
+ const SUBMIT_REASON = "Visitors send forms signed out. It accepts only a form the view rule shows them, checks every answer against the form, and is rate limited per address.";
39
+ const submitBody = z.strictObject({
40
+ values: z.record(z.string().max(40), z.union([z.string().max(10_000), z.number(), z.boolean(), z.null()])).refine((values) => Object.keys(values).length <= 60, "Too many answers."),
41
+ token: z.string().max(200),
42
+ answer: z.string().max(4096).optional(),
43
+ /** The trap: a field people never see. Anything in it is a script. */
44
+ website: z.string().max(2000).optional(),
45
+ page: z.string().max(2000).optional(),
46
+ /** The page's language, on a site with more than one. */
47
+ locale: z.string().min(2).max(35).optional(),
48
+ });
49
+ /** Before a form is saved: every field's name is its own, and the addresses to notify are addresses. */
50
+ function checkForm(context) {
51
+ const { values, reject } = context;
52
+ if (Object.hasOwn(values, "fields")) {
53
+ const twice = duplicateNames(values.fields);
54
+ if (twice.length)
55
+ reject(`Two fields are named "${twice[0]}". Give each field its own name.`, "fields");
56
+ }
57
+ if (Object.hasOwn(values, "notify") && str(values.notify).trim()) {
58
+ const given = str(values.notify).split(/[,;\s]+/).filter(Boolean);
59
+ if (recipients(values.notify, "").length !== given.length)
60
+ reject("List email addresses separated by commas.", "notify");
61
+ }
62
+ }
63
+ /** Tells whoever the form names, replying to the visitor. A failed delivery is only logged by core, and the submission is already saved. */
64
+ async function announce(context) {
65
+ const { record, system, mail } = context;
66
+ if (record.state === "spam")
67
+ return;
68
+ const formId = idOf(record.form);
69
+ const form = formId === null ? null : await system.records.get(FORMS, formId).catch(() => null);
70
+ if (!form)
71
+ return;
72
+ const to = recipients(form.notify, (await settingsOf(context)).notify);
73
+ if (!to.length)
74
+ return;
75
+ const data = record.data && typeof record.data === "object" ? record.data : {};
76
+ const replyTo = typeof record.email === "string" && record.email ? record.email : undefined;
77
+ for (const address of to) {
78
+ // In the language of the person it goes to, when they have an account, else the site's default.
79
+ const locale = (await system.users.findByEmail(address))?.locale ?? (await context.schema.languages()).defaultLocale;
80
+ const { subject, body } = notification(str(form.title), fieldsOf(form.fields), data, str(record.page), wordsIn(siteMessages, locale).t);
81
+ await mail.send({ to: address, locale, subject, body, ...(replyTo ? { replyTo } : {}) });
82
+ }
83
+ }
84
+ /** Removes submissions older than the setting, a page at a time. Nothing when it's 0. */
85
+ async function forgetOldSubmissions(context) {
86
+ const days = (await settingsOf(context)).keepDays;
87
+ if (!Number.isInteger(days) || days < 1)
88
+ return;
89
+ const before = new Date(Date.now() - days * 86_400_000).toISOString();
90
+ for (let round = 0; round < 50; round++) {
91
+ const { items } = await context.system.records.list(SUBMISSIONS, { filter: `createdAt < "${before}"`, perPage: 200, fields: "id" });
92
+ if (!items.length)
93
+ return;
94
+ for (const { id } of items)
95
+ await context.system.records.delete(SUBMISSIONS, id);
96
+ }
97
+ }
98
+ /**
99
+ * Forms visitors fill in, such as a contact form: built from field blocks, put on any page
100
+ * with the Form block, kept as submissions only staff read, and emailed to whoever the form
101
+ * names. Spam is kept out by a trap field, a minimum time to fill in, a rate limit per
102
+ * address and, once one is set up, the site's CAPTCHA. See docs/plugins/forms.md.
103
+ */
104
+ export function forms(options = {}) {
105
+ const value = optionsSchema.parse({ notify: "", ...Object.fromEntries(Object.entries(options).filter(([, option]) => option !== undefined)) });
106
+ return definePlugin({
107
+ name: "forms",
108
+ messages,
109
+ version: "0.1.1",
110
+ apiVersion: 1,
111
+ requires: { cms: "^0.1.1" },
112
+ admin: { server: "@tansy/forms/admin", render: "@tansy/forms/render" },
113
+ options: { schema: optionsSchema, value },
114
+ settings: {
115
+ fields: [
116
+ { name: "notify", type: "text", perScope: true, default: value.notify, maxLength: 1000, label: "Email submissions to", description: "Addresses separated by commas, for forms that don't name their own. Empty sends no email: submissions are still kept." },
117
+ { name: "minSeconds", type: "number", perScope: true, integer: true, min: 0, max: 60, default: 3, label: "Fastest a person fills in a form (seconds)", description: "Anything sent sooner after the form loaded is refused as a script. 0 turns this off." },
118
+ { name: "keepDays", type: "number", perScope: true, integer: true, min: 0, max: 3650, default: 0, label: "Delete submissions after (days)", description: "0 keeps them until someone deletes them." },
119
+ ],
120
+ },
121
+ contract: CONTRACT,
122
+ blocks: FIELD_BLOCKS,
123
+ hooks: {
124
+ "record.beforeCreate": (context) => { if (context.collection.slug === FORMS)
125
+ checkForm(context); },
126
+ "record.beforeUpdate": (context) => { if (context.collection.slug === FORMS)
127
+ checkForm(context); },
128
+ "record.afterCreate": async (context) => { if (context.collection.slug === SUBMISSIONS)
129
+ await announce(context); },
130
+ },
131
+ routes: [
132
+ defineRoute({
133
+ method: "GET",
134
+ path: "/forms/:id",
135
+ access: "public",
136
+ reason: FORM_REASON,
137
+ handler: async (context) => {
138
+ const id = idOf(context.params.id);
139
+ const { read, t } = await visitorLanguage(context, new URL(context.request.url).searchParams.get("locale"));
140
+ const form = id === null ? null : await readForm(context, id, read);
141
+ if (!form || id === null)
142
+ return refuse(404, "NOT_FOUND", t("forms.refusals.notFound"));
143
+ const captcha = form.captcha === false ? null : await context.captcha.widget();
144
+ return Response.json({
145
+ id,
146
+ title: str(form.title),
147
+ fields: fieldsOf(form.fields),
148
+ submitLabel: str(form.submitLabel).trim() || t("forms.send"),
149
+ captcha,
150
+ token: await issueToken(await signingKey(context), id),
151
+ }, { headers: { "cache-control": "no-store" } });
152
+ },
153
+ }),
154
+ defineRoute({
155
+ method: "POST",
156
+ path: "/forms/:id/submit",
157
+ access: "public",
158
+ reason: SUBMIT_REASON,
159
+ audit: "forms.submit",
160
+ body: submitBody,
161
+ // Per address and form: a person sends one now and then, a script hundreds.
162
+ rateLimit: { window: 600, max: 5 },
163
+ handler: async (context) => {
164
+ const body = context.body;
165
+ const id = idOf(context.params.id);
166
+ const { read, t } = await visitorLanguage(context, body.locale);
167
+ const form = id === null ? null : await readForm(context, id, read);
168
+ if (!form || id === null)
169
+ return refuse(404, "NOT_FOUND", t("forms.refusals.notFound"));
170
+ const thanks = { ok: true, message: str(form.successMessage).trim() || t("forms.thanks") };
171
+ // Answer a filled trap as if it worked, so the script learns nothing. Nothing is kept.
172
+ if (body.website?.trim())
173
+ return thanks;
174
+ const settings = await settingsOf(context);
175
+ const timing = await tokenProblem(await signingKey(context), id, body.token, settings.minSeconds);
176
+ if (timing === "early")
177
+ return refuse(400, "TOO_FAST", t("forms.refusals.tooFast"));
178
+ if (timing !== "ok")
179
+ return refuse(400, "FORM_EXPIRED", t("forms.refusals.expired"));
180
+ const fields = fieldsOf(form.fields);
181
+ const { data, errors, replyTo } = check(fields, body.values, t);
182
+ if (Object.keys(errors).length)
183
+ return refuse(400, "INVALID_ANSWERS", t("forms.refusals.invalid"), { fields: errors });
184
+ if (!fields.length)
185
+ return refuse(400, "NO_FIELDS", t("forms.refusals.noFields"));
186
+ // After the answers are checked, as a CAPTCHA's answer works only once.
187
+ if (form.captcha !== false && (await context.captcha.widget())) {
188
+ if (!body.answer)
189
+ return refuse(400, "CAPTCHA_REQUIRED", t("forms.refusals.captchaRequired"));
190
+ if (!(await context.captcha.verify(body.answer, { ip: context.ip })))
191
+ return refuse(403, "CAPTCHA_FAILED", t("forms.refusals.captchaFailed"));
192
+ }
193
+ const submission = await context.system.records.create(SUBMISSIONS, { form: id, data, email: replyTo, page: pageOf(body.page) || null, state: "new" });
194
+ context.auditTarget(SUBMISSIONS, String(submission.id), { form: id });
195
+ return thanks;
196
+ },
197
+ }),
198
+ defineRoute({
199
+ method: "GET",
200
+ path: "/status",
201
+ access: "permission",
202
+ permission: "dashboard:access",
203
+ handler: async ({ mail, captcha }) => ({ mail: await mail.ready(), captcha: (await captcha.widget()) !== null }),
204
+ }),
205
+ ],
206
+ // Each tenant keeps submissions as long as its own setting says.
207
+ jobs: [{ name: "forms-forget-submissions", cron: "41 3 * * *", perScope: true, handler: forgetOldSubmissions }],
208
+ migrations: [{
209
+ id: "001-collections",
210
+ up: async ({ schema }) => {
211
+ for (const slug of COLLECTIONS) {
212
+ if (await schema.describe(slug))
213
+ throw new Error(`A collection called "${slug}" already exists, and the forms plugin didn't create it. Rename it under Dashboard → Collections, then start again.`);
214
+ }
215
+ await schema.apply(formsSchema());
216
+ },
217
+ }, {
218
+ id: "002-names-in-languages",
219
+ up: async ({ schema }) => {
220
+ for (const [slug, labels] of Object.entries(COLLECTION_LABELS))
221
+ await schema.addLabels(slug, labels);
222
+ },
223
+ }, {
224
+ id: "003-field-names-in-languages",
225
+ up: async ({ schema }) => {
226
+ for (const [slug, fields] of Object.entries(FIELD_LABELS))
227
+ await schema.addFieldLabels(slug, fields);
228
+ for (const [block, fields] of Object.entries(BLOCK_FIELD_LABELS))
229
+ await schema.addBlockFieldLabels(block, fields);
230
+ },
231
+ }],
232
+ });
233
+ }
package/logic.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ /** What Forms does with a form's fields and a visitor's answers. No server imports, so it's easy to test. */
2
+ export type FieldKind = "text" | "email" | "textarea" | "select" | "checkbox" | "number";
3
+ /** One field, as the browser gets it. Everything here is public. */
4
+ export interface FormField {
5
+ kind: FieldKind;
6
+ name: string;
7
+ label: string;
8
+ required: boolean;
9
+ help: string;
10
+ placeholder: string;
11
+ maxLength?: number;
12
+ options?: string[];
13
+ min?: number;
14
+ max?: number;
15
+ }
16
+ /** The most fields one form takes, so a submission's size stays bounded. */
17
+ export declare const MAX_FIELDS = 50;
18
+ /** One line of plain text: no control characters, so nothing can become a header or break a layout. */
19
+ export declare const oneLine: (value: string) => string;
20
+ /**
21
+ * A form's fields from its `fields` stream. Blocks of other types are skipped, and so is a
22
+ * second field with a name already used: the first one wins, as the owner was told when saving.
23
+ */
24
+ export declare function fieldsOf(stream: unknown): FormField[];
25
+ /** Names used by more than one field, for the owner to fix before saving. */
26
+ export declare function duplicateNames(stream: unknown): string[];
27
+ export declare const isAddress: (value: string) => boolean;
28
+ export type Answer = string | number | boolean;
29
+ export interface Checked {
30
+ /** The answers to keep, by field name. Empty optional fields are left out. */
31
+ data: Record<string, Answer>;
32
+ /** By field name, what to fix. */
33
+ errors: Record<string, string>;
34
+ /** The first email field's answer, for replies. */
35
+ replyTo: string | null;
36
+ }
37
+ /** Words by key under `forms`, such as the visitor's from the page, or English. */
38
+ export type Words = (key: string, values?: Record<string, string | number>) => string;
39
+ /**
40
+ * Checks answers against the form's own fields, the way the browser should have. Problems are
41
+ * worded with `t`, in the visitor's language when the route knows it. Anything
42
+ * the form doesn't ask is dropped, so a submission can only hold what the owner asked for.
43
+ */
44
+ export declare function check(fields: FormField[], values: Record<string, unknown>, t?: Words): Checked;
45
+ /** The addresses to notify: the form's own, else the settings'. At most ten, each checked. */
46
+ export declare function recipients(own: unknown, fallback: unknown): string[];
47
+ /** The email the owner gets: each question and answer, plain text, with nothing that could become markup or a link. Worded with `t`, in the owner's language. */
48
+ export declare function notification(title: string, fields: FormField[], data: Record<string, unknown>, page: string, t?: Words): {
49
+ subject: string;
50
+ body: string;
51
+ };
52
+ /** Only a site path, such as /contact, so a submission can't carry a link to somewhere else. */
53
+ export declare const pageOf: (value: unknown) => string;
54
+ /** When the form was handed out, signed, so a script can't claim it waited. */
55
+ export declare function issueToken(key: string, formId: number, now?: number): Promise<string>;
56
+ /** "ok", or why the token doesn't do: not signed by us for this form, too fresh, or a day old. */
57
+ export declare function tokenProblem(key: string, formId: number, token: unknown, minSeconds: number, now?: number): Promise<"ok" | "invalid" | "early" | "expired">;
58
+ /** A new signing key: 32 random bytes. */
59
+ export declare const newKey: () => string;