payload-canvas 0.5.1 → 0.6.0

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 (194) hide show
  1. package/README.md +333 -28
  2. package/dist/admin/ArrayRowLabel.d.ts +12 -0
  3. package/dist/admin/ArrayRowLabel.js +21 -0
  4. package/dist/admin/DocumentEditView.js +9 -2
  5. package/dist/admin/client.d.ts +1 -0
  6. package/dist/admin/client.js +2 -0
  7. package/dist/admin/editor/Editor.js +8 -1
  8. package/dist/admin/editor/Inspector.js +23 -17
  9. package/dist/admin/editor/Library.d.ts +2 -2
  10. package/dist/admin/editor/Library.js +7 -5
  11. package/dist/admin/editor/Outline.js +20 -12
  12. package/dist/admin/editor/Overlay.js +6 -4
  13. package/dist/admin/editor/actions.d.ts +7 -2
  14. package/dist/admin/editor/actions.js +44 -12
  15. package/dist/admin/editor/assistant/AssistantPanel.js +32 -20
  16. package/dist/admin/editor/comments/controller.d.ts +7 -0
  17. package/dist/admin/editor/comments/controller.js +12 -0
  18. package/dist/admin/editor/comments/useCommentFromURL.d.ts +2 -0
  19. package/dist/admin/editor/comments/useCommentFromURL.js +36 -0
  20. package/dist/admin/editor/dnd/smooth.js +1 -1
  21. package/dist/admin/editor/editor.scss +28 -0
  22. package/dist/admin/editor/fields/ArrayField.js +3 -3
  23. package/dist/admin/editor/fields/FormBlock.d.ts +20 -0
  24. package/dist/admin/editor/fields/FormBlock.js +167 -0
  25. package/dist/admin/editor/fields/FormFieldName.d.ts +25 -0
  26. package/dist/admin/editor/fields/FormFieldName.js +58 -0
  27. package/dist/admin/editor/fields/GroupField.d.ts +22 -2
  28. package/dist/admin/editor/fields/GroupField.js +30 -1
  29. package/dist/admin/editor/fields/MergeTags.d.ts +8 -0
  30. package/dist/admin/editor/fields/MergeTags.js +62 -0
  31. package/dist/admin/editor/fields/arrayRows.d.ts +0 -2
  32. package/dist/admin/editor/fields/arrayRows.js +0 -4
  33. package/dist/admin/editor/fields/fields.scss +150 -0
  34. package/dist/admin/editor/fields/values.d.ts +0 -2
  35. package/dist/admin/editor/fields/values.js +0 -14
  36. package/dist/admin/editor/icons.d.ts +3 -0
  37. package/dist/admin/editor/icons.js +3 -0
  38. package/dist/admin/editor/insert/InsertHandle.js +1 -1
  39. package/dist/admin/editor/insert/picker.d.ts +3 -2
  40. package/dist/admin/editor/insert/picker.js +9 -3
  41. package/dist/admin/editor/layout/LeftPanel.js +5 -3
  42. package/dist/admin/editor/layout/leftTabs.d.ts +15 -0
  43. package/dist/admin/editor/layout/leftTabs.js +18 -0
  44. package/dist/admin/editor/media/ImageEditor.d.ts +8 -2
  45. package/dist/admin/editor/media/ImageEditor.js +16 -10
  46. package/dist/admin/editor/media/media.scss +12 -2
  47. package/dist/admin/editor/media/model.d.ts +10 -1
  48. package/dist/admin/editor/media/model.js +19 -0
  49. package/dist/admin/editor/menu/blockMenu.js +3 -3
  50. package/dist/admin/editor/names.d.ts +9 -0
  51. package/dist/admin/editor/names.js +18 -0
  52. package/dist/admin/editor/regions/RegionFields.d.ts +6 -0
  53. package/dist/admin/editor/regions/RegionFields.js +122 -0
  54. package/dist/admin/editor/regions/RegionPane.js +5 -3
  55. package/dist/admin/editor/regions/RegionRows.js +2 -2
  56. package/dist/admin/editor/regions/required.d.ts +16 -0
  57. package/dist/admin/editor/regions/required.js +43 -0
  58. package/dist/admin/editor/renderField.d.ts +9 -2
  59. package/dist/admin/editor/renderField.js +86 -32
  60. package/dist/admin/editor/runtime.d.ts +3 -2
  61. package/dist/admin/editor/runtime.js +12 -18
  62. package/dist/admin/editor/styles/StylesPanel.js +4 -2
  63. package/dist/admin/editor/styles/context.js +9 -4
  64. package/dist/admin/editor/topbar/ContentModeToggle.js +1 -1
  65. package/dist/admin/editor/topbar/DocumentActions.js +4 -3
  66. package/dist/admin/editor/topbar/contentMode.scss +0 -9
  67. package/dist/admin/editor/topbar/topbar.scss +1 -41
  68. package/dist/admin/editor/ui/Tabs.d.ts +17 -0
  69. package/dist/admin/editor/ui/Tabs.js +17 -0
  70. package/dist/admin/forms/SubmissionCells.d.ts +6 -0
  71. package/dist/admin/forms/SubmissionCells.js +31 -0
  72. package/dist/admin/forms/SubmissionView.d.ts +5 -0
  73. package/dist/admin/forms/SubmissionView.js +106 -0
  74. package/dist/admin/forms/submissionData.d.ts +32 -0
  75. package/dist/admin/forms/submissionData.js +63 -0
  76. package/dist/admin/forms/submissions.scss +197 -0
  77. package/dist/admin/rsc.d.ts +2 -0
  78. package/dist/admin/rsc.js +5 -0
  79. package/dist/ai/endpoint.d.ts +5 -0
  80. package/dist/ai/endpoint.js +18 -8
  81. package/dist/ai/prompt.d.ts +8 -0
  82. package/dist/ai/prompt.js +30 -0
  83. package/dist/ai/tools.d.ts +6 -1
  84. package/dist/ai/tools.js +90 -6
  85. package/dist/blocks/builtins/carousel.js +10 -1
  86. package/dist/blocks/index.d.ts +1 -1
  87. package/dist/blocks/index.js +1 -1
  88. package/dist/blocks/payload.d.ts +7 -0
  89. package/dist/blocks/payload.js +16 -2
  90. package/dist/comments/shared.d.ts +5 -0
  91. package/dist/comments/shared.js +5 -0
  92. package/dist/core/blocks.d.ts +17 -3
  93. package/dist/core/blocks.js +92 -10
  94. package/dist/core/classes.d.ts +5 -0
  95. package/dist/core/classes.js +26 -1
  96. package/dist/core/conditions.d.ts +7 -0
  97. package/dist/core/conditions.js +22 -0
  98. package/dist/core/dropTarget.d.ts +3 -2
  99. package/dist/core/dropTarget.js +7 -1
  100. package/dist/core/index.d.ts +6 -3
  101. package/dist/core/index.js +6 -3
  102. package/dist/core/payloadBlocks.js +25 -3
  103. package/dist/core/references.d.ts +7 -0
  104. package/dist/core/references.js +29 -11
  105. package/dist/core/regions.d.ts +14 -0
  106. package/dist/core/regions.js +17 -1
  107. package/dist/core/rowLabel.d.ts +8 -0
  108. package/dist/core/rowLabel.js +98 -0
  109. package/dist/core/starter.d.ts +10 -0
  110. package/dist/core/starter.js +40 -0
  111. package/dist/core/tree.js +4 -0
  112. package/dist/core/types.d.ts +96 -0
  113. package/dist/core/uniqueProps.d.ts +40 -0
  114. package/dist/core/uniqueProps.js +156 -0
  115. package/dist/core/validate.js +43 -3
  116. package/dist/forms/answers.d.ts +21 -0
  117. package/dist/forms/answers.js +82 -0
  118. package/dist/forms/blocks.d.ts +33 -0
  119. package/dist/forms/blocks.js +178 -0
  120. package/dist/forms/conditions.d.ts +78 -0
  121. package/dist/forms/conditions.js +184 -0
  122. package/dist/forms/emails.d.ts +23 -0
  123. package/dist/forms/emails.js +64 -0
  124. package/dist/forms/fieldConfigs.d.ts +35 -0
  125. package/dist/forms/fieldConfigs.js +167 -0
  126. package/dist/forms/fieldOps.d.ts +78 -0
  127. package/dist/forms/fieldOps.js +378 -0
  128. package/dist/forms/fieldSettings.d.ts +81 -0
  129. package/dist/forms/fieldSettings.js +239 -0
  130. package/dist/forms/files.d.ts +54 -0
  131. package/dist/forms/files.js +128 -0
  132. package/dist/forms/index.d.ts +16 -0
  133. package/dist/forms/index.js +18 -0
  134. package/dist/forms/mergeTags.d.ts +103 -0
  135. package/dist/forms/mergeTags.js +150 -0
  136. package/dist/forms/noScript.d.ts +60 -0
  137. package/dist/forms/noScript.js +109 -0
  138. package/dist/forms/pageForms.d.ts +99 -0
  139. package/dist/forms/pageForms.js +294 -0
  140. package/dist/forms/pageSync.d.ts +91 -0
  141. package/dist/forms/pageSync.js +325 -0
  142. package/dist/forms/rateLimit.d.ts +21 -0
  143. package/dist/forms/rateLimit.js +50 -0
  144. package/dist/forms/settings.d.ts +13 -0
  145. package/dist/forms/settings.js +92 -0
  146. package/dist/forms/spam.d.ts +100 -0
  147. package/dist/forms/spam.js +218 -0
  148. package/dist/forms/spamSettings.d.ts +43 -0
  149. package/dist/forms/spamSettings.js +25 -0
  150. package/dist/forms/submission.d.ts +34 -0
  151. package/dist/forms/submission.js +89 -0
  152. package/dist/forms/submissionsAdmin.d.ts +26 -0
  153. package/dist/forms/submissionsAdmin.js +108 -0
  154. package/dist/forms/summary.d.ts +60 -0
  155. package/dist/forms/summary.js +113 -0
  156. package/dist/forms/uploads.d.ts +41 -0
  157. package/dist/forms/uploads.js +132 -0
  158. package/dist/index.d.ts +8 -2
  159. package/dist/index.js +8 -2
  160. package/dist/live/document.d.ts +12 -0
  161. package/dist/live/document.js +8 -1
  162. package/dist/live/endpoints.d.ts +1 -0
  163. package/dist/live/session.js +3 -1
  164. package/dist/live/storage.d.ts +13 -2
  165. package/dist/live/storage.js +18 -7
  166. package/dist/mcp/forms.d.ts +26 -0
  167. package/dist/mcp/forms.js +280 -0
  168. package/dist/mcp/index.d.ts +7 -0
  169. package/dist/mcp/index.js +29 -10
  170. package/dist/mcp/shared.d.ts +1 -0
  171. package/dist/mcp/shared.js +1 -0
  172. package/dist/plugin/forms.d.ts +30 -0
  173. package/dist/plugin/forms.js +63 -0
  174. package/dist/plugin/formsSync.d.ts +138 -0
  175. package/dist/plugin/formsSync.js +345 -0
  176. package/dist/plugin/hook.d.ts +22 -0
  177. package/dist/plugin/hook.js +19 -7
  178. package/dist/plugin/index.d.ts +14 -0
  179. package/dist/plugin/index.js +99 -28
  180. package/dist/plugin/links.d.ts +21 -2
  181. package/dist/plugin/links.js +32 -3
  182. package/dist/plugin/references.d.ts +6 -0
  183. package/dist/plugin/references.js +12 -0
  184. package/dist/react/canvas/BuilderCanvas.d.ts +2 -0
  185. package/dist/react/canvas/BuilderCanvas.js +29 -6
  186. package/dist/react/canvas/inline/mapper.d.ts +6 -1
  187. package/dist/react/canvas/inline/mapper.js +35 -4
  188. package/dist/react/render/LayoutOutlet.d.ts +7 -3
  189. package/dist/react/render/LayoutOutlet.js +9 -4
  190. package/dist/react/render/RenderLayout.js +13 -7
  191. package/dist/react/render/resolve.d.ts +1 -0
  192. package/dist/react/render/resolve.js +5 -1
  193. package/dist/react/server.js +19 -0
  194. package/package.json +5 -1
