@brimsites/brimjs 0.0.0-stage → 1.0.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 (238) hide show
  1. package/LICENSE +110 -0
  2. package/README.md +22 -2
  3. package/bin/brim.js +5 -0
  4. package/dist/cli.js +3802 -0
  5. package/editor-dist/editor.css +1 -0
  6. package/editor-dist/editor.js +91 -0
  7. package/package.json +71 -3
  8. package/skills/brim-convert/SKILL.md +256 -0
  9. package/skills/brim-hosting/SKILL.md +221 -0
  10. package/src/astro-shim.d.ts +5 -0
  11. package/src/auth/accounts.ts +341 -0
  12. package/src/auth/password.ts +34 -0
  13. package/src/auth/permissions.ts +44 -0
  14. package/src/blocks/accordion/Accordion.astro +48 -0
  15. package/src/blocks/accordion/accordion.css +63 -0
  16. package/src/blocks/analytics/Analytics.astro +45 -0
  17. package/src/blocks/analytics/ConsentBanner.astro +41 -0
  18. package/src/blocks/analytics/analytics.client.ts +125 -0
  19. package/src/blocks/analytics/analytics.css +51 -0
  20. package/src/blocks/analytics/consent.ts +51 -0
  21. package/src/blocks/button/Button.astro +64 -0
  22. package/src/blocks/button/button.css +100 -0
  23. package/src/blocks/carousel/Carousel.astro +140 -0
  24. package/src/blocks/carousel/carousel.client.ts +153 -0
  25. package/src/blocks/carousel/carousel.css +181 -0
  26. package/src/blocks/data/icons.ts +285 -0
  27. package/src/blocks/data/image-shapes.ts +91 -0
  28. package/src/blocks/data/social-icons.ts +41 -0
  29. package/src/blocks/data/social-networks.ts +256 -0
  30. package/src/blocks/divider/Divider.astro +27 -0
  31. package/src/blocks/divider/divider.css +17 -0
  32. package/src/blocks/form/Captcha.astro +27 -0
  33. package/src/blocks/form/Form.astro +250 -0
  34. package/src/blocks/form/FormField.astro +138 -0
  35. package/src/blocks/form/Newsletter.astro +80 -0
  36. package/src/blocks/form/form.client.ts +339 -0
  37. package/src/blocks/form/form.css +271 -0
  38. package/src/blocks/gallery/ImageGallery.astro +126 -0
  39. package/src/blocks/gallery/gallery.css +43 -0
  40. package/src/blocks/gallery/lightbox.client.ts +178 -0
  41. package/src/blocks/gallery/lightbox.css +134 -0
  42. package/src/blocks/icon/Icon.astro +41 -0
  43. package/src/blocks/icon/icon.css +16 -0
  44. package/src/blocks/image/Image.astro +158 -0
  45. package/src/blocks/image/image.css +42 -0
  46. package/src/blocks/images.ts +64 -0
  47. package/src/blocks/in-editor.client.ts +8 -0
  48. package/src/blocks/listing/Listing.astro +288 -0
  49. package/src/blocks/listing/ListingCards.astro +48 -0
  50. package/src/blocks/listing/listing.css +136 -0
  51. package/src/blocks/listing/query.ts +363 -0
  52. package/src/blocks/map/Map.astro +75 -0
  53. package/src/blocks/map/map.css +32 -0
  54. package/src/blocks/schemas/accordion.ts +118 -0
  55. package/src/blocks/schemas/button.ts +78 -0
  56. package/src/blocks/schemas/carousel.ts +133 -0
  57. package/src/blocks/schemas/divider.ts +29 -0
  58. package/src/blocks/schemas/form-field-types.ts +29 -0
  59. package/src/blocks/schemas/form.ts +350 -0
  60. package/src/blocks/schemas/icon.ts +24 -0
  61. package/src/blocks/schemas/image-gallery.ts +54 -0
  62. package/src/blocks/schemas/image.ts +87 -0
  63. package/src/blocks/schemas/index.ts +33 -0
  64. package/src/blocks/schemas/listing.ts +14 -0
  65. package/src/blocks/schemas/map.ts +81 -0
  66. package/src/blocks/schemas/newsletter.ts +324 -0
  67. package/src/blocks/schemas/social-media.ts +348 -0
  68. package/src/blocks/schemas/text.ts +151 -0
  69. package/src/blocks/schemas/video.ts +57 -0
  70. package/src/blocks/search/Search.astro +147 -0
  71. package/src/blocks/search/search.css +69 -0
  72. package/src/blocks/search/state.ts +28 -0
  73. package/src/blocks/settings.ts +94 -0
  74. package/src/blocks/social/SocialMedia.astro +102 -0
  75. package/src/blocks/social/social-links.ts +16 -0
  76. package/src/blocks/social/social.css +31 -0
  77. package/src/blocks/theme.ts +35 -0
  78. package/src/blocks/types.ts +52 -0
  79. package/src/blocks/video/Video.astro +90 -0
  80. package/src/blocks/video/video-source.ts +77 -0
  81. package/src/blocks/video/video.client.ts +43 -0
  82. package/src/blocks/video/video.css +29 -0
  83. package/src/check.ts +1119 -0
  84. package/src/cli.ts +493 -0
  85. package/src/components/Blocks.astro +68 -0
  86. package/src/components/Field.astro +61 -0
  87. package/src/components/Footer.astro +36 -0
  88. package/src/components/Link.astro +18 -0
  89. package/src/components/MobileMenu.astro +77 -0
  90. package/src/components/Navbar.astro +42 -0
  91. package/src/components/RichText.astro +32 -0
  92. package/src/components/Seo.astro +202 -0
  93. package/src/components/Setting.astro +46 -0
  94. package/src/components/Shared.astro +17 -0
  95. package/src/components/Text.astro +91 -0
  96. package/src/components/blocks.css +86 -0
  97. package/src/components/index.ts +27 -0
  98. package/src/components/mobile-menu.client.ts +21 -0
  99. package/src/components/mobile-menu.css +52 -0
  100. package/src/components/text.css +48 -0
  101. package/src/config.ts +413 -0
  102. package/src/content/block-layout.ts +63 -0
  103. package/src/content/block-values.ts +48 -0
  104. package/src/content/content-check.ts +174 -0
  105. package/src/content/content-types.ts +408 -0
  106. package/src/content/drafts.ts +115 -0
  107. package/src/content/feed.ts +237 -0
  108. package/src/content/field-types.ts +107 -0
  109. package/src/content/history.ts +140 -0
  110. package/src/content/ids.ts +50 -0
  111. package/src/content/image-size.ts +212 -0
  112. package/src/content/image-sizes.ts +126 -0
  113. package/src/content/item-fields.ts +110 -0
  114. package/src/content/item-head.ts +126 -0
  115. package/src/content/item-image.ts +26 -0
  116. package/src/content/item-path.ts +122 -0
  117. package/src/content/items.ts +580 -0
  118. package/src/content/language-scopes.ts +40 -0
  119. package/src/content/media.ts +271 -0
  120. package/src/content/menus.ts +51 -0
  121. package/src/content/page-templates.ts +52 -0
  122. package/src/content/redirects.ts +112 -0
  123. package/src/content/references.ts +165 -0
  124. package/src/content/rich-text.ts +63 -0
  125. package/src/content/search.ts +167 -0
  126. package/src/content/seed.ts +229 -0
  127. package/src/content/site-settings.ts +111 -0
  128. package/src/content/sitemap.ts +143 -0
  129. package/src/content/store.ts +225 -0
  130. package/src/content/tags.ts +67 -0
  131. package/src/content/text-default.ts +139 -0
  132. package/src/content/types.ts +137 -0
  133. package/src/content/validate.ts +253 -0
  134. package/src/content/validation-error.ts +2 -0
  135. package/src/db/cached.ts +140 -0
  136. package/src/db/database.ts +15 -0
  137. package/src/db/libsql.ts +29 -0
  138. package/src/db/schema.ts +189 -0
  139. package/src/db/url.ts +44 -0
  140. package/src/editor/client/BlockSettings.tsx +1063 -0
  141. package/src/editor/client/Chrome.tsx +284 -0
  142. package/src/editor/client/ContentBrowser.tsx +1299 -0
  143. package/src/editor/client/Editor.tsx +1756 -0
  144. package/src/editor/client/HistoryPanel.tsx +114 -0
  145. package/src/editor/client/ImagesWidget.tsx +113 -0
  146. package/src/editor/client/Inspector.tsx +127 -0
  147. package/src/editor/client/ItemForm.tsx +535 -0
  148. package/src/editor/client/LinkWidget.tsx +440 -0
  149. package/src/editor/client/ListingPanel.tsx +99 -0
  150. package/src/editor/client/Login.tsx +338 -0
  151. package/src/editor/client/Menu.tsx +64 -0
  152. package/src/editor/client/PageSettings.tsx +270 -0
  153. package/src/editor/client/RedirectsSettings.tsx +130 -0
  154. package/src/editor/client/Resize.tsx +204 -0
  155. package/src/editor/client/Sidebar.tsx +51 -0
  156. package/src/editor/client/SiteMap.tsx +568 -0
  157. package/src/editor/client/SiteSettings.tsx +409 -0
  158. package/src/editor/client/TextTools.tsx +391 -0
  159. package/src/editor/client/Toolbar.tsx +449 -0
  160. package/src/editor/client/VideoUpload.tsx +251 -0
  161. package/src/editor/client/api.ts +417 -0
  162. package/src/editor/client/brand.ts +20 -0
  163. package/src/editor/client/connection.ts +98 -0
  164. package/src/editor/client/context.ts +19 -0
  165. package/src/editor/client/css.d.ts +2 -0
  166. package/src/editor/client/editor.css +4656 -0
  167. package/src/editor/client/fields.tsx +812 -0
  168. package/src/editor/client/icons.tsx +174 -0
  169. package/src/editor/client/keys.ts +15 -0
  170. package/src/editor/client/kinds.ts +289 -0
  171. package/src/editor/client/languages.ts +32 -0
  172. package/src/editor/client/main.tsx +100 -0
  173. package/src/editor/client/responses.ts +26 -0
  174. package/src/editor/client/rich-text.ts +326 -0
  175. package/src/editor/client/site-tree.ts +239 -0
  176. package/src/editor/client/theme.ts +55 -0
  177. package/src/editor/client/tsconfig.json +18 -0
  178. package/src/editor/client/tus.ts +137 -0
  179. package/src/editor/client/use-rect.ts +50 -0
  180. package/src/editor/client/widgets.tsx +1218 -0
  181. package/src/forms/captcha.ts +83 -0
  182. package/src/forms/define.ts +166 -0
  183. package/src/forms/fields.ts +197 -0
  184. package/src/forms/file-types.ts +108 -0
  185. package/src/forms/files.ts +216 -0
  186. package/src/forms/form-page.ts +9 -0
  187. package/src/forms/handler.ts +622 -0
  188. package/src/forms/spec.ts +89 -0
  189. package/src/forms/store.ts +96 -0
  190. package/src/forms/work.ts +50 -0
  191. package/src/icons/library.ts +144 -0
  192. package/src/icons/load.ts +63 -0
  193. package/src/index.ts +99 -0
  194. package/src/init.ts +257 -0
  195. package/src/integration.ts +469 -0
  196. package/src/mail/mailer.ts +197 -0
  197. package/src/mail/notify.ts +272 -0
  198. package/src/mail/settings.ts +173 -0
  199. package/src/mail/templates.ts +191 -0
  200. package/src/mcp/page-nodes.ts +209 -0
  201. package/src/mcp/server.ts +111 -0
  202. package/src/mcp/tools.ts +637 -0
  203. package/src/runtime/TemplatePage.astro +39 -0
  204. package/src/runtime/TemplatePageStatic.astro +13 -0
  205. package/src/runtime/admin-route.ts +80 -0
  206. package/src/runtime/connect.ts +53 -0
  207. package/src/runtime/content.ts +188 -0
  208. package/src/runtime/context.ts +131 -0
  209. package/src/runtime/form-files.ts +18 -0
  210. package/src/runtime/forms-route.ts +33 -0
  211. package/src/runtime/forms.ts +28 -0
  212. package/src/runtime/icons.ts +5 -0
  213. package/src/runtime/media.ts +175 -0
  214. package/src/runtime/middleware.ts +186 -0
  215. package/src/runtime/nav.ts +13 -0
  216. package/src/runtime/query-reads.ts +49 -0
  217. package/src/runtime/query-store.ts +16 -0
  218. package/src/runtime/request-state.ts +69 -0
  219. package/src/runtime/robots.ts +29 -0
  220. package/src/runtime/rss-static.ts +16 -0
  221. package/src/runtime/rss.ts +29 -0
  222. package/src/runtime/server.ts +29 -0
  223. package/src/runtime/sitemap.ts +34 -0
  224. package/src/runtime/template-paths.ts +34 -0
  225. package/src/runtime/uploads-route.ts +13 -0
  226. package/src/seed-cli.ts +253 -0
  227. package/src/server/auth.ts +31 -0
  228. package/src/server/fetch-image.ts +219 -0
  229. package/src/server/handler.ts +2106 -0
  230. package/src/server/http.ts +162 -0
  231. package/src/server/locales.ts +73 -0
  232. package/src/server/node.ts +57 -0
  233. package/src/server/query-params.ts +249 -0
  234. package/src/server/rate-limit.ts +72 -0
  235. package/src/server/video-host.ts +162 -0
  236. package/src/starter.ts +70 -0
  237. package/src/version.ts +4 -0
  238. package/src/virtual.d.ts +65 -0
