@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,272 @@
1
+ import type { Accounts, Role } from "../auth/accounts.ts";
2
+ import type { FormAnswer } from "../forms/store.ts";
3
+ import { fileSize } from "../forms/files.ts";
4
+ import type { MailMessage } from "./mailer.ts";
5
+ import type { AccountEmail } from "./templates.ts";
6
+ import { type MailSettings, isEmail, splitAddresses } from "./settings.ts";
7
+
8
+ const MAX_RECIPIENTS = 10;
9
+
10
+ /**
11
+ * Who hears about a form message: every user of the roles Site Settings chose (owners by default, editors too when
12
+ * asked), Site Settings' addresses and the form's own.
13
+ */
14
+ export async function formRecipients(
15
+ settings: MailSettings,
16
+ accounts: Accounts,
17
+ formNotify: string | undefined,
18
+ ): Promise<string[]> {
19
+ const users =
20
+ settings.notifyRoles.length > 0
21
+ ? (await accounts.listUsers())
22
+ .filter((user) => settings.notifyRoles.includes(user.role))
23
+ .map((user) => user.email)
24
+ : [];
25
+ const all = [...users, ...settings.notify, ...splitAddresses(formNotify ?? "")];
26
+ return [...new Set(all.map((address) => address.toLowerCase()))].filter(isEmail).slice(0, MAX_RECIPIENTS);
27
+ }
28
+
29
+ /** The email the owner gets for one form message: every answer, and "Reply" goes to the visitor. */
30
+ export function formNotice(input: {
31
+ site: string;
32
+ title: string;
33
+ answers: FormAnswer[];
34
+ /** Where the editor lists the messages; "" when the site's address is not known, as for the other addresses. */
35
+ responsesUrl: string;
36
+ /** Where the editor opens this message. */
37
+ responseUrl?: string;
38
+ /** The page the form was sent from, e.g. the product an order form is about. */
39
+ page?: string;
40
+ /**
41
+ * The files the visitor attached, each with where a signed-in owner or editor downloads it. They are never
42
+ * attached to the email: an inbox is not a place to open a stranger's file, and the link asks who is asking.
43
+ */
44
+ files?: NoticeFile[];
45
+ settings: MailSettings;
46
+ to: string[];
47
+ }): MailMessage {
48
+ const { site, title, answers, responsesUrl, responseUrl, page, settings, to, files = [] } = input;
49
+ const replyTo = answers.map((answer) => answer.value).find((value) => isEmail(value));
50
+ const subject = `New message from ${title} on ${site}`.replace(/[\r\n]+/g, " ");
51
+ const text = [
52
+ `Someone wrote through "${title}" on ${site}.`,
53
+ ...(page ? [`Sent from: ${page}`] : []),
54
+ "",
55
+ ...answers.flatMap((answer) => [`${answer.label}:`, answer.value, ""]),
56
+ ...files.flatMap((file) => [
57
+ `${file.label}:`,
58
+ `${file.name} (${fileSize(file.size)})${file.url ? `: ${file.url}` : ""}`,
59
+ "",
60
+ ]),
61
+ ...(files.length > 0 ? ["Files open only for someone signed in to the editor who may read messages.", ""] : []),
62
+ replyTo ? `Reply to this email to answer ${replyTo}.` : "",
63
+ ...(responseUrl ? [`Open it in the editor: ${responseUrl}`] : []),
64
+ responsesUrl ? `All messages: ${responsesUrl}` : "Read it in the site's editor.",
65
+ ].join("\n");
66
+ const rows = answers
67
+ .map(
68
+ (answer) =>
69
+ `<tr><td style="padding:8px 12px 8px 0;color:#666;vertical-align:top;white-space:nowrap">${escape(answer.label)}</td>` +
70
+ `<td style="padding:8px 0;white-space:pre-wrap">${escape(answer.value)}</td></tr>`,
71
+ )
72
+ .join("");
73
+ const fileRows = files
74
+ .map(
75
+ (file) =>
76
+ `<tr><td style="padding:8px 12px 8px 0;color:#666;vertical-align:top;white-space:nowrap">${escape(file.label)}</td>` +
77
+ `<td style="padding:8px 0">${file.url ? `<a href="${escape(file.url)}" style="color:#111">${escape(file.name)}</a>` : escape(file.name)} (${escape(fileSize(file.size))})</td></tr>`,
78
+ )
79
+ .join("");
80
+ const html =
81
+ `<div style="font-family:system-ui,-apple-system,Segoe UI,sans-serif;font-size:15px;line-height:1.5;color:#111;max-width:560px">` +
82
+ `<p>Someone wrote through <strong>${escape(title)}</strong> on ${escape(site)}.</p>` +
83
+ (page ? `<p>Sent from <a href="${escape(page)}" style="color:#111">${escape(page)}</a></p>` : "") +
84
+ `<table style="border-collapse:collapse;margin:16px 0">${rows}${fileRows}</table>` +
85
+ (files.length > 0
86
+ ? `<p style="color:#666">Files open only for someone signed in to the editor who may read messages.</p>`
87
+ : "") +
88
+ (replyTo ? `<p style="color:#666">Reply to this email to answer ${escape(replyTo)}.</p>` : "") +
89
+ (responseUrl
90
+ ? `<p><a href="${escape(responseUrl)}" style="display:inline-block;padding:10px 18px;border-radius:999px;background:#111;color:#fff;text-decoration:none">Open this message</a></p>`
91
+ : "") +
92
+ (responsesUrl
93
+ ? `<p><a href="${escape(responsesUrl)}" style="color:#111">See all messages</a></p></div>`
94
+ : `<p>Read it in the site's editor.</p></div>`);
95
+ return { to, subject, text, html, replyTo, fromName: settings.senderName || site };
96
+ }
97
+
98
+ /** A file of a message as an email names it: never its bytes, only where the editor hands it over. */
99
+ export interface NoticeFile {
100
+ label: string;
101
+ name: string;
102
+ size: number;
103
+ url: string;
104
+ }
105
+
106
+ /** The most of the owner's message a confirmation carries, and of each answer when the owner asked for them. */
107
+ export const CONFIRMATION_MESSAGE_LENGTH = 5_000;
108
+ export const CONFIRMATION_SUBJECT_LENGTH = 150;
109
+ export const CONFIRMATION_ANSWER_LENGTH = 300;
110
+ export const CONFIRMATION_ANSWERS_LENGTH = 2_000;
111
+
112
+ /**
113
+ * What the visitor answered, as a confirmation may repeat it: text only, each answer and all of them together cut
114
+ * short. The address the confirmation goes to may be someone else's, so the less of a stranger's words it can
115
+ * carry, the less the site is worth to someone who wants it to write to a victim.
116
+ */
117
+ export function confirmationAnswers(answers: FormAnswer[]): FormAnswer[] {
118
+ const kept: FormAnswer[] = [];
119
+ let total = 0;
120
+ for (const { label, value } of answers) {
121
+ const text = value.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "");
122
+ const short = text.length > CONFIRMATION_ANSWER_LENGTH ? `${text.slice(0, CONFIRMATION_ANSWER_LENGTH)}…` : text;
123
+ if (total + short.length > CONFIRMATION_ANSWERS_LENGTH) break;
124
+ total += short.length;
125
+ kept.push({ label, value: short });
126
+ }
127
+ return kept;
128
+ }
129
+
130
+ /**
131
+ * The email a visitor gets once their message was kept: the subject and the words the owner wrote. It says nothing
132
+ * the visitor typed unless the owner asked for the answers, and "Reply" goes to the site, never to an address a
133
+ * visitor gave.
134
+ */
135
+ export function confirmationNotice(input: {
136
+ site: string;
137
+ subject: string;
138
+ message: string;
139
+ /** Present only when the owner asked for them; already shortened (`confirmationAnswers`). */
140
+ answers?: FormAnswer[] | undefined;
141
+ replyTo?: string | undefined;
142
+ settings: MailSettings;
143
+ to: string;
144
+ }): MailMessage {
145
+ const { site, answers = [], replyTo, settings, to } = input;
146
+ const subject = input.subject.trim().slice(0, CONFIRMATION_SUBJECT_LENGTH) || `We received your message (${site})`;
147
+ const message = input.message.trim().slice(0, CONFIRMATION_MESSAGE_LENGTH) || "Thank you. We received your message.";
148
+ const text = [message, "", ...answers.flatMap((answer) => [`${answer.label}:`, answer.value, ""]), site].join("\n");
149
+ const rows = answers
150
+ .map(
151
+ (answer) =>
152
+ `<tr><td style="padding:8px 12px 8px 0;color:#666;vertical-align:top">${escape(answer.label)}</td>` +
153
+ `<td style="padding:8px 0;white-space:pre-wrap">${escape(answer.value)}</td></tr>`,
154
+ )
155
+ .join("");
156
+ const html =
157
+ `<div style="font-family:system-ui,-apple-system,Segoe UI,sans-serif;font-size:15px;line-height:1.5;color:#111;max-width:560px">` +
158
+ `<p style="white-space:pre-wrap">${escape(message)}</p>` +
159
+ (rows ? `<table style="border-collapse:collapse;margin:16px 0">${rows}</table>` : "") +
160
+ `<p style="color:#666">${escape(site)}</p></div>`;
161
+ return { to: [to], subject, text, html, replyTo, fromName: settings.senderName || site };
162
+ }
163
+
164
+ /** A short email that shows the settings work. */
165
+ export function testNotice(site: string, settings: MailSettings, to: string): MailMessage {
166
+ const text = `This is a test from ${site}. Emails from your site's forms will arrive like this one.`;
167
+ return {
168
+ to: [to],
169
+ subject: `Test email from ${site}`,
170
+ text,
171
+ html: `<p style="font-family:system-ui,sans-serif;font-size:15px">${escape(text)}</p>`,
172
+ fromName: settings.senderName || site,
173
+ };
174
+ }
175
+
176
+ /** The "forgot password" email: one link, what it does, how long it works, and what to do if it was not you. */
177
+ export function passwordResetNotice(site: string, settings: MailSettings, to: string, link: string): MailMessage {
178
+ const lines = [
179
+ `Someone asked to set a new password for ${to} on ${site}.`,
180
+ "Open this link within an hour to choose a new one. It works once:",
181
+ link,
182
+ "If it was not you, ignore this email: your password stays as it is.",
183
+ ];
184
+ return {
185
+ to: [to],
186
+ subject: `Set a new password for ${site}`,
187
+ text: lines.join("\n\n"),
188
+ html:
189
+ `<div style="font-family:system-ui,sans-serif;font-size:15px;line-height:1.5">` +
190
+ `<p>${escape(lines[0]!)}</p><p>${escape(lines[1]!)}</p>` +
191
+ `<p><a href="${escape(link)}">Set a new password</a></p>` +
192
+ `<p style="color:#666">${escape(lines[3]!)}</p></div>`,
193
+ fromName: settings.senderName || site,
194
+ };
195
+ }
196
+
197
+ /** What each role allows, in the words the account emails use (see `auth/permissions.ts`). */
198
+ export const ROLE_DESCRIPTIONS: Record<Role, string> = {
199
+ owner: "manage everything: content, pages, settings and users",
200
+ editor: "write, publish, add pages and read the messages sent through the forms",
201
+ };
202
+
203
+ /**
204
+ * Brim's own email for a change to someone's access (`added`, `role`, `reset`): what happened, what they may do now,
205
+ * and how to get in — a link to choose their password, and the host's own sign-in when the site offers it. A site
206
+ * writes its own in `src/emails.ts` (`userAdded`, `roleChanged`, `accessReset`).
207
+ */
208
+ export function accountNotice(email: AccountEmail, settings: MailSettings): MailMessage {
209
+ const { site, role, roleDescription, by, editorUrl, passwordUrl, passwordLinkHours, hostSignIn } = email;
210
+ const who = by && by !== email.email ? by : "An owner of the site";
211
+ const within = passwordLinkHours
212
+ ? passwordLinkHours % 24 === 0
213
+ ? `${passwordLinkHours / 24} day${passwordLinkHours === 24 ? "" : "s"}` // betterleaks:allow
214
+ : `${passwordLinkHours} hour${passwordLinkHours === 1 ? "" : "s"}` // betterleaks:allow
215
+ : "";
216
+ const passwordLine = passwordUrl // betterleaks:allow
217
+ ? `Choose your password to open the editor. The link works once, within ${within}:`
218
+ : "";
219
+ const hostLine = hostSignIn
220
+ ? `You can also sign in with ${hostSignIn.name}: open the editor and choose "Continue with ${hostSignIn.name}", with this same email.`
221
+ : "";
222
+ const content = {
223
+ added: {
224
+ subject: `You can now edit ${site}`,
225
+ intro: `${who} added you to ${site} as ${article(role)} ${role}: you can ${roleDescription}.`,
226
+ button: "Choose your password",
227
+ },
228
+ role: {
229
+ subject: `Your role on ${site} is now ${role}`,
230
+ intro:
231
+ `${who} changed your role on ${site}` +
232
+ (email.previousRole ? ` from ${email.previousRole} to ${role}` : ` to ${role}`) +
233
+ `: you can now ${roleDescription}.`,
234
+ button: "",
235
+ },
236
+ reset: {
237
+ subject: `Your access to ${site} was reset`,
238
+ intro: `${who} reset your access to ${site}: you were signed out everywhere and your old password no longer works.`,
239
+ button: "Choose a new password",
240
+ },
241
+ }[email.kind];
242
+ const subject = content.subject.replace(/[\r\n]+/g, " ");
243
+ const text = [
244
+ content.intro,
245
+ ...(passwordUrl ? [`${passwordLine}\n${passwordUrl}`] : []),
246
+ ...(hostLine ? [hostLine] : []),
247
+ `The editor: ${editorUrl}`,
248
+ ...(email.kind === "reset" ? ["If you did not expect this, reply to whoever runs the site."] : []),
249
+ ].join("\n\n");
250
+ const button = (href: string, label: string) =>
251
+ `<p><a href="${escape(href)}" style="display:inline-block;padding:10px 18px;border-radius:999px;background:#111;color:#fff;text-decoration:none">${escape(label)}</a></p>`;
252
+ const html =
253
+ `<div style="font-family:system-ui,-apple-system,Segoe UI,sans-serif;font-size:15px;line-height:1.5;color:#111;max-width:560px">` +
254
+ `<p>${escape(content.intro)}</p>` +
255
+ (passwordUrl
256
+ ? `<p>${escape(passwordLine)}</p>${button(passwordUrl, content.button)}`
257
+ : button(editorUrl, "Open the editor")) +
258
+ (hostLine ? `<p>${escape(hostLine)}</p>` : "") +
259
+ (passwordUrl
260
+ ? `<p style="color:#666">The editor: <a href="${escape(editorUrl)}" style="color:#111">${escape(editorUrl)}</a></p>`
261
+ : "") +
262
+ `</div>`;
263
+ return { to: [email.email], subject, text, html, fromName: settings.senderName || site };
264
+ }
265
+
266
+ function article(word: string): string {
267
+ return /^[aeiou]/i.test(word) ? "an" : "a";
268
+ }
269
+
270
+ function escape(value: string): string {
271
+ return value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
272
+ }
@@ -0,0 +1,173 @@
1
+ import type { Role } from "../auth/accounts.ts";
2
+ import { ROLES, permissionsOf } from "../auth/permissions.ts";
3
+ import type { Database } from "../db/database.ts";
4
+ import { ValidationError } from "../content/validation-error.ts";
5
+ import { isIP } from "node:net";
6
+ import { isPrivate } from "../server/fetch-image.ts";
7
+
8
+ /** The owner's own SMTP server, set in the editor. Its password is never sent back to the editor. */
9
+ export interface SmtpServer {
10
+ host: string;
11
+ port: number;
12
+ /** TLS from the start (port 465). Otherwise STARTTLS is used when the server offers it. */
13
+ secure: boolean;
14
+ user: string;
15
+ password: string; // betterleaks:allow
16
+ /** The address mail is sent from. */
17
+ from: string;
18
+ }
19
+
20
+ /**
21
+ * The roles whose users can be emailed form messages: those who may read them in the editor.
22
+ */
23
+ export const NOTIFIABLE_ROLES: readonly Role[] = ROLES.filter((role) => permissionsOf(role).includes("responses"));
24
+
25
+ /** The site's email settings, kept in the database and changed in the editor's Site Settings. */
26
+ export interface MailSettings {
27
+ /** The roles whose users all get an email for every form message (owners, editors). */
28
+ notifyRoles: Role[];
29
+ /** More addresses that get every form message. */
30
+ notify: string[];
31
+ /** The name shown as the sender. Empty uses the site's address. */
32
+ senderName: string;
33
+ /** The owner's own server. Without it, the server's email setup sends. */
34
+ smtp: SmtpServer | null;
35
+ }
36
+
37
+ /**
38
+ * What the editor sees: the same, with the password replaced by whether one is saved, and `notifyOwners` for the
39
+ * clients written before roles could be chosen.
40
+ */
41
+ export type MailSettingsView = Omit<MailSettings, "smtp"> & {
42
+ notifyOwners: boolean;
43
+ smtp: (Omit<SmtpServer, "password"> & { hasPassword: boolean }) | null; // betterleaks:allow
44
+ };
45
+
46
+ const KEY = "mail_settings";
47
+ const MAX_RECIPIENTS = 10;
48
+ const EMAIL = /^[^\s@<>,;]+@[^\s@<>,;]+\.[^\s@<>,;]+$/;
49
+
50
+ export const DEFAULT_MAIL_SETTINGS: MailSettings = { notifyRoles: ["owner"], notify: [], senderName: "", smtp: null };
51
+
52
+ /** Roles as saved or sent: only those that may be emailed, each once. */
53
+ function notifiable(roles: unknown[]): Role[] {
54
+ return NOTIFIABLE_ROLES.filter((role) => roles.includes(role));
55
+ }
56
+
57
+ /** Settings saved before roles could be chosen said only whether owners were emailed (`notifyOwners`). */
58
+ function fromSaved(saved: Partial<MailSettings> & { notifyOwners?: unknown }): MailSettings {
59
+ const { notifyOwners, ...rest } = saved;
60
+ const notifyRoles = Array.isArray(saved.notifyRoles)
61
+ ? notifiable(saved.notifyRoles)
62
+ : notifyOwners === false
63
+ ? []
64
+ : ["owner" as const];
65
+ return { ...DEFAULT_MAIL_SETTINGS, ...rest, notifyRoles };
66
+ }
67
+
68
+ export function isEmail(value: string): boolean {
69
+ return EMAIL.test(value) && value.length <= 254;
70
+ }
71
+
72
+ export class MailSettingsStore {
73
+ readonly #db: Database;
74
+
75
+ constructor(db: Database) {
76
+ this.#db = db;
77
+ }
78
+
79
+ async get(): Promise<MailSettings> {
80
+ const rows = await this.#db.query("SELECT value FROM brim_meta WHERE key = ?", [KEY]);
81
+ if (!rows[0]) return { ...DEFAULT_MAIL_SETTINGS };
82
+ try {
83
+ return fromSaved(JSON.parse(String(rows[0].value)) as Partial<MailSettings>);
84
+ } catch {
85
+ return { ...DEFAULT_MAIL_SETTINGS };
86
+ }
87
+ }
88
+
89
+ async view(): Promise<MailSettingsView> {
90
+ return toView(await this.get());
91
+ }
92
+
93
+ /** Checks and saves what the editor sent. An empty password keeps the saved one. */
94
+ async update(input: Record<string, unknown>): Promise<MailSettingsView> {
95
+ const current = await this.get();
96
+ const next = parseSettings(input, current);
97
+ await this.#db.query(
98
+ "INSERT INTO brim_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
99
+ [KEY, JSON.stringify(next)],
100
+ );
101
+ return toView(next);
102
+ }
103
+ }
104
+
105
+ function toView(settings: MailSettings): MailSettingsView {
106
+ const { smtp, ...settled } = settings;
107
+ const rest = { ...settled, notifyOwners: settings.notifyRoles.includes("owner") };
108
+ if (!smtp) return { ...rest, smtp: null };
109
+ const { password, ...server } = smtp; // betterleaks:allow
110
+ return { ...rest, smtp: { ...server, hasPassword: password !== "" } }; // betterleaks:allow
111
+ }
112
+
113
+ function parseSettings(input: Record<string, unknown>, current: MailSettings): MailSettings {
114
+ const text = (value: unknown, max = 200): string => (typeof value === "string" ? value.trim().slice(0, max) : "");
115
+ const notify = splitAddresses(input.notify);
116
+ for (const address of notify) {
117
+ if (!isEmail(address)) throw new ValidationError(`"${address}" is not an email address.`);
118
+ }
119
+ if (notify.length > MAX_RECIPIENTS) throw new ValidationError(`At most ${MAX_RECIPIENTS} addresses.`);
120
+
121
+ let smtp: SmtpServer | null = null;
122
+ const server = input.smtp;
123
+ if (server && typeof server === "object") {
124
+ const given = server as Record<string, unknown>;
125
+ const host = text(given.host, 253);
126
+ const from = text(given.from, 254);
127
+ const port = Number(given.port || 587);
128
+ if (!host) throw new ValidationError("Write the address of your email server, e.g. smtp.example.com.");
129
+ if (!/^[a-z0-9.-]+$/i.test(host)) throw new ValidationError("The email server's address is not valid.");
130
+ // The site's server connects to it: an owner may not point it at the host's own network. A name is checked
131
+ // again when an email is sent, once it is resolved (see Mailer).
132
+ const lower = host.toLowerCase();
133
+ if (lower === "localhost" || lower.endsWith(".localhost") || !lower.includes(".") || (isIP(lower) && isPrivate(lower))) {
134
+ throw new ValidationError("The email server must be a public address, e.g. smtp.example.com.");
135
+ }
136
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new ValidationError("The port is a number, e.g. 587.");
137
+ if (!isEmail(from)) throw new ValidationError("Write the address emails are sent from.");
138
+ const typed = typeof given.password === "string" ? given.password : ""; // betterleaks:allow
139
+ // The saved password was given for the saved server. It is never sent to another one: whoever changes where
140
+ // mail goes types the password of that place.
141
+ const sameServer = current.smtp?.host.toLowerCase() === host.toLowerCase() && current.smtp.port === port;
142
+ if (typed === "" && current.smtp?.password && !sameServer) {
143
+ throw new ValidationError("Type the password again: the saved one was for the email server you had before.");
144
+ }
145
+ smtp = {
146
+ host,
147
+ port,
148
+ secure: given.secure === true || (given.secure === undefined && port === 465),
149
+ user: text(given.user, 254),
150
+ password: typed !== "" ? typed : (current.smtp?.password ?? ""), // betterleaks:allow
151
+ from,
152
+ };
153
+ }
154
+
155
+ return {
156
+ // The roles as chosen; a client from before roles sends only whether owners are emailed, which keeps the rest.
157
+ notifyRoles: Array.isArray(input.notifyRoles)
158
+ ? notifiable(input.notifyRoles)
159
+ : notifiable([
160
+ ...current.notifyRoles.filter((role) => role !== "owner"),
161
+ ...(input.notifyOwners !== false ? ["owner"] : []),
162
+ ]),
163
+ notify,
164
+ senderName: text(input.senderName, 80).replace(/[\r\n<>"]/g, ""),
165
+ smtp,
166
+ };
167
+ }
168
+
169
+ /** Addresses as a list, or written with commas, semicolons or on separate lines. */
170
+ export function splitAddresses(value: unknown): string[] {
171
+ const parts = Array.isArray(value) ? value.map(String) : typeof value === "string" ? value.split(/[\s,;]+/) : [];
172
+ return [...new Set(parts.map((part) => part.trim().toLowerCase()).filter(Boolean))];
173
+ }
@@ -0,0 +1,191 @@
1
+ import type { Role } from "../auth/accounts.ts";
2
+ import type { MailMessage } from "./mailer.ts";
3
+
4
+ const MARKUP = Symbol("brim-html");
5
+
6
+ /** Markup made with `html`: what it holds is HTML already, every value in it escaped. */
7
+ export interface Html {
8
+ readonly [MARKUP]: string;
9
+ toString(): string;
10
+ }
11
+
12
+ function markup(value: string): Html {
13
+ return { [MARKUP]: value, toString: () => value };
14
+ }
15
+
16
+ function isHtml(value: unknown): value is Html {
17
+ return typeof value === "object" && value !== null && MARKUP in value;
18
+ }
19
+
20
+ function escape(text: string): string {
21
+ return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
22
+ }
23
+
24
+ function piece(value: unknown): string {
25
+ if (value === null || value === undefined || value === false) return "";
26
+ if (isHtml(value)) return value[MARKUP];
27
+ if (Array.isArray(value)) return value.map(piece).join("");
28
+ return escape(String(value));
29
+ }
30
+
31
+ /**
32
+ * Writes an email's HTML: every value put in it is escaped (what a visitor typed can never become markup), and
33
+ * markup made with `html` and lists of it go in as they are.
34
+ *
35
+ * html`<p>${answer.label}: <strong>${answer.value}</strong></p>`
36
+ * html`<table>${email.answers.map((answer) => html`<tr><td>${answer.label}</td><td>${answer.value}</td></tr>`)}</table>`
37
+ */
38
+ export function html(strings: TemplateStringsArray, ...values: unknown[]): Html {
39
+ return markup(
40
+ strings.reduce((written, part, index) => written + part + (index < values.length ? piece(values[index]) : ""), ""),
41
+ );
42
+ }
43
+
44
+ /** Markup of the site's own that is HTML already (a logo's `<svg>`, a shared footer), put in as it is. */
45
+ export function rawHtml(trusted: string): Html {
46
+ return markup(trusted);
47
+ }
48
+
49
+ /** One message sent through a form, as an email template receives it. */
50
+ export interface FormEmail {
51
+ /** The form's title, e.g. "Comandă produs". */
52
+ form: string;
53
+ /**
54
+ * The site's host, e.g. `studionord.ro`, and its address. A site whose address is not set (`site` in the Astro
55
+ * config, or `BRIM_SITE_URL`) has its name as `site`, and every address here is "".
56
+ */
57
+ site: string;
58
+ siteUrl: string;
59
+ /** The page it was sent from, when the form is on one (a product's order form says which product). */
60
+ page?: string | undefined;
61
+ /** Each field the visitor filled in, in the form's order. */
62
+ answers: { label: string; value: string }[];
63
+ /** The visitor's email, when the form asked for it: "Reply" goes there. */
64
+ replyTo?: string | undefined;
65
+ /**
66
+ * The files the visitor attached: their names and where a signed-in owner or editor downloads each. Never the
67
+ * files themselves.
68
+ */
69
+ files?: { label: string; name: string; size: number; url: string }[];
70
+ /** Where the editor lists the messages. */
71
+ responsesUrl: string;
72
+ /** Where the editor opens this very message, its choices shown as the form asked them. */
73
+ responseUrl: string;
74
+ sentAt: Date;
75
+ }
76
+
77
+ /**
78
+ * What happened to someone's access to the site, as an account email's template receives it:
79
+ * - `added`: an owner added them (in a host's dashboard, or through `/admin/api/users`);
80
+ * - `role`: their role changed, from `previousRole` to `role`;
81
+ * - `reset`: an owner reset their access: their old password stopped working and they were signed out everywhere.
82
+ */
83
+ export interface AccountEmail {
84
+ kind: "added" | "role" | "reset";
85
+ /** The site's host, e.g. `studionord.ro`, and its address. */
86
+ site: string;
87
+ siteUrl: string;
88
+ /** Whose access it is: the email goes to them. */
89
+ email: string;
90
+ role: Role;
91
+ /** What the role allows, in a few words ("write, publish, add pages…"). */
92
+ roleDescription: string;
93
+ previousRole?: Role | undefined;
94
+ /** Who did it, when known: the owner signed in, or whose token the host used. */
95
+ by?: string | undefined;
96
+ /** The editor's address: its sign-in form, with the host's own sign-in when there is one. */
97
+ editorUrl: string;
98
+ /**
99
+ * A link to choose their own password, for `added` and `reset`. It works once, within `passwordLinkHours`. The
100
+ * token is in its fragment, so link checkers that open every link in an email cannot use it up.
101
+ */
102
+ passwordUrl?: string | undefined;
103
+ passwordLinkHours?: number | undefined;
104
+ /** The host's own sign-in, when the site offers it beside the password (e.g. "Continue with Brimsites"). */
105
+ hostSignIn?: { name: string; url: string } | undefined;
106
+ sentAt: Date;
107
+ }
108
+
109
+ /** What the `confirmation` template receives: the email a visitor gets once their message was kept. */
110
+ export interface ConfirmationEmail {
111
+ /** The form's title. */
112
+ form: string;
113
+ /** The site's host and its address; its name and "" when its address is not set, as in `FormEmail`. */
114
+ site: string;
115
+ siteUrl: string;
116
+ /** The page the form was sent from, when it is on one. */
117
+ page?: string | undefined;
118
+ /** The subject and the message the owner wrote for this form, in the editor. */
119
+ subject: string;
120
+ message: string;
121
+ /**
122
+ * What the visitor answered, only when the owner turned "Include the answers" on: text, shortened. Empty
123
+ * otherwise, so a template cannot repeat a stranger's words to someone else's address by accident.
124
+ */
125
+ answers: { label: string; value: string }[];
126
+ sentAt: Date;
127
+ }
128
+
129
+ /** What a template gives; anything it leaves out is Brim's own (the text version is made from the answers). */
130
+ export interface EmailContent {
131
+ subject?: string;
132
+ html?: Html;
133
+ text?: string;
134
+ /** The sender's name; the address is whoever sends. */
135
+ fromName?: string;
136
+ }
137
+
138
+ /**
139
+ * The emails a site writes itself, in `src/emails.ts`: `export const emails = defineEmails({ form: (email) => … })`.
140
+ * Without one, or when one fails, Brim sends its own, so no message is lost.
141
+ */
142
+ export interface SiteEmails {
143
+ /** The email the owner gets for a message sent through a form. */
144
+ form?: (email: FormEmail) => EmailContent | Promise<EmailContent>;
145
+ /** The email someone gets when an owner adds them to the site, with how to sign in. */
146
+ userAdded?: AccountTemplate;
147
+ /** The email someone gets when their role changes. */
148
+ roleChanged?: AccountTemplate;
149
+ /** The email someone gets when an owner resets their access, with a link to choose a new password. */
150
+ accessReset?: AccountTemplate;
151
+ /** The email a visitor gets once their message was kept, when the owner turned the form's confirmation on. */
152
+ confirmation?: (email: ConfirmationEmail) => EmailContent | Promise<EmailContent>;
153
+ }
154
+
155
+ export type AccountTemplate = (email: AccountEmail) => EmailContent | Promise<EmailContent>;
156
+
157
+ export function defineEmails(emails: SiteEmails): SiteEmails {
158
+ return emails;
159
+ }
160
+
161
+ /**
162
+ * `message` (Brim's own) as the site's template writes it. A template that throws, or gives nothing usable, leaves
163
+ * Brim's own: the message is sent either way, and the reason is logged.
164
+ */
165
+ export async function writtenBySite<Email>(
166
+ message: MailMessage,
167
+ template: ((email: Email) => EmailContent | Promise<EmailContent>) | undefined,
168
+ email: Email,
169
+ ): Promise<MailMessage> {
170
+ if (!template) return message;
171
+ try {
172
+ const written = await template(email);
173
+ const subject = typeof written?.subject === "string" ? written.subject.replace(/[\r\n]+/g, " ").trim() : "";
174
+ const body =
175
+ written?.html === undefined ? "" : isHtml(written.html) ? written.html[MARKUP] : escape(String(written.html));
176
+ const fromName = typeof written?.fromName === "string" ? written.fromName.replace(/[\r\n]+/g, " ").trim() : "";
177
+ return {
178
+ ...message,
179
+ ...(subject && { subject }),
180
+ ...(body && { html: body }),
181
+ ...(typeof written?.text === "string" && written.text.trim() && { text: written.text }),
182
+ ...(fromName && { fromName }),
183
+ };
184
+ } catch (error) {
185
+ console.error(
186
+ "[brim] The site's email template failed; Brim's own was sent:",
187
+ error instanceof Error ? error.message : error,
188
+ );
189
+ return message;
190
+ }
191
+ }