@@ -0,0 +1,218 @@
1
+ // Spam protection for the forms of `@payloadcms/plugin-form-builder`, set per form:
2
+ // - `spamProtectionField()`: the `spamProtection` group for the forms collection (`formOverrides`).
3
+ // - `formSpamProtection()`: a submissions `beforeValidate` hook that checks every submission on the
4
+ // server (honeypot, minimum fill time, Cloudflare Turnstile, a rate limit per IP and form; the IP
5
+ // comes from a proxy header only when `trustedIpHeader` names it). A
6
+ // blocked submission is logged and refused with one generic message, so nothing is stored.
7
+ // Server only. The client-safe settings and constants are in `spamSettings.ts`.
8
+ import { APIError } from 'payload';
9
+ import { memoryStore, WindowCounter } from './rateLimit.js';
10
+ import { FORM_SPAM_FIELD, FORM_SPAM_KEY, SPAM_BLOCKED_MESSAGE, spamSettings, } from './spamSettings.js';
11
+ const TURNSTILE_VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
12
+ /** The Turnstile keys from `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY`. Null unless both are set. */
13
+ export function turnstileKeys(env = process.env) {
14
+ const siteKey = env.TURNSTILE_SITE_KEY?.trim();
15
+ const secretKey = env.TURNSTILE_SECRET_KEY?.trim();
16
+ return siteKey && secretKey ? { siteKey, secretKey } : null;
17
+ }
18
+ /**
19
+ * The `spamProtection` group for the form-builder plugin's forms collection:
20
+ * `formOverrides: { fields: ({ defaultFields }) => [...defaultFields, spamProtectionField()] }`.
21
+ * `turnstileSiteKey` is virtual and hidden: on read it holds the site key when the form uses
22
+ * Turnstile and both keys are set, so the site's form knows whether to show the widget.
23
+ */
24
+ export function spamProtectionField(options = {}) {
25
+ return {
26
+ name: FORM_SPAM_FIELD,
27
+ type: 'group',
28
+ label: 'Spam protection',
29
+ admin: { description: 'Checks that run on the server for every submission. Blocked submissions are not stored.' },
30
+ fields: [
31
+ {
32
+ name: 'honeypot',
33
+ type: 'checkbox',
34
+ label: 'Honeypot',
35
+ defaultValue: true,
36
+ admin: { description: 'A hidden input that people never see. Bots that fill it in are blocked.' },
37
+ },
38
+ {
39
+ name: 'minFillSeconds',
40
+ type: 'number',
41
+ label: 'Minimum fill time (seconds)',
42
+ defaultValue: 3,
43
+ min: 0,
44
+ admin: { description: 'Submissions sent faster than this after the form shows are blocked. 0 turns it off.' },
45
+ },
46
+ {
47
+ name: 'turnstile',
48
+ type: 'checkbox',
49
+ label: 'Cloudflare Turnstile',
50
+ defaultValue: false,
51
+ admin: { description: 'Shows a Turnstile check. Needs TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY on the server; without them it stays off.' },
52
+ },
53
+ {
54
+ name: 'rateLimit',
55
+ type: 'group',
56
+ label: 'Rate limit',
57
+ admin: { description: 'At most this many submissions per visitor (IP address) in the time window.' },
58
+ fields: [
59
+ { name: 'max', type: 'number', label: 'Submissions', defaultValue: 5, min: 0, admin: { description: '0 turns the limit off.' } },
60
+ { name: 'windowMinutes', type: 'number', label: 'Minutes', defaultValue: 10, min: 1 },
61
+ ],
62
+ },
63
+ {
64
+ name: 'turnstileSiteKey',
65
+ type: 'text',
66
+ virtual: true,
67
+ admin: { hidden: true, readOnly: true },
68
+ hooks: {
69
+ afterRead: [
70
+ ({ siblingData }) => {
71
+ if (siblingData?.turnstile !== true)
72
+ return null;
73
+ return turnstileKeys(options.env)?.siteKey ?? null;
74
+ },
75
+ ],
76
+ },
77
+ },
78
+ ],
79
+ };
80
+ }
81
+ /** True when the honeypot input has a value. */
82
+ export function honeypotFilled(values) {
83
+ return typeof values?.honeypot === 'string' && values.honeypot.trim() !== '';
84
+ }
85
+ /**
86
+ * True when the form was sent faster than the form allows. A missing time counts as too fast. A
87
+ * heuristic only: the visitor's browser measures the time, so a bot can send any value. The real
88
+ * checks are the honeypot, the rate limit and Turnstile.
89
+ */
90
+ export function filledTooFast(values, settings) {
91
+ if (settings.minFillSeconds <= 0)
92
+ return false;
93
+ const elapsed = values?.elapsedMs;
94
+ if (typeof elapsed !== 'number' || !Number.isFinite(elapsed))
95
+ return true;
96
+ return elapsed < settings.minFillSeconds * 1000;
97
+ }
98
+ /**
99
+ * The visitor's IP from the trusted header, or null. No header is trusted by default: any visitor
100
+ * can send these headers, and a proxy that the server does not sit behind does not fix them.
101
+ */
102
+ export function clientIp(headers, trusted) {
103
+ if (!headers || !trusted)
104
+ return null;
105
+ const value = headers.get(trusted);
106
+ if (!value)
107
+ return null;
108
+ if (trusted !== 'x-forwarded-for')
109
+ return value.trim() || null;
110
+ const entries = value.split(',').map((entry) => entry.trim()).filter(Boolean);
111
+ return entries.at(-1) ?? null;
112
+ }
113
+ /** Asks Cloudflare whether a Turnstile token is valid. A network error or a bad answer counts as invalid. */
114
+ export async function verifyTurnstile(args) {
115
+ if (typeof args.token !== 'string' || args.token === '')
116
+ return false;
117
+ const body = new URLSearchParams({ secret: args.secretKey, response: args.token });
118
+ if (args.ip)
119
+ body.set('remoteip', args.ip);
120
+ try {
121
+ const response = await (args.fetch ?? fetch)(TURNSTILE_VERIFY_URL, { method: 'POST', body });
122
+ if (!response.ok)
123
+ return false;
124
+ const result = (await response.json());
125
+ return result.success === true;
126
+ }
127
+ catch {
128
+ return false;
129
+ }
130
+ }
131
+ /** A short hash of the IP, so the store never holds addresses. */
132
+ async function ipHash(ip) {
133
+ const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(`form-rate:${ip}`));
134
+ return Buffer.from(digest).toString('hex').slice(0, 32);
135
+ }
136
+ /**
137
+ * `context` flag of a submission the site's no-JavaScript route sends (a native form post). The
138
+ * fill time cannot be measured without JavaScript: that check passes. A form that uses Turnstile
139
+ * is refused (the check needs the widget). Only server code can set `context`.
140
+ */
141
+ export const FORM_NO_SCRIPT_CONTEXT = 'builderFormNoScript';
142
+ /** The message for a form with Turnstile sent without JavaScript. */
143
+ export const TURNSTILE_NEEDS_SCRIPT_MESSAGE = 'This form needs JavaScript for its spam check. Turn on JavaScript and send it again.';
144
+ const idOf = (value) => {
145
+ if (typeof value === 'string' || typeof value === 'number')
146
+ return value;
147
+ if (value && typeof value === 'object' && 'id' in value)
148
+ return idOf(value.id);
149
+ return null;
150
+ };
151
+ /** Runs the checks, cheapest first. The rate limit counts only submissions that pass the others. */
152
+ export async function checkSubmission(args) {
153
+ const { settings, values } = args;
154
+ if (settings.honeypot && honeypotFilled(values))
155
+ return { ok: false, reason: 'honeypot' };
156
+ if (filledTooFast(values, settings))
157
+ return { ok: false, reason: 'too-fast' };
158
+ const keys = settings.turnstile ? turnstileKeys(args.env) : null;
159
+ if (keys && !(await verifyTurnstile({ token: values?.token, secretKey: keys.secretKey, ip: args.ip, fetch: args.fetch }))) {
160
+ return { ok: false, reason: 'turnstile' };
161
+ }
162
+ if (args.ip && settings.rateLimit.max > 0) {
163
+ const key = `website-builder:form-rate:${String(args.formId ?? 'none')}:${await ipHash(args.ip)}`;
164
+ const taken = await args.counter.take(args.store, key, settings.rateLimit.max, settings.rateLimit.windowMinutes * 60_000);
165
+ if (!taken.ok)
166
+ return { ok: false, reason: 'rate-limit' };
167
+ }
168
+ return { ok: true };
169
+ }
170
+ /**
171
+ * The submissions hook. Put it first in the form-builder plugin's submissions hooks:
172
+ * `formSubmissionOverrides: { hooks: { beforeValidate: [formSpamProtection(), formSubmissionConditions()] } }`.
173
+ * Runs on create only. The site's form sends `{ form, submissionData, spam }`; `spam` is always
174
+ * removed from the data, so it is never stored. Server code (Local API) and signed-in admin users
175
+ * who send no `spam` values (the admin's create view) are not checked.
176
+ */
177
+ export function formSpamProtection(options = {}) {
178
+ const formsSlug = options.forms ?? 'forms';
179
+ const counter = new WindowCounter(options.now);
180
+ const memory = memoryStore();
181
+ return async ({ context, data, operation, req }) => {
182
+ if (operation !== 'create' || !data)
183
+ return data;
184
+ const { [FORM_SPAM_KEY]: raw, ...rest } = data;
185
+ // Server code (Local API) that sends no spam values is not checked. The site's no-JavaScript route sends them.
186
+ if (req.payloadAPI === 'local' && raw === undefined)
187
+ return rest;
188
+ const adminUser = req.user && req.user.collection === req.payload.config.admin?.user;
189
+ if (adminUser && raw === undefined)
190
+ return rest;
191
+ const values = raw && typeof raw === 'object' ? raw : null;
192
+ const formId = idOf(rest.form);
193
+ const form = formId === null
194
+ ? null
195
+ : (await req.payload.findByID({ collection: formsSlug, id: formId, depth: 0, req, overrideAccess: true }).catch(() => null));
196
+ const stored = spamSettings(form?.[FORM_SPAM_FIELD]);
197
+ const noScript = context?.[FORM_NO_SCRIPT_CONTEXT] === true;
198
+ if (noScript && stored.turnstile && turnstileKeys(options.env ?? process.env))
199
+ throw new APIError(TURNSTILE_NEEDS_SCRIPT_MESSAGE, 400, null, true);
200
+ // Without JavaScript the fill time is not measured: that check passes. The honeypot and the rate limit stay.
201
+ const settings = noScript ? { ...stored, minFillSeconds: 0 } : stored;
202
+ const ip = options.ipOf ? options.ipOf(req) : clientIp(req.headers, options.trustedIpHeader);
203
+ const result = await checkSubmission({
204
+ values,
205
+ settings,
206
+ ip,
207
+ formId,
208
+ env: options.env ?? process.env,
209
+ fetch: options.fetch,
210
+ store: options.store ?? req.payload.kv ?? memory,
211
+ counter,
212
+ });
213
+ if (result.ok)
214
+ return rest;
215
+ req.payload.logger.warn({ msg: 'Form submission blocked', form: formId, reason: result.reason, ip });
216
+ throw new APIError(SPAM_BLOCKED_MESSAGE, result.reason === 'rate-limit' ? 429 : 400, null, true);
217
+ };
218
+ }
@@ -0,0 +1,43 @@
1
+ /** Name of the group field on the forms collection. */
2
+ export declare const FORM_SPAM_FIELD = "spamProtection";
3
+ /** The key of the submission body that carries the spam values: `{ form, submissionData, spam }`. */
4
+ export declare const FORM_SPAM_KEY = "spam";
5
+ /** Name of the honeypot input. People never see it; bots that fill every input fill it. */
6
+ export declare const HONEYPOT_NAME = "website";
7
+ /** The generic message a blocked visitor sees. It never says which check failed. */
8
+ export declare const SPAM_BLOCKED_MESSAGE = "Your message could not be sent. Please try again later.";
9
+ /** The form's settings as stored. Every key may be missing on forms saved before the field existed. */
10
+ export type FormSpamSettingsInput = {
11
+ honeypot?: boolean | null;
12
+ minFillSeconds?: number | null;
13
+ turnstile?: boolean | null;
14
+ rateLimit?: {
15
+ max?: number | null;
16
+ windowMinutes?: number | null;
17
+ } | null;
18
+ /** Read-only, set on read: the Turnstile site key when Turnstile is on and both keys are set. */
19
+ turnstileSiteKey?: string | null;
20
+ };
21
+ export type FormSpamSettings = {
22
+ honeypot: boolean;
23
+ minFillSeconds: number;
24
+ turnstile: boolean;
25
+ /** At most `max` submissions per visitor (IP) and form in `windowMinutes`. `max` 0: off. */
26
+ rateLimit: {
27
+ max: number;
28
+ windowMinutes: number;
29
+ };
30
+ };
31
+ export declare const SPAM_DEFAULTS: FormSpamSettings;
32
+ /** The settings with defaults for missing values: honeypot on, 3 seconds, no Turnstile, 5 per 10 minutes. */
33
+ export declare function spamSettings(value: FormSpamSettingsInput | null | undefined): FormSpamSettings;
34
+ /**
35
+ * What the site's form sends under `spam`: the honeypot input's value, the milliseconds between
36
+ * the form showing and the submit (measured in the browser, so clock differences do not matter),
37
+ * and the Turnstile token.
38
+ */
39
+ export type FormSpamValues = {
40
+ honeypot?: string | null;
41
+ elapsedMs?: number | null;
42
+ token?: string | null;
43
+ };
@@ -0,0 +1,25 @@
1
+ // Spam protection settings of a form (`spamProtection` group on the forms collection) and the
2
+ // values the site's form sends with a submission. Client-safe: no Payload runtime imports. The
3
+ // server checks live in `spam.ts`.
4
+ /** Name of the group field on the forms collection. */
5
+ export const FORM_SPAM_FIELD = 'spamProtection';
6
+ /** The key of the submission body that carries the spam values: `{ form, submissionData, spam }`. */
7
+ export const FORM_SPAM_KEY = 'spam';
8
+ /** Name of the honeypot input. People never see it; bots that fill every input fill it. */
9
+ export const HONEYPOT_NAME = 'website';
10
+ /** The generic message a blocked visitor sees. It never says which check failed. */
11
+ export const SPAM_BLOCKED_MESSAGE = 'Your message could not be sent. Please try again later.';
12
+ export const SPAM_DEFAULTS = { honeypot: true, minFillSeconds: 3, turnstile: false, rateLimit: { max: 5, windowMinutes: 10 } };
13
+ const count = (value, fallback) => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback);
14
+ /** The settings with defaults for missing values: honeypot on, 3 seconds, no Turnstile, 5 per 10 minutes. */
15
+ export function spamSettings(value) {
16
+ return {
17
+ honeypot: value?.honeypot !== false,
18
+ minFillSeconds: count(value?.minFillSeconds, SPAM_DEFAULTS.minFillSeconds),
19
+ turnstile: value?.turnstile === true,
20
+ rateLimit: {
21
+ max: count(value?.rateLimit?.max, SPAM_DEFAULTS.rateLimit.max),
22
+ windowMinutes: count(value?.rateLimit?.windowMinutes, SPAM_DEFAULTS.rateLimit.windowMinutes),
23
+ },
24
+ };
25
+ }
@@ -0,0 +1,34 @@
1
+ import { type CollectionBeforeValidateHook } from 'payload';
2
+ import { type FormAnswerField } from './answers.js';
3
+ /** One answer, as the plugin stores it in `submissionData`. */
4
+ export type SubmissionRow = {
5
+ field?: string | null;
6
+ value?: unknown;
7
+ id?: string | null;
8
+ };
9
+ type FormFieldWithLabel = FormAnswerField;
10
+ /**
11
+ * The answers to keep, the shown required fields left empty, and the shown fields whose answer has
12
+ * the wrong format (`invalid`, with the message). Pure: the hook and the tests use it. Answers for
13
+ * hidden fields are dropped; answers for names the form does not have stay.
14
+ */
15
+ export declare function applyFormConditions(fields: readonly FormFieldWithLabel[] | null | undefined, rows: readonly SubmissionRow[] | null | undefined): {
16
+ rows: SubmissionRow[];
17
+ hidden: Set<string>;
18
+ missing: FormFieldWithLabel[];
19
+ invalid: Array<{
20
+ field: FormFieldWithLabel;
21
+ message: string;
22
+ }>;
23
+ };
24
+ export type FormSubmissionConditionsOptions = {
25
+ /** Slug of the forms collection. Default "forms" (the plugin's default). */
26
+ forms?: string;
27
+ };
28
+ /**
29
+ * The submissions hook. Add it to the form-builder plugin:
30
+ * `formSubmissionOverrides: { hooks: { beforeValidate: [formSubmissionConditions()] } }`.
31
+ * Runs on create only. A form that cannot be read is left to the plugin's own check.
32
+ */
33
+ export declare function formSubmissionConditions(options?: FormSubmissionConditionsOptions): CollectionBeforeValidateHook;
34
+ export {};
@@ -0,0 +1,89 @@
1
+ // Server side of form display conditions and answer checks: a `beforeValidate` hook for the
2
+ // form-builder plugin's submissions collection. It reads the form, works out which fields the
3
+ // visitor's answers hide, drops the values of hidden fields, and refuses a submission that leaves a
4
+ // shown required field empty or gives an answer in the wrong format (email, phone, web address,
5
+ // number, date, an option the field does not have). A hidden required field is never required.
6
+ import { ValidationError } from 'payload';
7
+ import { formAnswerProblem, TICK_FIELD_TYPES } from './answers.js';
8
+ import { hiddenFormFields, isEmptyFormValue, isFormFieldShown } from './conditions.js';
9
+ /** A checkbox or consent answer arrives as text ("true"); the conditions compare booleans. */
10
+ function answerValue(field, value) {
11
+ if (TICK_FIELD_TYPES.has(field?.blockType ?? '')) {
12
+ if (typeof value === 'boolean')
13
+ return value;
14
+ return typeof value === 'string' ? ['true', 'on', '1', 'yes'].includes(value.trim().toLowerCase()) : false;
15
+ }
16
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
17
+ return value;
18
+ return value === null || value === undefined ? undefined : String(value);
19
+ }
20
+ const hasName = (field) => typeof field.name === 'string' && field.name !== '';
21
+ /**
22
+ * The answers to keep, the shown required fields left empty, and the shown fields whose answer has
23
+ * the wrong format (`invalid`, with the message). Pure: the hook and the tests use it. Answers for
24
+ * hidden fields are dropped; answers for names the form does not have stay.
25
+ */
26
+ export function applyFormConditions(fields, rows) {
27
+ const named = (fields ?? []).filter(hasName);
28
+ const byName = new Map(named.map((f) => [f.name, f]));
29
+ const values = {};
30
+ for (const row of rows ?? []) {
31
+ if (typeof row?.field !== 'string')
32
+ continue;
33
+ values[row.field] = answerValue(byName.get(row.field), row.value);
34
+ }
35
+ const hidden = hiddenFormFields(named, values);
36
+ const kept = (rows ?? []).filter((row) => typeof row?.field !== 'string' || !hidden.has(row.field));
37
+ const missing = named.filter((field) => {
38
+ if (!field.required || field.blockType === 'message' || !isFormFieldShown(field, hidden))
39
+ return false;
40
+ const value = values[field.name];
41
+ return TICK_FIELD_TYPES.has(field.blockType ?? '') ? value !== true : isEmptyFormValue(value);
42
+ });
43
+ const invalid = named.flatMap((field) => {
44
+ if (missing.includes(field) || !isFormFieldShown(field, hidden))
45
+ return [];
46
+ const message = formAnswerProblem(field, values[field.name]);
47
+ return message ? [{ field, message }] : [];
48
+ });
49
+ return { rows: kept, hidden, missing, invalid };
50
+ }
51
+ const idOf = (value) => {
52
+ if (typeof value === 'string' || typeof value === 'number')
53
+ return value;
54
+ if (value && typeof value === 'object' && 'id' in value)
55
+ return idOf(value.id);
56
+ return null;
57
+ };
58
+ /**
59
+ * The submissions hook. Add it to the form-builder plugin:
60
+ * `formSubmissionOverrides: { hooks: { beforeValidate: [formSubmissionConditions()] } }`.
61
+ * Runs on create only. A form that cannot be read is left to the plugin's own check.
62
+ */
63
+ export function formSubmissionConditions(options = {}) {
64
+ const formsSlug = options.forms ?? 'forms';
65
+ return async ({ collection, data, operation, req }) => {
66
+ if (operation !== 'create' || !data)
67
+ return data;
68
+ const id = idOf(data.form);
69
+ if (id === null)
70
+ return data;
71
+ const form = (await req.payload
72
+ .findByID({ collection: formsSlug, id, depth: 0, req, overrideAccess: true })
73
+ .catch(() => null));
74
+ if (!form)
75
+ return data;
76
+ const { rows, missing, invalid } = applyFormConditions(form.fields, data.submissionData);
77
+ if (missing.length > 0 || invalid.length > 0) {
78
+ throw new ValidationError({
79
+ collection: collection.slug,
80
+ req,
81
+ errors: [
82
+ ...missing.map((field) => ({ path: 'submissionData', message: `${field.label || field.name} is required.` })),
83
+ ...invalid.map(({ field, message }) => ({ path: 'submissionData', message: `${field.label || field.name}: ${message}` })),
84
+ ],
85
+ });
86
+ }
87
+ return { ...data, submissionData: rows };
88
+ };
89
+ }
@@ -0,0 +1,26 @@
1
+ import type { CollectionConfig, Field } from 'payload';
2
+ /** The date an admin first opened the submission. Empty: the list shows "New". */
3
+ export declare const SUBMISSION_READ_FIELD = "readAt";
4
+ /** The page the visitor sent the form from. */
5
+ export declare const SUBMISSION_PAGE_FIELD = "sourceUrl";
6
+ /** The detail view (a `ui` field). */
7
+ export declare const SUBMISSION_ANSWERS_FIELD = "answers";
8
+ /** The list's summary column (a `ui` field). */
9
+ export declare const SUBMISSION_SUMMARY_FIELD = "summary";
10
+ export type FormSubmissionsAdminOptions = {
11
+ /** An upload field (hasMany) with files sent with the submission. Default "attachments"; false: none. */
12
+ attachments?: string | false;
13
+ };
14
+ /** What the detail view and the cells read from `admin.custom`. */
15
+ export type SubmissionsAdminCustom = {
16
+ attachments: string | null;
17
+ };
18
+ /**
19
+ * The `admin` options and a `fields` function for `formSubmissionOverrides`. `fields` takes the
20
+ * collection's fields (the plugin's `defaultFields` plus your own) and returns them arranged for
21
+ * reading, with the read date, the source page and the two view fields added.
22
+ */
23
+ export declare function formSubmissionsAdmin(options?: FormSubmissionsAdminOptions): {
24
+ admin: Pick<NonNullable<CollectionConfig['admin']>, 'defaultColumns'>;
25
+ fields: (fields: Field[]) => Field[];
26
+ };
@@ -0,0 +1,108 @@
1
+ // The admin of the form-builder plugin's submissions collection, for people who read messages:
2
+ // a list with the summary, the form and a "New" badge, and a detail view with the answers as a
3
+ // table (the form's labels), the files, the page it came from and "Reply by email". The raw
4
+ // `submissionData` stays in a collapsed "Raw data" group. Server config: component paths only.
5
+ //
6
+ // const submissionsAdmin = formSubmissionsAdmin()
7
+ // formBuilderPlugin({
8
+ // formSubmissionOverrides: {
9
+ // admin: { ...submissionsAdmin.admin },
10
+ // fields: ({ defaultFields }) => submissionsAdmin.fields([...defaultFields, myAttachmentsField]),
11
+ // },
12
+ // })
13
+ import { withoutFormResult } from './noScript.js';
14
+ import { safePageUrl } from './summary.js';
15
+ /** The date an admin first opened the submission. Empty: the list shows "New". */
16
+ export const SUBMISSION_READ_FIELD = 'readAt';
17
+ /** The page the visitor sent the form from. */
18
+ export const SUBMISSION_PAGE_FIELD = 'sourceUrl';
19
+ /** The detail view (a `ui` field). */
20
+ export const SUBMISSION_ANSWERS_FIELD = 'answers';
21
+ /** The list's summary column (a `ui` field). */
22
+ export const SUBMISSION_SUMMARY_FIELD = 'summary';
23
+ /** The fields the "Raw data" group holds: the plugin's own storage and the attachments. */
24
+ const RAW_FIELDS = ['submissionData', 'submissionUploads'];
25
+ /** The page address on create: the one the form sent, else the request's Referer. Only links that are safe to show. */
26
+ const pageOnCreate = ({ operation, req, value }) => {
27
+ if (operation !== 'create')
28
+ return value;
29
+ const page = safePageUrl(value) ?? safePageUrl(req.headers?.get?.('referer'));
30
+ // A form sent again from a no-JavaScript result view: the page, without the result.
31
+ return page ? withoutFormResult(page) : null;
32
+ };
33
+ const nameOf = (field) => ('name' in field && typeof field.name === 'string' ? field.name : null);
34
+ /**
35
+ * The `admin` options and a `fields` function for `formSubmissionOverrides`. `fields` takes the
36
+ * collection's fields (the plugin's `defaultFields` plus your own) and returns them arranged for
37
+ * reading, with the read date, the source page and the two view fields added.
38
+ */
39
+ export function formSubmissionsAdmin(options = {}) {
40
+ const attachments = options.attachments === false ? null : (options.attachments ?? 'attachments');
41
+ const custom = { attachments };
42
+ const raw = new Set([...RAW_FIELDS, ...(attachments ? [attachments] : [])]);
43
+ return {
44
+ admin: { defaultColumns: [SUBMISSION_SUMMARY_FIELD, 'form', SUBMISSION_READ_FIELD, 'createdAt'] },
45
+ fields: (fields) => {
46
+ const names = new Set(fields.map(nameOf).filter(Boolean));
47
+ const rawFields = fields.filter((field) => raw.has(nameOf(field) ?? ''));
48
+ const rest = fields
49
+ .filter((field) => !raw.has(nameOf(field) ?? ''))
50
+ .map((field) => (nameOf(field) === 'form' ? { ...field, admin: { ...field.admin, position: 'sidebar' } } : field));
51
+ const added = [
52
+ {
53
+ name: SUBMISSION_ANSWERS_FIELD,
54
+ type: 'ui',
55
+ admin: { components: { Field: 'payload-canvas/rsc#SubmissionView' }, disableListColumn: true, custom },
56
+ },
57
+ {
58
+ name: SUBMISSION_SUMMARY_FIELD,
59
+ type: 'ui',
60
+ label: 'Message',
61
+ // List only: a ui field without a Field component shows nothing in the edit view.
62
+ admin: { components: { Cell: 'payload-canvas/rsc#SubmissionSummaryCell' }, custom },
63
+ },
64
+ ];
65
+ const sidebar = [
66
+ ...(names.has(SUBMISSION_READ_FIELD)
67
+ ? []
68
+ : [
69
+ {
70
+ name: SUBMISSION_READ_FIELD,
71
+ type: 'date',
72
+ label: 'Opened',
73
+ index: true,
74
+ // Set by the detail view, never by visitors or the edit form.
75
+ access: { create: () => false, update: () => false },
76
+ admin: {
77
+ position: 'sidebar',
78
+ readOnly: true,
79
+ date: { pickerAppearance: 'dayAndTime' },
80
+ description: 'When someone first opened this message. Empty: the list shows "New".',
81
+ components: { Cell: 'payload-canvas/rsc#SubmissionReadCell' },
82
+ },
83
+ },
84
+ ]),
85
+ ...(names.has(SUBMISSION_PAGE_FIELD)
86
+ ? []
87
+ : [
88
+ {
89
+ name: SUBMISSION_PAGE_FIELD,
90
+ type: 'text',
91
+ label: 'Sent from',
92
+ access: { update: () => false },
93
+ hooks: { beforeChange: [pageOnCreate] },
94
+ admin: { position: 'sidebar', readOnly: true, description: 'The page the form was sent from.' },
95
+ },
96
+ ]),
97
+ ];
98
+ return [
99
+ ...added,
100
+ ...rest,
101
+ ...(rawFields.length > 0
102
+ ? [{ type: 'collapsible', label: 'Raw data', admin: { initCollapsed: true }, fields: rawFields }]
103
+ : []),
104
+ ...sidebar,
105
+ ];
106
+ },
107
+ };
108
+ }
@@ -0,0 +1,60 @@
1
+ /** One answer, as `@payloadcms/plugin-form-builder` stores it in `submissionData`. */
2
+ export type SubmissionDataRow = {
3
+ field?: string | null;
4
+ value?: unknown;
5
+ };
6
+ /** The parts of a form field block the summary reads. */
7
+ export type SubmissionFormField = {
8
+ blockType?: string | null;
9
+ name?: string | null;
10
+ label?: string | null;
11
+ options?: ReadonlyArray<{
12
+ label?: string | null;
13
+ value?: string | null;
14
+ }> | null;
15
+ };
16
+ export type SubmissionAnswer = {
17
+ /** The field name the answer was sent for. */
18
+ name: string;
19
+ /** The form field's label, else the name. */
20
+ label: string;
21
+ /** The answer as sent. */
22
+ value: string;
23
+ /** The answer for people: "Yes" / "No" for a checkbox, the option label for a choice. */
24
+ display: string;
25
+ /** The form field's block type (`email`, `checkbox`, …). Null when the form has no field of that name any more. */
26
+ type: string | null;
27
+ };
28
+ export type SubmissionSummary = {
29
+ name: string | null;
30
+ email: string | null;
31
+ /** The message, else the first other answer. */
32
+ text: string | null;
33
+ /** One line for lists: "Ada Lovelace · ada@example.com", else the name, the email or the text. */
34
+ line: string | null;
35
+ };
36
+ /** True for a plain email address. */
37
+ export declare function isEmailAddress(value: unknown): value is string;
38
+ /**
39
+ * The answers in the form's field order, with the form's labels. Answers for names the form no
40
+ * longer has come last, labelled with their name. Fields without an answer (hidden by display
41
+ * conditions, or added later) and messages are left out.
42
+ */
43
+ export declare function submissionAnswers(fields: readonly SubmissionFormField[] | null | undefined, rows: readonly SubmissionDataRow[] | null | undefined): SubmissionAnswer[];
44
+ /**
45
+ * Name, email and message of a submission. Email: an email field, else a field called "email",
46
+ * else the first answer that looks like an address. Name: a field called "name" (first and last
47
+ * name are joined). Text: a message-like field, else the first other answer.
48
+ */
49
+ export declare function submissionSummary(rows: readonly SubmissionDataRow[] | null | undefined, fields?: readonly SubmissionFormField[] | null): SubmissionSummary;
50
+ /** A `mailto:` link that replies to `email`, or null when it is not an address. */
51
+ export declare function replyMailto(email: string | null | undefined, options?: {
52
+ subject?: string | null;
53
+ }): string | null;
54
+ /** One line of text, at most `max` characters, with an ellipsis when cut. */
55
+ export declare function shortAnswer(text: string | null | undefined, max?: number): string;
56
+ /**
57
+ * A page address a submission names, safe to link: an http(s) URL or a site path. Null otherwise.
58
+ * Visitors send it, so nothing else (javascript:, data:) ever becomes a link.
59
+ */
60
+ export declare function safePageUrl(value: unknown): string | null;