@@ -0,0 +1,622 @@
1
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
+ import { ValidationError } from "../content/validation-error.ts";
3
+ import type { Brim } from "../runtime/connect.ts";
4
+ import { HttpError, assertSameOrigin, json, readBytes, readJson, trustedOrigin } from "../server/http.ts";
5
+ import { formPage } from "./form-page.ts";
6
+ import { type ConfirmationEmail, type FormEmail, type SiteEmails, writtenBySite } from "../mail/templates.ts";
7
+ import { RateLimiter } from "../server/rate-limit.ts";
8
+ import type { Mailer } from "../mail/mailer.ts";
9
+ import {
10
+ CONFIRMATION_MESSAGE_LENGTH,
11
+ CONFIRMATION_SUBJECT_LENGTH,
12
+ confirmationAnswers,
13
+ confirmationNotice,
14
+ formNotice,
15
+ formRecipients,
16
+ } from "../mail/notify.ts";
17
+ import { MailSettingsStore, isEmail, splitAddresses } from "../mail/settings.ts";
18
+ import {
19
+ FILE_TYPES,
20
+ type FileType,
21
+ type FormFile,
22
+ FormFiles,
23
+ MAX_FIELDS_BYTES,
24
+ MAX_FILES,
25
+ MAX_FILE_BYTES,
26
+ MAX_MESSAGE_BYTES,
27
+ type PrivateFiles,
28
+ fileSize,
29
+ fileTypes,
30
+ safeFileName,
31
+ sniffFileType,
32
+ } from "./files.ts";
33
+ import type { FormAnswer } from "./store.ts";
34
+ import { CHOICE_TYPES, type FormChoice, type FormField, fieldShown } from "./fields.ts";
35
+ import { type CaptchaCheck, verifyCaptcha } from "./captcha.ts";
36
+ import { WORK_WINDOW_SECONDS, workBits, workDone } from "./work.ts";
37
+ import { type FormSpec, decodeSpec, isSigned, openAddress, sign } from "./spec.ts";
38
+
39
+ export const FORMS_PATH = "/_brim/forms";
40
+
41
+ /** A visitor needs at least this long to fill a form in; anything faster is a script. */
42
+ const MIN_FILL_MS = 2_000;
43
+ const TOKEN_LIFETIME_MS = 2 * 60 * 60 * 1000; // betterleaks:allow
44
+ const PER_VISITOR = { limit: 5, windowSeconds: 10 * 60 };
45
+ /**
46
+ * Emails sent about messages, on the whole site, a day. Past it messages are still kept for the editor, only not
47
+ * emailed: someone sending from many addresses can fill the owner's inbox, but cannot stop real visitors' messages.
48
+ */
49
+ const EMAILS_PER_SITE = { limit: 300, windowSeconds: 24 * 60 * 60 };
50
+ /** Messages kept on the whole site a day, far above any real use: past it the database is being filled on purpose. */
51
+ const KEPT_PER_SITE = { limit: 5_000, windowSeconds: 24 * 60 * 60 };
52
+ const TOKENS_PER_VISITOR = { limit: 30, windowSeconds: 10 * 60 };
53
+ /**
54
+ * Messages with files one visitor may start sending, counted before a byte of the body is read: reading costs
55
+ * memory, so someone without a fresh token, or past this, is refused while the files are still on their side.
56
+ */
57
+ const UPLOADS_PER_VISITOR = { limit: 20, windowSeconds: 10 * 60 };
58
+ /** Bytes of files kept a day: from one visitor (three full messages), and on the whole site. */
59
+ const FILE_BYTES_PER_VISITOR = { limit: 30 * 1024 * 1024, windowSeconds: 24 * 60 * 60 };
60
+ const FILE_BYTES_PER_SITE = { limit: 500 * 1024 * 1024, windowSeconds: 24 * 60 * 60 };
61
+ /**
62
+ * Confirmations a day. Anyone can type someone else's address in a form, so these are what keeps the site from
63
+ * being used to write to strangers: one address hears from the site three times a day at most, one visitor causes
64
+ * ten, and the whole site sends two hundred. They are counted apart from the emails to the owners
65
+ * (`EMAILS_PER_SITE`), so confirmations spent by an abuser never cost the owner a notification.
66
+ */
67
+ const CONFIRMATIONS_PER_ADDRESS = { limit: 3, windowSeconds: 24 * 60 * 60 };
68
+ const CONFIRMATIONS_PER_VISITOR = { limit: 10, windowSeconds: 24 * 60 * 60 };
69
+ const CONFIRMATIONS_PER_SITE = { limit: 200, windowSeconds: 24 * 60 * 60 };
70
+ /** The header a message with files carries its token in, so it is checked before the body is read. */
71
+ export const TOKEN_HEADER = "x-brim-form-token"; // betterleaks:allow (a header's name)
72
+ /** The work done for that token, which the page's script found (./work.ts). */
73
+ export const WORK_HEADER = "x-brim-form-work";
74
+
75
+ const MAX_LENGTH: Record<string, number> = { textarea: 10_000 };
76
+ const DEFAULT_MAX_LENGTH = 1_000;
77
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
78
+
79
+ export type FormsHandler = (request: Request, info: { clientAddress: string }) => Promise<Response | undefined>;
80
+
81
+ /**
82
+ * The public side of forms: hands out a short-lived token and accepts submissions.
83
+ * Resolves to `undefined` for any other path.
84
+ *
85
+ * A submission is accepted only when all of these hold:
86
+ * - it comes from a page of the site itself;
87
+ * - the form description it carries was signed by the site, so its fields are the author's;
88
+ * - it carries a token issued a little while ago and not used before, and the work its browser did for it;
89
+ * - the hidden trap field is empty;
90
+ * - when the site's forms have a challenge (Turnstile or hCaptcha), its provider says it was passed;
91
+ * - the visitor is within their limit, and the site within the messages it keeps a day;
92
+ * - every value fits the field it answers;
93
+ * - every file is one of the kinds its field takes by its own bytes, and within the sizes and counts allowed.
94
+ *
95
+ * Files are stored only once all of that held, so a refused message leaves nothing behind.
96
+ */
97
+ export interface FormsOptions {
98
+ /** Sends the email about each message. Without one, messages are only kept for the editor. */
99
+ mailer?: Mailer | undefined;
100
+ /**
101
+ * Given the sending of each email, which runs after the visitor has their answer. Tests wait on it; a server
102
+ * that may stop between requests can keep itself alive with it.
103
+ */
104
+ background?: (work: Promise<void>) => void;
105
+ /** The emails the site writes itself (`src/emails.ts`), asked for at each message so a change shows at once. */
106
+ emails?: () => SiteEmails | null | undefined | Promise<SiteEmails | null | undefined>;
107
+ /** The challenge every submission must pass, when the config sets one (`forms.captcha`). */
108
+ captcha?: CaptchaCheck | undefined;
109
+ /** How the provider is asked about a challenge; tests give their own. */
110
+ fetch?: typeof fetch;
111
+ /**
112
+ * Where visitors' files are kept (`resolveFormFiles`). Without it the site has no private place for them, and a
113
+ * message that carries files is refused.
114
+ */
115
+ files?: PrivateFiles | undefined;
116
+ /** The site's name (`identity.name`), the sender's name of a confirmation when Site Settings gives none. */
117
+ siteName?: string | undefined;
118
+ /**
119
+ * The site's public address (Astro's `site`), for the links in emails. Never taken from the request alone: whoever
120
+ * sends a message writes its Host header, and the email goes to someone else.
121
+ */
122
+ siteUrl?: string | undefined;
123
+ }
124
+
125
+ export function createFormsHandler(brim: Brim, options: FormsOptions = {}): FormsHandler {
126
+ const limiter = new RateLimiter(brim.db);
127
+ const mailSettings = new MailSettingsStore(brim.db);
128
+ const fileStore = options.files && new FormFiles(options.files, () => brim.forms.secret());
129
+
130
+ let missingAddressLogged = false;
131
+
132
+ /** The site's address and name for an email. Without an address the email has no links (see `trustedOrigin`). */
133
+ function sender(request: Request): { origin: string | undefined; site: string } {
134
+ const origin = trustedOrigin(request, options.siteUrl);
135
+ if (!origin && !missingAddressLogged) {
136
+ missingAddressLogged = true;
137
+ console.warn("[brim] Emails about forms have no links: set `site` in astro.config.mjs to the site's address.");
138
+ }
139
+ return { origin, site: origin ? new URL(origin).host : options.siteName || "the site" };
140
+ }
141
+
142
+ /** Emails the message to whoever should hear about it. A failure is logged: the message is saved either way. */
143
+ async function notify(
144
+ request: Request,
145
+ spec: FormSpec,
146
+ answers: FormAnswer[],
147
+ id: string,
148
+ kept: FormFile[],
149
+ ): Promise<void> {
150
+ const { mailer } = options;
151
+ if (!mailer) return;
152
+ const settings = await mailSettings.get();
153
+ if (mailer.delivery(settings) === "none") return;
154
+ const notifyAlso = spec.notify ? openAddress(await brim.forms.secret(), spec.notify) : undefined;
155
+ const to = await formRecipients(settings, brim.accounts, notifyAlso);
156
+ if (to.length === 0) return;
157
+ const { origin, site } = sender(request);
158
+ const page = origin && formPage(spec.form);
159
+ // Where the editor's API hands each file to a signed-in owner or editor; the email never carries the file.
160
+ const files = kept.map(({ id: fileId, label, name, size }) => ({
161
+ label,
162
+ name,
163
+ size,
164
+ url: origin ? `${origin}/admin/api/responses/${id}/files/${fileId}` : "",
165
+ }));
166
+ const email: FormEmail = {
167
+ form: spec.title,
168
+ site,
169
+ siteUrl: origin ?? "",
170
+ ...(page && { page: `${origin}${page}` }),
171
+ answers: answers.map(({ label, value }) => ({ label, value })),
172
+ ...(files.length > 0 && { files }),
173
+ responsesUrl: origin ? `${origin}/admin/edit` : "",
174
+ responseUrl: origin ? `${origin}/admin/edit?response=${encodeURIComponent(id)}` : "",
175
+ sentAt: new Date(),
176
+ };
177
+ const message = formNotice({
178
+ site: email.site,
179
+ title: email.form,
180
+ answers,
181
+ ...(email.page && { page: email.page }),
182
+ responsesUrl: email.responsesUrl,
183
+ responseUrl: email.responseUrl,
184
+ files,
185
+ settings,
186
+ to,
187
+ });
188
+ const template = (await Promise.resolve(options.emails?.()).catch(() => undefined))?.form;
189
+ await mailer.send(settings, await writtenBySite(message, template, { ...email, replyTo: message.replyTo }));
190
+ }
191
+
192
+ /**
193
+ * Emails the visitor that their message arrived, when the form's owner turned that on. Called only for a message
194
+ * that passed every check and was kept. One email, to the one address the form's chosen email field holds, in the
195
+ * words the owner wrote; within the limits above, or not at all. Nothing here can fail the visitor's sending.
196
+ */
197
+ async function confirm(request: Request, spec: FormSpec, given: Given[], clientAddress: string): Promise<void> {
198
+ const { mailer } = options;
199
+ const wanted = spec.confirm;
200
+ if (!mailer || !wanted) return;
201
+ // Only a field the form's author made an email field, whose value was checked as one address, names a recipient.
202
+ const field = spec.fields.find((candidate) => candidate.name === wanted.field && candidate.type === "email");
203
+ const to = field && given.find((answer) => answer.name === field.name)?.value.toLowerCase();
204
+ if (!to || !isEmail(to)) return;
205
+ const settings = await mailSettings.get();
206
+ if (mailer.delivery(settings) === "none") return;
207
+
208
+ // The address is counted by its hash: the table of limits never holds visitors' addresses.
209
+ const address = createHash("sha256").update(to).digest("hex").slice(0, 32);
210
+ const within = async (key: string, { limit, windowSeconds }: { limit: number; windowSeconds: number }) =>
211
+ limiter.allow(key, limit, windowSeconds);
212
+ if (
213
+ !(await within(`form-confirm:visitor:${clientAddress}`, CONFIRMATIONS_PER_VISITOR)) ||
214
+ !(await within(`form-confirm:to:${address}`, CONFIRMATIONS_PER_ADDRESS)) ||
215
+ !(await within("form-confirm:site", CONFIRMATIONS_PER_SITE))
216
+ ) {
217
+ console.warn("[brim] A confirmation email was not sent: its daily limit was reached.");
218
+ return;
219
+ }
220
+
221
+ const { origin, site } = sender(request);
222
+ const page = origin && formPage(spec.form);
223
+ const answers =
224
+ wanted.answers === true ? confirmationAnswers(given.map(({ label, value }) => ({ label, value }))) : [];
225
+ // "Reply" goes to the site: the form's own notification address, else the first of Site Settings'. Never to
226
+ // anything a visitor wrote.
227
+ const notifyAlso = spec.notify ? openAddress(await brim.forms.secret(), spec.notify) : undefined;
228
+ const replyTo = [...splitAddresses(notifyAlso ?? ""), ...settings.notify].find(isEmail);
229
+ const email: ConfirmationEmail = {
230
+ form: spec.title,
231
+ site,
232
+ siteUrl: origin ?? "",
233
+ ...(page && { page: `${origin}${page}` }),
234
+ subject: String(wanted.subject ?? "").slice(0, CONFIRMATION_SUBJECT_LENGTH),
235
+ message: String(wanted.message ?? "").slice(0, CONFIRMATION_MESSAGE_LENGTH),
236
+ answers,
237
+ sentAt: new Date(),
238
+ };
239
+ const message = confirmationNotice({
240
+ site,
241
+ subject: email.subject,
242
+ message: email.message,
243
+ answers,
244
+ replyTo,
245
+ // The email is the site's: its sender is the site's name, whichever server carries it.
246
+ settings: { ...settings, senderName: settings.senderName || options.siteName || "" },
247
+ to,
248
+ });
249
+ const template = (await Promise.resolve(options.emails?.()).catch(() => undefined))?.confirmation;
250
+ const written = await writtenBySite(message, template, email);
251
+ // A template writes the words and the look; who it goes to and where replies go are not its to change.
252
+ await mailer.send(settings, { ...written, to: [to], replyTo });
253
+ }
254
+
255
+ async function token(info: { clientAddress: string }): Promise<Response> {
256
+ const { limit, windowSeconds } = TOKENS_PER_VISITOR;
257
+ if (!(await limiter.allow(`form-token:${info.clientAddress}`, limit, windowSeconds))) {
258
+ throw new HttpError(429, "Too many requests. Try again in a few minutes.");
259
+ }
260
+ // `work`: how many zero bits the page's script finds after the token before it sends (./work.ts). It is part of
261
+ // what the token signs, so a script cannot ask for less.
262
+ const work = workBits(await recentAttempts());
263
+ const payload = `${Date.now()}.${randomBytes(12).toString("base64url")}.${work}`;
264
+ return json({ token: `${payload}.${sign(await brim.forms.secret(), payload)}`, work });
265
+ }
266
+
267
+ /** The ten-minute window a message tried now counts in; each has its own key, so the one before stays readable. */
268
+ const attemptsKey = (offset = 0) => `form:attempts:${Math.floor(Date.now() / 1000 / WORK_WINDOW_SECONDS) - offset}`;
269
+
270
+ /**
271
+ * A message tried counts towards the work new tokens ask for, sent or refused, once its token is good, and only so
272
+ * many from one address: otherwise one person, at no cost, could have every visitor's browser work harder.
273
+ */
274
+ async function countAttempt(clientAddress: string): Promise<void> {
275
+ const { limit, windowSeconds } = PER_VISITOR;
276
+ if (!(await limiter.allow(`form-attempts:${clientAddress}`, limit, windowSeconds))) return;
277
+ await limiter.allow(attemptsKey(), Number.MAX_SAFE_INTEGER, WORK_WINDOW_SECONDS);
278
+ }
279
+
280
+ /** Messages tried on the whole site lately: this window or the one before, whichever saw more. */
281
+ async function recentAttempts(): Promise<number> {
282
+ return Math.max(await limiter.count(attemptsKey()), await limiter.count(attemptsKey(1)));
283
+ }
284
+
285
+ /** Whether the token is the site's, of the right age and its work done, without using it up; its single-use part. */
286
+ async function readToken(input: unknown, work: unknown): Promise<string> {
287
+ const [issuedAt, nonce, bits, signature] = typeof input === "string" ? input.split(".") : [];
288
+ const secret = await brim.forms.secret();
289
+ if (!issuedAt || !nonce || !bits || !signature || !isSigned(secret, `${issuedAt}.${nonce}.${bits}`, signature)) {
290
+ throw new HttpError(400, "This form has expired. Reload the page and try again.");
291
+ }
292
+ const age = Date.now() - Number(issuedAt);
293
+ if (age > TOKEN_LIFETIME_MS) throw new HttpError(400, "This form has expired. Reload the page and try again.");
294
+ if (age < MIN_FILL_MS) throw new HttpError(429, "That was very fast. Wait a moment and send again.");
295
+ if (!workDone(input as string, work, Number(bits)))
296
+ throw new HttpError(400, "This form has expired. Reload the page and try again.");
297
+ return nonce;
298
+ }
299
+
300
+ async function checkToken(input: unknown, work: unknown): Promise<void> {
301
+ const nonce = await readToken(input, work);
302
+ // Counting the token as a rate-limit key makes it usable exactly once.
303
+ if (!(await limiter.allow(`form-used:${nonce}`, 1, TOKEN_LIFETIME_MS / 1000))) {
304
+ throw new HttpError(400, "This form was already sent. Reload the page to send another.");
305
+ }
306
+ }
307
+
308
+ let missingSecretLogged = false;
309
+
310
+ /** The challenge's answer, checked with its provider. Without the secret key nothing is sent unchecked. */
311
+ async function checkCaptcha(check: CaptchaCheck, answer: unknown, clientAddress: string): Promise<void> {
312
+ if (!check.secret) {
313
+ if (!missingSecretLogged) {
314
+ missingSecretLogged = true;
315
+ console.error(
316
+ `[brim] Forms ask for ${check.provider}, but BRIM_CAPTCHA_SECRET is not set: no form can be sent.`,
317
+ );
318
+ }
319
+ throw new HttpError(503, "This form cannot be sent right now. Please try again later.");
320
+ }
321
+ if (typeof answer !== "string" || answer === "" || answer.length > 4096) {
322
+ throw new HttpError(400, "Please complete the check before sending.");
323
+ }
324
+ if (!(await verifyCaptcha({ ...check, secret: check.secret }, answer, clientAddress, options.fetch))) {
325
+ throw new HttpError(400, "The check did not pass. Please try again.");
326
+ }
327
+ }
328
+
329
+ /**
330
+ * A message that carries files, sent as `multipart/form-data`. Its token comes in a header and is checked first,
331
+ * with the visitor's limit on such messages, so nothing is read from someone who could not send anyway; then the
332
+ * body is read up to the most a message may weigh and refused the moment it is larger.
333
+ */
334
+ async function readMultipart(request: Request, clientAddress: string): Promise<Submission> {
335
+ const token = request.headers.get(TOKEN_HEADER);
336
+ const work = Number(request.headers.get(WORK_HEADER) ?? Number.NaN);
337
+ await readToken(token, work);
338
+ const { limit, windowSeconds } = UPLOADS_PER_VISITOR;
339
+ if (!(await limiter.allow(`form-upload:${clientAddress}`, limit, windowSeconds))) {
340
+ throw new HttpError(429, "Too many messages. Try again later.");
341
+ }
342
+ const bytes = await readBytes(
343
+ request,
344
+ MAX_MESSAGE_BYTES + MAX_FIELDS_BYTES,
345
+ `The files are too large: at most ${fileSize(MAX_MESSAGE_BYTES)} in one message.`,
346
+ );
347
+ let data: FormData;
348
+ try {
349
+ data = await new Response(bytes, {
350
+ headers: { "content-type": request.headers.get("content-type") ?? "" },
351
+ }).formData();
352
+ } catch {
353
+ throw new HttpError(400, "The form could not be read.");
354
+ }
355
+ const text = (name: string): string | undefined => {
356
+ const value = data.getAll(name).find((entry) => typeof entry === "string");
357
+ return typeof value === "string" ? value : undefined;
358
+ };
359
+ let values: unknown;
360
+ try {
361
+ values = JSON.parse(text("values") ?? "{}");
362
+ } catch {
363
+ throw new HttpError(400, "The form could not be read.");
364
+ }
365
+ return {
366
+ body: {
367
+ spec: text("spec"),
368
+ signature: text("signature"),
369
+ token,
370
+ work,
371
+ trap: text("trap"),
372
+ consent: text("consent") === "true",
373
+ captcha: text("captcha"),
374
+ values,
375
+ },
376
+ // A file input left empty still sends a part, with no name and no bytes.
377
+ files: (name) =>
378
+ data
379
+ .getAll(name)
380
+ .filter((entry): entry is File => typeof entry !== "string" && (entry.size > 0 || entry.name !== "")),
381
+ };
382
+ }
383
+
384
+ /**
385
+ * The files of a message, checked against the form's file fields: how many, how large, and what each one is by
386
+ * its own bytes. Files sent under any other name are never looked at, and nothing is stored here.
387
+ */
388
+ async function attached(spec: FormSpec, sent: Submission["files"], input: unknown): Promise<Attached[]> {
389
+ const values = typeof input === "object" && input !== null ? (input as Record<string, unknown>) : {};
390
+ const all: Attached[] = [];
391
+ for (const field of spec.fields) {
392
+ // A file field asked only after another answer is not checked, nor are its files kept, when it was not asked.
393
+ if (field.type !== "file" || !fieldShown(field, values)) continue;
394
+ const files = sent(field.name);
395
+ if (files.length === 0) {
396
+ if (field.required) throw new ValidationError(`"${field.label}" is required.`);
397
+ continue;
398
+ }
399
+ if (files.length > (field.multiple ? MAX_FILES : 1)) {
400
+ throw new ValidationError(
401
+ field.multiple ? `"${field.label}" takes at most ${MAX_FILES} files.` : `"${field.label}" takes one file.`,
402
+ );
403
+ }
404
+ // What the field takes is read again from the signed form, so only Brim's own kinds can ever be named.
405
+ const accept = fileTypes(field.accept);
406
+ for (const file of files) {
407
+ if (file.size === 0) throw new ValidationError(`"${field.label}": the file is empty.`);
408
+ if (file.size > MAX_FILE_BYTES) {
409
+ throw new ValidationError(`"${field.label}": a file is larger than ${fileSize(MAX_FILE_BYTES)}.`);
410
+ }
411
+ const bytes = new Uint8Array(await file.arrayBuffer());
412
+ const type = sniffFileType(bytes);
413
+ if (!type || !accept.includes(type)) {
414
+ throw new ValidationError(
415
+ `"${field.label}" takes only ${accept.map((key) => FILE_TYPES[key].label).join(", ")} files.`,
416
+ );
417
+ }
418
+ all.push({ label: field.label, name: safeFileName(file.name, type), type, bytes });
419
+ }
420
+ }
421
+ if (all.length > MAX_FILES) throw new ValidationError(`A message takes at most ${MAX_FILES} files.`);
422
+ if (all.reduce((sum, file) => sum + file.bytes.byteLength, 0) > MAX_MESSAGE_BYTES) {
423
+ throw new ValidationError(`The files are too large: at most ${fileSize(MAX_MESSAGE_BYTES)} in one message.`);
424
+ }
425
+ return all;
426
+ }
427
+
428
+ /** Stores the files of an accepted message under its id. If one cannot be kept, none is. */
429
+ async function keep(id: string, files: Attached[]): Promise<FormFile[]> {
430
+ if (files.length === 0) return [];
431
+ if (!fileStore) throw new HttpError(501, "Files cannot be sent through this form.");
432
+ const kept: FormFile[] = [];
433
+ try {
434
+ for (const file of files) {
435
+ const fileId = randomUUID();
436
+ await fileStore.write(id, fileId, file.bytes);
437
+ kept.push({
438
+ id: fileId,
439
+ label: file.label,
440
+ name: file.name,
441
+ mime: FILE_TYPES[file.type].mime,
442
+ size: file.bytes.byteLength,
443
+ });
444
+ }
445
+ } catch (error) {
446
+ console.error("[brim] A form's files were not kept:", error instanceof Error ? error.message : error);
447
+ await fileStore.remove(id, kept);
448
+ throw new HttpError(503, "The files could not be kept. Please try again later.");
449
+ }
450
+ return kept;
451
+ }
452
+
453
+ async function submit(request: Request, info: { clientAddress: string }): Promise<Response> {
454
+ assertSameOrigin(request);
455
+ const multipart = request.headers.get("content-type")?.startsWith("multipart/form-data") === true;
456
+ const { body, files: sent }: Submission = multipart
457
+ ? await readMultipart(request, info.clientAddress)
458
+ : { body: await readJson(request), files: () => [] };
459
+
460
+ const secret = await brim.forms.secret();
461
+ if (
462
+ typeof body.spec !== "string" ||
463
+ typeof body.signature !== "string" ||
464
+ !isSigned(secret, body.spec, body.signature)
465
+ ) {
466
+ throw new HttpError(400, "This form is not one of this site's forms.");
467
+ }
468
+ const spec = decodeSpec(body.spec);
469
+
470
+ // A filled trap field means a script. It is told all went well, so it learns nothing: nothing is kept (no
471
+ // message, no file) and no email leaves, to the owner or to the address it wrote.
472
+ if (typeof body.trap === "string" && body.trap !== "") return json({ ok: true });
473
+
474
+ await checkToken(body.token, body.work);
475
+ await countAttempt(info.clientAddress);
476
+ if (options.captcha) await checkCaptcha(options.captcha, body.captcha, info.clientAddress);
477
+ const allowed =
478
+ (await limiter.allow(`form:${spec.form}:${info.clientAddress}`, PER_VISITOR.limit, PER_VISITOR.windowSeconds)) &&
479
+ (await limiter.allow("form:site-kept", KEPT_PER_SITE.limit, KEPT_PER_SITE.windowSeconds));
480
+ if (!allowed) throw new HttpError(429, "Too many messages. Try again later.");
481
+
482
+ if (spec.consentRequired && body.consent !== true) throw new ValidationError("Please agree before sending.");
483
+ const given = answers(spec, body.values);
484
+ const files = await attached(spec, sent, body.values);
485
+ const size = files.reduce((sum, file) => sum + file.bytes.byteLength, 0);
486
+ if (size > 0) {
487
+ if (!fileStore) throw new HttpError(501, "Files cannot be sent through this form.");
488
+ const within =
489
+ (await limiter.add(
490
+ `form-files:${info.clientAddress}`,
491
+ size,
492
+ FILE_BYTES_PER_VISITOR.limit,
493
+ FILE_BYTES_PER_VISITOR.windowSeconds,
494
+ )) &&
495
+ (await limiter.add("form-files:site", size, FILE_BYTES_PER_SITE.limit, FILE_BYTES_PER_SITE.windowSeconds));
496
+ if (!within) throw new HttpError(429, "Too many files today. Try again tomorrow.");
497
+ }
498
+
499
+ // Everything held: only now is anything written. The files first, under the message's id, then the message
500
+ // that lists them; if the message cannot be kept, its files go again.
501
+ const id = randomUUID();
502
+ const kept = await keep(id, files);
503
+ const saved = given.map(({ name: _name, ...answer }): FormAnswer => answer);
504
+ try {
505
+ await brim.forms.save(spec.form, spec.title, saved, kept, id);
506
+ } catch (error) {
507
+ await fileStore?.remove(id, kept);
508
+ throw error;
509
+ }
510
+
511
+ if (await limiter.allow("form:site-emails", EMAILS_PER_SITE.limit, EMAILS_PER_SITE.windowSeconds)) {
512
+ const sending = notify(request, spec, saved, id, kept).catch((error: unknown) => {
513
+ console.error(
514
+ "[brim] The email about a form message was not sent:",
515
+ error instanceof Error ? error.message : error,
516
+ );
517
+ });
518
+ options.background?.(sending);
519
+ } else {
520
+ console.warn("[brim] A form message was kept but not emailed: the site sent its emails for today.");
521
+ }
522
+ if (spec.confirm) {
523
+ const confirming = confirm(request, spec, given, info.clientAddress).catch((error: unknown) => {
524
+ console.error("[brim] A confirmation email was not sent:", error instanceof Error ? error.message : error);
525
+ });
526
+ options.background?.(confirming);
527
+ }
528
+ return json({ ok: true });
529
+ }
530
+
531
+ return async (request, info) => {
532
+ const { pathname } = new URL(request.url);
533
+ if (!pathname.startsWith(`${FORMS_PATH}/`)) return undefined;
534
+ try {
535
+ if (request.method === "GET" && pathname === `${FORMS_PATH}/token`) return await token(info);
536
+ if (request.method === "POST" && pathname === `${FORMS_PATH}/submit`) return await submit(request, info);
537
+ throw new HttpError(404, "Not found.");
538
+ } catch (error) {
539
+ if (error instanceof HttpError) return json({ error: error.message }, { status: error.status });
540
+ if (error instanceof ValidationError) return json({ error: error.message }, { status: 422 });
541
+ throw error;
542
+ }
543
+ };
544
+ }
545
+
546
+ /** A message as it was sent: its fields, and the files sent under a field's name (none in a JSON message). */
547
+ interface Submission {
548
+ body: Record<string, unknown>;
549
+ files: (name: string) => File[];
550
+ }
551
+
552
+ /** An answer with the name of its field, which says whether it is the one a confirmation goes to. */
553
+ type Given = FormAnswer & { name: string };
554
+
555
+ /** A file that passed its checks, not stored yet. */
556
+ interface Attached {
557
+ label: string;
558
+ name: string;
559
+ type: FileType;
560
+ bytes: Uint8Array;
561
+ }
562
+
563
+ /** Checks each value against its field and keeps only values of fields the form has. Files are checked apart. */
564
+ function answers(spec: FormSpec, input: unknown): Given[] {
565
+ const values = typeof input === "object" && input !== null ? (input as Record<string, unknown>) : {};
566
+ return spec.fields.flatMap((field) => {
567
+ if (field.type === "file") return [];
568
+ // A field asked only after another answer is not checked, nor kept, when that answer was not given.
569
+ if (!fieldShown(field, values)) return [];
570
+ const value = answer(field, values[field.name]);
571
+ if (value === "") return [];
572
+ if (!field.options?.length || !CHOICE_TYPES.includes(field.type)) return [{ name: field.name, label: field.label, value }];
573
+ // Taken from what was sent, never from the joined text: a choice's own words may hold a comma.
574
+ const sent = values[field.name];
575
+ const picked =
576
+ field.type === "checkboxes" && Array.isArray(sent)
577
+ ? [...new Set(sent.filter((item): item is string => typeof item === "string").map((item) => item.trim()))]
578
+ : [value];
579
+ const offered: FormChoice[] = field.choices ?? field.options.map((label) => ({ label }));
580
+ const choices = offered.map(({ label, icon, image }) => ({
581
+ label,
582
+ ...(icon && { icon }),
583
+ ...(image && { image }),
584
+ }));
585
+ return [{ name: field.name, label: field.label, value, choices, picked }];
586
+ });
587
+ }
588
+
589
+ function answer(field: FormField, input: unknown): string {
590
+ if (field.type === "checkbox") {
591
+ if (field.required && input !== true) throw new ValidationError(`"${field.label}" is required.`);
592
+ return input === true ? "Yes" : "";
593
+ }
594
+
595
+ if (field.type === "checkboxes") {
596
+ // Several choices, each one of the options, kept as one answer.
597
+ const picked = (Array.isArray(input) ? input : []).filter((item): item is string => typeof item === "string");
598
+ const unique = [...new Set(picked.map((item) => item.trim()).filter(Boolean))];
599
+ if (unique.some((item) => !field.options?.includes(item)))
600
+ throw new ValidationError(`"${field.label}" is not one of the choices.`);
601
+ if (unique.length === 0 && field.required) throw new ValidationError(`"${field.label}" is required.`);
602
+ return unique.join(", ");
603
+ }
604
+
605
+ const value = typeof input === "string" ? input.trim() : "";
606
+ if (value === "") {
607
+ if (field.required) throw new ValidationError(`"${field.label}" is required.`);
608
+ return "";
609
+ }
610
+ if (value.length > (MAX_LENGTH[field.type] ?? DEFAULT_MAX_LENGTH))
611
+ throw new ValidationError(`"${field.label}" is too long.`);
612
+ if (field.type === "email" && !EMAIL.test(value))
613
+ throw new ValidationError(`"${field.label}" must be an email address.`);
614
+ if (field.type === "number" && !Number.isFinite(Number(value)))
615
+ throw new ValidationError(`"${field.label}" must be a number.`);
616
+ if (field.type === "url" && !/^https?:\/\//i.test(value))
617
+ throw new ValidationError(`"${field.label}" must be a web address.`);
618
+ if ((field.type === "select" || field.type === "radio") && !field.options?.includes(value)) {
619
+ throw new ValidationError(`"${field.label}" is not one of the choices.`);
620
+ }
621
+ return value;
622
+ }