@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,2106 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHash } from "node:crypto";
3
+ import { readFile } from "node:fs/promises";
4
+ import { type Role, type User, normalizeEmail } from "../auth/accounts.ts";
5
+ import { type Permission, REFUSALS, ROLES, can, permissionsOf } from "../auth/permissions.ts";
6
+ import type { HistoryRecord } from "../content/history.ts";
7
+ import type { DraftTarget, ItemContentDraft, NodeDraft } from "../content/drafts.ts";
8
+ import { type ContentType, isSlug, itemPageOf, slugify, standardField } from "../content/content-types.ts";
9
+ import { isNodeId, normalizePagePath, pageScope, siteScope, typeScope } from "../content/ids.ts";
10
+ import { FIELD_KIND, applyToItem } from "../content/item-fields.ts";
11
+ import { type Item, parseItem } from "../content/items.ts";
12
+ import { type PageTemplate, templateInfo } from "../content/page-templates.ts";
13
+ import { FormFiles, type PrivateFiles, fileDownload } from "../forms/files.ts";
14
+ import { MAX_UPLOAD_BYTES, type MediaFiles, MediaStore } from "../content/media.ts";
15
+ import { blockDefinitions } from "../blocks/schemas/index.ts";
16
+ import { parseSettings } from "../blocks/settings.ts";
17
+ import type { NodeKind, PageRecord, SeoSettings, StoredNode, Visibility } from "../content/types.ts";
18
+ import { ValidationError, parseNodeValue, parseSeo } from "../content/validate.ts";
19
+ import { parseRedirects, redirectsAfterMove } from "../content/redirects.ts";
20
+ import { generatePassword } from "../auth/password.ts";
21
+ import type { Brim } from "../runtime/connect.ts";
22
+ import {
23
+ HttpError,
24
+ assertSameOrigin,
25
+ isLocalHost,
26
+ json,
27
+ publicOrigin,
28
+ readBytes,
29
+ readJson,
30
+ requestOrigin,
31
+ } from "./http.ts";
32
+ import { itemPathSegments } from "../content/item-path.ts";
33
+ import { type LocaleConfig, itemPagePath, localeOfPath, pathInLocale, storedLocale } from "./locales.ts";
34
+ import { RateLimiter } from "./rate-limit.ts";
35
+ import { SESSION_COOKIE, bearerToken, requestUser, sessionCookies } from "./auth.ts";
36
+ import { SCHEMA_VERSION } from "../db/schema.ts";
37
+ import type { QueryRules } from "./query-params.ts";
38
+ import { VERSION } from "../version.ts";
39
+ import { handleMcp } from "../mcp/server.ts";
40
+ import {
41
+ type BrandColor,
42
+ type HostSignIn,
43
+ type SiteIdentity,
44
+ type VideoUploadsOptions,
45
+ faviconType,
46
+ } from "../config.ts";
47
+ import { VideoHost, parseNewVideo } from "./video-host.ts";
48
+ import type { Mailer } from "../mail/mailer.ts";
49
+ import { MailSettingsStore } from "../mail/settings.ts";
50
+ import {
51
+ ROLE_DESCRIPTIONS,
52
+ accountNotice,
53
+ confirmationNotice,
54
+ formNotice,
55
+ passwordResetNotice,
56
+ testNotice,
57
+ } from "../mail/notify.ts";
58
+ import {
59
+ type AccountEmail,
60
+ type ConfirmationEmail,
61
+ type FormEmail,
62
+ type SiteEmails,
63
+ writtenBySite,
64
+ } from "../mail/templates.ts";
65
+ import { formPage } from "../forms/form-page.ts";
66
+ import { IconLibrary } from "../icons/library.ts";
67
+ import type { ToolContext } from "../mcp/tools.ts";
68
+ import { fetchImage } from "./fetch-image.ts";
69
+ import {
70
+ assertTermSlug,
71
+ assertUnused,
72
+ checkReferences,
73
+ isReferenced,
74
+ renameReferences,
75
+ } from "../content/references.ts";
76
+ import { applySeed, exportSeed, planSeed } from "../content/seed.ts";
77
+ import { checkContent } from "../content/content-check.ts";
78
+ import {
79
+ SITE_SETTINGS_NODE,
80
+ type SiteSettings,
81
+ parseSettings as parseSiteSettings,
82
+ settingsAsType,
83
+ settingsValues,
84
+ } from "../content/site-settings.ts";
85
+
86
+ /** A seed comes in one request, so it can be checked whole: a few hundred items with their text (the server takes
87
+ * requests up to a little over 10 MB). */
88
+ const MAX_SEED_BYTES = 10 * 1024 * 1024;
89
+
90
+ export const ADMIN_PATH = "/admin";
91
+ const API_PATH = `${ADMIN_PATH}/api`;
92
+ const MCP_PATH = `${ADMIN_PATH}/mcp`;
93
+ const ASSETS_PATH = `${ADMIN_PATH}/assets`;
94
+ const LOGIN_ATTEMPTS = 10;
95
+ const LOGIN_WINDOW_SECONDS = 15 * 60;
96
+ /** "Forgot password" emails: per address of the asker, and per email asked for (so nobody's inbox is flooded). */
97
+ const RESET_ASKS_PER_ADDRESS = 5;
98
+ const RESET_ASKS_PER_EMAIL = 3;
99
+ const RESET_WINDOW_SECONDS = 60 * 60;
100
+ /** How long the link to choose a password works: in the email of someone just added, and after a reset of access. */
101
+ const WELCOME_LINK_HOURS = 7 * 24;
102
+ const RESET_ACCESS_LINK_HOURS = 24;
103
+ /** Account emails one owner can have sent in an hour, so a script gone wrong cannot flood anyone. */
104
+ const ACCOUNT_EMAILS_PER_HOUR = 30;
105
+ /** Which of the site's templates (`src/emails.ts`) writes each account email. */
106
+ const ACCOUNT_TEMPLATES = { added: "userAdded", role: "roleChanged", reset: "accessReset" } as const;
107
+
108
+ const ASSETS: Record<string, string> = {
109
+ "editor.js": "text/javascript; charset=utf-8",
110
+ "editor.css": "text/css; charset=utf-8",
111
+ };
112
+
113
+ export interface AdminOptions {
114
+ brim: Brim;
115
+ /**
116
+ * The site's public address (Astro's `site`), for links that leave the site in an email, such as a "forgot
117
+ * password" link. Never taken from the request alone: its Host header is the sender's to write.
118
+ */
119
+ siteUrl?: string | undefined;
120
+ /** Astro's i18n setup, when the site is multilingual. */
121
+ locales?: LocaleConfig | undefined;
122
+ /** The site's content types. Asked for on each request, so changes to their declaration show up at once. */
123
+ contentTypes?: () => ContentType[] | Promise<ContentType[]>;
124
+ /** The site's page templates, asked for on each request like the content types. */
125
+ pageTemplates?: () => PageTemplate[] | Promise<PageTemplate[]>;
126
+ /** The site's own settings (`src/site-settings.ts`), or null when it declares none. */
127
+ siteSettings?: () => SiteSettings | null | Promise<SiteSettings | null>;
128
+ /** The emails the site writes itself (`src/emails.ts`), for their preview. */
129
+ emails?: () => SiteEmails | null | undefined | Promise<SiteEmails | null | undefined>;
130
+ /** Where uploaded images are written: the `uploads` folder of the site's public directory. */
131
+ mediaDirectory?: URL;
132
+ /** Where uploads are written when not in `mediaDirectory`: a storage reached over HTTP (`media.storage`). */
133
+ mediaFiles?: MediaFiles | undefined;
134
+ /**
135
+ * Where the files visitors attach to form messages are kept (`resolveFormFiles`): read here for a download,
136
+ * deleted here with their message. Without it the site takes no files.
137
+ */
138
+ formFiles?: PrivateFiles | undefined;
139
+ /** A small copy of an upload for the editor's picker, when the site's CDN makes them; `undefined` otherwise. */
140
+ thumbnail?: ((url: string) => string | undefined) | undefined;
141
+ /** The video host that takes videos uploaded in the editor. Without one, videos are pasted links only. */
142
+ videoUploads?: VideoUploadsOptions | undefined;
143
+ /** A host's own sign-in, offered on the sign-in form beside the password (`BRIM_HOST_SIGN_IN_URL`). */
144
+ hostSignIn?: HostSignIn | undefined;
145
+ /** Sends the site's email; Site Settings shows who sends and can send a test. */
146
+ mailer?: Mailer | undefined;
147
+ /** The icons the editor offers. Without it: Brim's own set. */
148
+ icons?: IconLibrary | undefined;
149
+ /** The brand's colors, offered first in the editor's color pickers. */
150
+ brandColors?: BrandColor[] | undefined;
151
+ /** The site's name and favicon, shown in the editor's tab too. */
152
+ identity?: SiteIdentity | undefined;
153
+ /** How the video host is reached; tests put a fake host here. */
154
+ fetch?: typeof fetch;
155
+ /** Paths of the site's pages, for the editor's page switcher. */
156
+ pages?: () => string[];
157
+ /** Patterns of the dynamic routes in src/pages (`/produse/[category]`), for `brim check --content`. */
158
+ patterns?: () => string[];
159
+ /** Directory holding the built editor (`editor.js`, `editor.css`). */
160
+ assetsDirectory: URL;
161
+ /** Called after content changed, with the pages to rebuild. `undefined` means the whole site. */
162
+ onChange?: (pagePath: string | undefined) => void | Promise<void>;
163
+ /**
164
+ * The HTML of a page as the dev server renders it, for the MCP's page reading.
165
+ * Defaults to fetching the page from the site itself.
166
+ */
167
+ renderPage?: (url: URL) => Promise<string>;
168
+ /**
169
+ * The query parameters each page and route of the site reads (see `QueryRules`), answered in /admin/api/info for
170
+ * a host that keeps pages in a CDN. Without it the site declares nothing and every parameter is kept.
171
+ */
172
+ queryParams?: () => QueryRules | Promise<QueryRules>;
173
+ }
174
+
175
+ /**
176
+ * The header a request that changed what visitors see is answered with (`X-Brim-Changed: live`), so a host that keeps
177
+ * pages in a CDN empties it then, and only then: drafts saved, an item published, a page moved, the redirects or the
178
+ * site's settings changed, a change taken back. Drafts being typed, reads, sign-ins and uploads never carry it. Said
179
+ * in /admin/api/info as the capability `live-change-header`.
180
+ */
181
+ export const LIVE_CHANGE_HEADER = "x-brim-changed";
182
+
183
+ /** Whether the request being answered (an MCP message's tool calls included) changed what visitors see. */
184
+ const liveChanges = new AsyncLocalStorage<{ live: boolean }>();
185
+
186
+ export interface RequestInfo {
187
+ /** Address of the visitor, used only to slow down password guessing. */
188
+ clientAddress: string;
189
+ /**
190
+ * Where this server itself answers, when `request.url` cannot be trusted to say so: the dev server builds that
191
+ * from the `Host` header. Astro's built server already puts only an address it checked in `request.url`.
192
+ */
193
+ serverOrigin?: string | undefined;
194
+ }
195
+
196
+ export type AdminHandler = (request: Request, info: RequestInfo) => Promise<Response | undefined>;
197
+
198
+ /**
199
+ * Everything under `/admin`: the editor's pages, its assets and the protected API.
200
+ * Resolves to `undefined` for any other path, so the caller can serve the site.
201
+ */
202
+ export function createAdminHandler(options: AdminOptions): AdminHandler {
203
+ const {
204
+ brim,
205
+ locales,
206
+ assetsDirectory,
207
+ onChange,
208
+ pages = () => [],
209
+ contentTypes = () => [],
210
+ pageTemplates = () => [],
211
+ siteSettings = () => null,
212
+ } = options;
213
+ const rateLimiter = new RateLimiter(brim.db);
214
+ const mediaFiles = options.mediaFiles ?? options.mediaDirectory;
215
+ const media = mediaFiles ? new MediaStore(brim.db, mediaFiles) : undefined;
216
+
217
+ const formFiles = options.formFiles && new FormFiles(options.formFiles, () => brim.forms.secret());
218
+
219
+ const videos = VideoHost.from(options.videoUploads, options.fetch);
220
+ const mailSettings = new MailSettingsStore(brim.db);
221
+
222
+ /** The signed-in user, when their role allows all of `permissions` (see `auth/permissions.ts`). */
223
+ async function allowed(request: Request, ...permissions: Permission[]): Promise<User> {
224
+ const user = await currentUser(request);
225
+ for (const permission of permissions) need(user, permission);
226
+ return user;
227
+ }
228
+
229
+ function need(user: User, permission: Permission): void {
230
+ if (!can(user, permission)) throw new HttpError(403, REFUSALS[permission]);
231
+ }
232
+
233
+ /**
234
+ * After content changed: the dev server draws the pages again (`onChange`), and a change visitors can see marks
235
+ * the request, which is then answered with `X-Brim-Changed: live`.
236
+ */
237
+ async function changed(pagePath: string | undefined, visible = true): Promise<void> {
238
+ const request = liveChanges.getStore();
239
+ if (visible && request) request.live = true;
240
+ await onChange?.(pagePath);
241
+ }
242
+
243
+ /** What the site's pages read, as /admin/api/info says it; a failure to read it declares nothing. */
244
+ async function queryRules(): Promise<QueryRules> {
245
+ try {
246
+ return (await options.queryParams?.()) ?? {};
247
+ } catch {
248
+ return {};
249
+ }
250
+ }
251
+
252
+ /** Site Settings are the owners' to change. */
253
+ const currentOwner = (request: Request): Promise<User> => allowed(request, "settings");
254
+
255
+ /** Remembers an element's saved value before it changes, so the change can be taken back. */
256
+ async function rememberNode(
257
+ user: User,
258
+ scope: string,
259
+ nodeId: string,
260
+ page: string,
261
+ action: "changed" | "reset",
262
+ always = false,
263
+ ): Promise<void> {
264
+ const saved = (await brim.content.loadNodes([scope])).find((node) => node.nodeId === nodeId);
265
+ if (!saved && action === "reset") return;
266
+ await brim.history.record({
267
+ target: "node",
268
+ key: `${scope}\n${nodeId}`,
269
+ action,
270
+ page,
271
+ title: nodeId,
272
+ before: saved ? { kind: saved.kind, value: saved.value } : null,
273
+ user: user.email,
274
+ always,
275
+ });
276
+ }
277
+
278
+ /** Remembers an item before it changes or is deleted, with what was placed on its own page when it goes. */
279
+ async function rememberItem(
280
+ user: User,
281
+ item: Item,
282
+ action: "changed" | "deleted",
283
+ nodes: StoredNode[] = [],
284
+ always = false,
285
+ translations: string[] = [],
286
+ ): Promise<void> {
287
+ await brim.history.record({
288
+ target: "item",
289
+ key: item.id,
290
+ action,
291
+ page: "",
292
+ title: item.title,
293
+ before: { item, nodes, ...(translations.length > 0 && { translations }) },
294
+ user: user.email,
295
+ always,
296
+ });
297
+ }
298
+
299
+ /** Takes a change back: the content becomes what it was before it. Returns the pages to draw again. */
300
+ async function restore(user: User, record: HistoryRecord): Promise<void> {
301
+ if (record.target === "node") {
302
+ const [scope = "", nodeId = ""] = record.key.split("\n");
303
+ need(user, scope.startsWith("type:") ? "templates" : "content");
304
+ const before = record.before as { kind: string; value: unknown } | null;
305
+ await rememberNode(user, scope, nodeId, record.page, before ? "changed" : "reset", true);
306
+ if (before) await brim.content.saveNode(scope, nodeId, before.kind, before.value);
307
+ else await brim.content.resetNode(scope, nodeId);
308
+ return;
309
+ }
310
+ if (record.target === "item") {
311
+ const {
312
+ item,
313
+ nodes = [],
314
+ translations = [],
315
+ } = record.before as { item: Item; nodes?: StoredNode[]; translations?: string[] };
316
+ const current = await brim.items.get(item.id);
317
+ if (current) {
318
+ need(user, "content");
319
+ const type = await contentType(current.type);
320
+ await rememberItem(user, current, "changed", [], true);
321
+ await brim.items.update(current, {
322
+ slug: item.slug,
323
+ title: item.title,
324
+ visibility: item.visibility,
325
+ data: item.data,
326
+ });
327
+ await itemMoved(type, current, { ...current, slug: item.slug, data: item.data, visibility: current.visibility });
328
+ return;
329
+ }
330
+ need(user, "publish");
331
+ const restored = await brim.items.restore(item);
332
+ if (!restored.translationOf) await brim.items.relink(restored.id, translations);
333
+ for (const node of nodes) await brim.content.saveNode(node.scope, node.nodeId, node.kind, node.value);
334
+ await brim.history.remove(record.id);
335
+ return;
336
+ }
337
+ need(user, "pages");
338
+ const { page, nodes = [] } = record.before as { page: PageRecord; nodes?: StoredNode[] };
339
+ if (
340
+ !page.template ||
341
+ pages().some((coded) => normalizePagePath(coded) === page.path) ||
342
+ (await brim.content.page(page.path)).template
343
+ ) {
344
+ throw new ValidationError(`The address ${page.path} is used by another page now.`);
345
+ }
346
+ // It comes back private: whoever restores it looks at it before visitors do.
347
+ await brim.content.createPage(page.path, page.template, page.title ?? "", "private");
348
+ if (Object.keys(page.seo ?? {}).length > 0) await brim.content.setPageSeo(page.path, page.seo as SeoSettings);
349
+ for (const node of nodes) await brim.content.saveNode(node.scope, node.nodeId, node.kind, node.value);
350
+ await brim.history.remove(record.id);
351
+ }
352
+
353
+ async function mailView(): Promise<Record<string, unknown>> {
354
+ const settings = await mailSettings.get();
355
+ return { ...(await mailSettings.view()), delivery: options.mailer?.delivery(settings) ?? "none" };
356
+ }
357
+ const icons = options.icons ?? new IconLibrary();
358
+
359
+ function videoHost(): VideoHost {
360
+ if (!videos) throw new HttpError(501, "Video uploads are not set up for this site. Paste a video link instead.");
361
+ return videos;
362
+ }
363
+
364
+ function mediaStore(): MediaStore {
365
+ if (!media) throw new HttpError(501, "Uploads are not set up for this site.");
366
+ return media;
367
+ }
368
+
369
+ /** The user behind the request: the editor's session cookie, or an access token from `brim token add`. */
370
+ /**
371
+ * Where a "forgot password" link points: the site's configured address, or the host's. A request's own Host is
372
+ * trusted only on this computer (`localhost`): anywhere else whoever asks could write it, and the link, with its
373
+ * token, would go to their server.
374
+ */
375
+ function resetLinkOrigin(request: Request): string {
376
+ const configured = [options.siteUrl, process.env.BRIM_SITE_URL]
377
+ .map((value) => String(value ?? "").trim())
378
+ .find((value) => /^https?:\/\//.test(value));
379
+ if (configured) return new URL(configured).origin;
380
+ const origin = requestOrigin(request);
381
+ if (isLocalHost(new URL(origin).hostname)) return origin;
382
+ throw new HttpError(501, "Set `site` in astro.config.mjs so password links point at your site.");
383
+ }
384
+
385
+ /**
386
+ * Tells someone what changed in their access to the site, through the site's own email (its template in
387
+ * `src/emails.ts`, or Brim's), with a link to choose their password when they need one. The change is made either
388
+ * way: the answer says whether the email went out, and why not.
389
+ */
390
+ async function sendAccountEmail(
391
+ request: Request,
392
+ kind: AccountEmail["kind"],
393
+ user: User,
394
+ by: User,
395
+ previousRole?: Role,
396
+ ): Promise<{ emailed: boolean; emailError?: string }> {
397
+ try {
398
+ const settings = await mailSettings.get();
399
+ const mailer = options.mailer;
400
+ if (!mailer || mailer.delivery(settings) === "none") {
401
+ return { emailed: false, emailError: "Email is not set up for this site, so no email was sent." };
402
+ }
403
+ if (!(await rateLimiter.allow(`account-mail:${by.id}`, ACCOUNT_EMAILS_PER_HOUR, 60 * 60))) {
404
+ return { emailed: false, emailError: "Too many account emails this hour, so no email was sent." };
405
+ }
406
+ const origin = resetLinkOrigin(request);
407
+ const hours = linkHours(kind);
408
+ const link = hours ? await brim.accounts.createResetToken(user.email, hours * 60 * 60) : undefined;
409
+ const email = accountEmail(origin, kind, user, by, link?.token, previousRole);
410
+ await mailer.send(settings, await accountMessage(email));
411
+ return { emailed: true };
412
+ } catch (error) {
413
+ const reason = error instanceof Error ? error.message : String(error);
414
+ console.error("[brim] The account email was not sent:", reason);
415
+ return { emailed: false, emailError: reason };
416
+ }
417
+ }
418
+
419
+ function linkHours(kind: AccountEmail["kind"]): number {
420
+ return kind === "added" ? WELCOME_LINK_HOURS : kind === "reset" ? RESET_ACCESS_LINK_HOURS : 0;
421
+ }
422
+
423
+ /** What an account email's template is given. */
424
+ function accountEmail(
425
+ origin: string,
426
+ kind: AccountEmail["kind"],
427
+ user: User,
428
+ by: User | undefined,
429
+ passwordToken: string | undefined, // betterleaks:allow
430
+ previousRole?: Role,
431
+ ): AccountEmail {
432
+ return {
433
+ kind,
434
+ site: new URL(origin).host,
435
+ siteUrl: origin,
436
+ email: user.email,
437
+ role: user.role,
438
+ roleDescription: ROLE_DESCRIPTIONS[user.role],
439
+ ...(previousRole && { previousRole }),
440
+ ...(by && { by: by.email }),
441
+ editorUrl: `${origin}${ADMIN_PATH}/edit`,
442
+ // The token is in the fragment, which browsers never send, so a link checker opening it cannot use it up.
443
+ ...(passwordToken && {
444
+ passwordUrl: `${origin}${ADMIN_PATH}/edit#reset=${passwordToken}`,
445
+ passwordLinkHours: linkHours(kind), // betterleaks:allow
446
+ }),
447
+ ...(options.hostSignIn && { hostSignIn: { name: options.hostSignIn.name, url: options.hostSignIn.url } }),
448
+ sentAt: new Date(),
449
+ };
450
+ }
451
+
452
+ /** The account email as the site's template writes it (`src/emails.ts`), or Brim's own. */
453
+ async function accountMessage(email: AccountEmail) {
454
+ const settings = await mailSettings.get();
455
+ const template = (await Promise.resolve(options.emails?.()).catch(() => undefined))?.[ACCOUNT_TEMPLATES[email.kind]];
456
+ return writtenBySite(accountNotice(email, settings), template, email);
457
+ }
458
+
459
+ /** An email shown as a page of its own, for its author to look at: `?text` shows its subject and text version. */
460
+ function emailPreview(request: Request, message: { subject: string; html: string; text: string; fromName: string }): Response {
461
+ const text = new URL(request.url).searchParams.has("text");
462
+ const headers = {
463
+ "content-type": text ? "text/plain; charset=utf-8" : "text/html; charset=utf-8",
464
+ "cache-control": "no-store",
465
+ // The visitor's words are in it: nothing in the preview runs.
466
+ "content-security-policy": "default-src 'none'; img-src * data:; style-src 'unsafe-inline'",
467
+ };
468
+ // A page of its own, as a phone shows it: the email clients' own viewport, not a desktop's 980 px.
469
+ const shown = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${message.subject.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`)}</title>${message.html}`;
470
+ return new Response(text ? `Subject: ${message.subject}\nFrom: ${message.fromName}\n\n${message.text}` : shown, { headers });
471
+ }
472
+
473
+ /** A change to the users, its refusals said the way the API says them. */
474
+ async function usersChange<T>(change: () => Promise<T>): Promise<T> {
475
+ try {
476
+ return await change();
477
+ } catch (error) {
478
+ if (error instanceof HttpError) throw error;
479
+ const message = error instanceof Error ? error.message : String(error);
480
+ if (message.startsWith("There is no user")) throw new HttpError(404, message);
481
+ if (message.includes("already exists")) throw new HttpError(409, message);
482
+ throw new ValidationError(message);
483
+ }
484
+ }
485
+
486
+ function roleOf(value: unknown): Role {
487
+ if (!ROLES.includes(value as Role)) throw new ValidationError('The role is "owner" or "editor".');
488
+ return value as Role;
489
+ }
490
+
491
+ async function currentUser(request: Request): Promise<User> {
492
+ const user = await requestUser(brim, request);
493
+ if (!user) {
494
+ throw new HttpError(401, bearerToken(request) ? "The access token is not valid." : "Sign in to continue.");
495
+ }
496
+ return user;
497
+ }
498
+
499
+ async function contentType(key: unknown): Promise<ContentType> {
500
+ const type = (await contentTypes()).find((candidate) => candidate.key === key);
501
+ if (!type) throw new HttpError(404, "This content type does not exist.");
502
+ return type;
503
+ }
504
+
505
+ /** An item's language as stored: "" for the default one; a code the site does not declare is refused. */
506
+ /** Where a language's site settings are kept: the site's shared content of that language, as pages read it. */
507
+ function settingsScope(value: unknown): string {
508
+ if (!locales) return siteScope();
509
+ const code = value === undefined || value === null || value === "" ? locales.defaultLocale : String(value);
510
+ if (!locales.locales.includes(code)) throw new ValidationError(`"${code}" is not one of the site's languages.`);
511
+ return siteScope(code);
512
+ }
513
+
514
+ function localeOf(value: unknown): string {
515
+ if (value === undefined || value === null || value === "") return "";
516
+ const stored = storedLocale(String(value), locales);
517
+ if (stored === undefined) throw new ValidationError(`"${String(value)}" is not one of the site's languages.`);
518
+ return stored;
519
+ }
520
+
521
+ async function existingItem(body: Record<string, unknown>): Promise<Item> {
522
+ const item = await brim.items.get(requireString(body.id, "id"));
523
+ if (!item) throw new HttpError(404, "This item does not exist.");
524
+ return item;
525
+ }
526
+
527
+ async function pageTemplate(key: unknown): Promise<PageTemplate> {
528
+ const template = (await pageTemplates()).find((candidate) => candidate.key === key);
529
+ if (!template) throw new HttpError(404, "This page template does not exist.");
530
+ return template;
531
+ }
532
+
533
+ /** A page added from a template; pages written in code cannot be removed or renamed here. */
534
+ async function templatePage(path: string): Promise<PageRecord> {
535
+ const page = await brim.content.page(path);
536
+ if (!page.template) throw new HttpError(404, "Only pages added from a template can be changed this way.");
537
+ return page;
538
+ }
539
+
540
+ /** The address of a new page: free, and not one the site's code or its content types answer. */
541
+ async function newPagePath(body: Record<string, unknown>, template: PageTemplate, title: string): Promise<string> {
542
+ const given = typeof body.path === "string" && body.path.trim() !== "" ? body.path.trim() : undefined;
543
+ const path = normalizePagePath(
544
+ given?.replace(/^\/*/, "/") ?? `/${template.folder ? `${template.folder}/` : ""}${slugify(title) || "page"}`,
545
+ );
546
+ const segments = path.split("/").slice(1);
547
+ if (path === "/" || !segments.every(isSlug)) {
548
+ throw new ValidationError(
549
+ "The address can only have lowercase letters, digits and dashes, e.g. /services/lawn-care.",
550
+ );
551
+ }
552
+ const reserved = [ADMIN_PATH.slice(1), "404", "uploads", ...(await contentTypes()).flatMap(addressPrefixes)];
553
+ if (reserved.includes(segments[0] ?? "")) throw new ValidationError(`The address ${path} is reserved.`);
554
+ if (pages().some((page) => normalizePagePath(page) === path) || (await brim.content.page(path)).template) {
555
+ throw new ValidationError(`The address ${path} is already used by another page.`);
556
+ }
557
+ return path;
558
+ }
559
+
560
+ /**
561
+ * What follows an item to its new address when its slug (or a value in its path) changes: its page's search
562
+ * settings, what the owner placed on its page when that is written in code, and, for a published item, a redirect
563
+ * from the old address, so links and search results that point there still arrive.
564
+ */
565
+ async function itemMoved(type: ContentType, existing: Item, item: Item): Promise<void> {
566
+ const from = normalizePagePath(itemPagePath(type, existing, locales));
567
+ const to = normalizePagePath(itemPagePath(type, item, locales));
568
+ if (from === to) return;
569
+ await brim.content.movePageSettings(from, to);
570
+ if (!type.component) await brim.content.moveNodes(pageScope(from), pageScope(to));
571
+ const redirects = await brim.content.redirects();
572
+ if (existing.visibility === "published") {
573
+ await brim.content.setRedirects(redirectsAfterMove(redirects, from, to));
574
+ } else if (redirects.some((redirect) => redirect.from === to)) {
575
+ await brim.content.setRedirects(redirects.filter((redirect) => redirect.from !== to));
576
+ }
577
+ }
578
+
579
+ /** `slug`, or the first of `slug-2`, `slug-3`… that no item of the type has in that language. */
580
+ async function freeSlug(type: string, slug: string, locale: string | undefined): Promise<string> {
581
+ const taken = async (candidate: string) => (await brim.items.bySlug(type, candidate, { locale: locale ?? "" })) !== undefined;
582
+ if (!(await taken(slug))) return slug;
583
+ for (let number = 2; number < 1000; number++) {
584
+ const candidate = `${slug.slice(0, 120)}-${number}`;
585
+ if (!(await taken(candidate))) return candidate;
586
+ }
587
+ return slug;
588
+ }
589
+
590
+ /** A new page at an address an old redirect still points away from: the redirect goes, so the page is seen. */
591
+ async function clearRedirectFrom(path: string): Promise<boolean> {
592
+ const redirects = await brim.content.redirects();
593
+ if (!redirects.some((redirect) => redirect.from === path)) return false;
594
+ await brim.content.setRedirects(redirects.filter((redirect) => redirect.from !== path));
595
+ return true;
596
+ }
597
+
598
+ /**
599
+ * A term moved to a new slug: its translations, which share its slug, move with it, and the items pointing at it
600
+ * (in every language) follow, once no item keeps the old slug.
601
+ */
602
+ async function termMoved(types: ContentType[], type: ContentType, existing: Item, item: Item): Promise<void> {
603
+ if (item.slug === existing.slug || !isReferenced(types, type.key)) return;
604
+ if (existing.translationOf === null) {
605
+ for (const translation of await brim.items.translations(existing)) {
606
+ if (translation.id === existing.id || translation.slug !== existing.slug) continue;
607
+ const moved = await brim.items.update(translation, { ...translation, slug: item.slug });
608
+ await itemMoved(type, translation, moved);
609
+ }
610
+ }
611
+ if (!(await brim.items.list(type.key)).some((other) => other.slug === existing.slug)) {
612
+ for (const changed of await renameReferences(types, brim.items, existing, item.slug)) {
613
+ await itemMoved(changed.type, changed.before, changed.item);
614
+ }
615
+ }
616
+ }
617
+
618
+ /** An element that shows a field of an item: only the field is saved, into the item, checked like the item form. */
619
+ async function saveToItem(
620
+ user: User,
621
+ body: Record<string, unknown>,
622
+ nodeId: string,
623
+ kind: string,
624
+ value: Record<string, unknown>,
625
+ ): Promise<Response> {
626
+ const live = await existingItem({ id: body.item });
627
+ const field = requireString(body.field, "field");
628
+ if (body.draft === true) {
629
+ const existing = await brim.drafts.overlayItem(live);
630
+ const next = applyToItem(await contentType(live.type), existing, field, kind, value);
631
+ return json({ nodeId, kind, ...(await draftItem(live, next, pagePathOf(body))) });
632
+ }
633
+ const type = await contentType(live.type);
634
+ const next = applyToItem(type, live, field, kind, value);
635
+ await rememberItem(user, live, "changed");
636
+ const item = await brim.items.update(live, next);
637
+ await itemMoved(type, live, item);
638
+ await changed(undefined);
639
+ return json({ nodeId, kind, item });
640
+ }
641
+
642
+ /** Where a node is kept: with the whole site, with its page, or with the template of the item whose page it is. */
643
+ async function scopeOf(body: Record<string, unknown>, pagePath: string): Promise<string> {
644
+ if (body.scope === "site") return siteScope(localeOfPath(pagePath, locales));
645
+ if (body.scope === "page") return pageScope(pagePath);
646
+ if (body.scope === "template") {
647
+ const itemPage = itemPageOf(await contentTypes(), pagePath, locales);
648
+ if (!itemPage) throw new HttpError(400, `${pagePath} is not the page of an item, so it has no template.`);
649
+ return typeScope(itemPage.type.key, localeOfPath(pagePath, locales));
650
+ }
651
+ throw new HttpError(400, '"scope" must be "page", "site" or "template".');
652
+ }
653
+
654
+ /** An element's value as sent: a block's settings checked against its schema, a primitive against its shape. */
655
+ function nodeValueOf(kind: string, input: unknown): unknown {
656
+ const block = Object.hasOwn(blockDefinitions, kind) ? blockDefinitions[kind] : undefined;
657
+ return block && !isPrimitive(kind) ? parseSettings(block, input) : parseNodeValue(kind as NodeKind, input);
658
+ }
659
+
660
+ /**
661
+ * Writes one draft and answers with the change, so the editor can take it back (`before`) and make it again
662
+ * (`after`); `null` is no draft, the saved content. `drafts` counts the changes nobody has saved yet.
663
+ */
664
+ async function writeDraft(
665
+ target: DraftTarget,
666
+ key: string,
667
+ value: unknown,
668
+ page: string,
669
+ ): Promise<{ change: { target: DraftTarget; key: string; page: string; before: unknown; after: unknown }; drafts: number }> {
670
+ const before = await brim.drafts.get(target, key);
671
+ await brim.drafts.set(target, key, value, page);
672
+ return {
673
+ change: { target, key, page, before: before ?? null, after: value ?? null },
674
+ drafts: await brim.drafts.count(),
675
+ };
676
+ }
677
+
678
+ /** An item's content held back as a draft; who can see it is never drafted. Answers with the item as previewed. */
679
+ async function draftItem(live: Item, next: ItemContentDraft, page: string) {
680
+ const content: ItemContentDraft = { slug: next.slug, title: next.title, data: next.data };
681
+ const same = content.slug === live.slug && content.title === live.title && sameJson(content.data, live.data);
682
+ const answer = await writeDraft("item", live.id, same ? undefined : content, page);
683
+ return { ...answer, item: { ...live, ...content } };
684
+ }
685
+
686
+ /** Checks a draft the editor sends back to undo or redo a change, as if it were made anew. */
687
+ async function checkedDraft(user: User, target: DraftTarget, key: string, value: unknown): Promise<unknown> {
688
+ if (target === "node") {
689
+ const [scope = "", nodeId = "", ...rest] = key.split("\n");
690
+ if (rest.length > 0 || !isNodeId(nodeId) || !/^(page:|site|type:)/.test(scope)) {
691
+ throw new HttpError(400, "This is not an element of the site.");
692
+ }
693
+ assertElement(nodeId);
694
+ if (scope.startsWith("type:")) need(user, "templates");
695
+ if (value === null) return undefined;
696
+ const draft = value as Record<string, unknown>;
697
+ if (draft.reset === true) return { reset: true };
698
+ const kind = requireString(draft.kind, "kind");
699
+ return { kind, value: nodeValueOf(kind, draft.value) };
700
+ }
701
+ if (target === "item") {
702
+ const live = await existingItem({ id: key });
703
+ if (value === null) return undefined;
704
+ const type = await contentType(live.type);
705
+ const parsed = parseItem(type, { ...(value as Record<string, unknown>), visibility: live.visibility });
706
+ return { slug: parsed.slug, title: parsed.title, data: parsed.data };
707
+ }
708
+ if (target === "seo") return value === null ? undefined : parseSeo(value);
709
+ throw new HttpError(400, '"target" must be "node", "item" or "seo".');
710
+ }
711
+
712
+ /**
713
+ * Writes every draft to the content visitors see, each remembered in the history so it can be taken back.
714
+ * A draft that cannot be saved (an address taken meanwhile, an item deleted) stays, and is reported.
715
+ */
716
+ async function saveDrafts(user: User): Promise<{ saved: number; failed: { page: string; error: string }[] }> {
717
+ let saved = 0;
718
+ const failed: { page: string; error: string }[] = [];
719
+ for (const row of await brim.drafts.all()) {
720
+ try {
721
+ if (row.target === "node") {
722
+ const [scope = "", nodeId = ""] = row.key.split("\n");
723
+ if (scope.startsWith("type:")) need(user, "templates");
724
+ const draft = row.value as NodeDraft;
725
+ if ("reset" in draft) {
726
+ await rememberNode(user, scope, nodeId, row.page, "reset", true);
727
+ await brim.content.resetNode(scope, nodeId);
728
+ } else {
729
+ await rememberNode(user, scope, nodeId, row.page, "changed", true);
730
+ await brim.content.saveNode(scope, nodeId, draft.kind, draft.value);
731
+ }
732
+ } else if (row.target === "item") {
733
+ const existing = await brim.items.get(row.key);
734
+ if (existing) {
735
+ const content = row.value as ItemContentDraft;
736
+ const type = await contentType(existing.type);
737
+ await rememberItem(user, existing, "changed", [], true);
738
+ const item = await brim.items.update(existing, { ...content, visibility: existing.visibility });
739
+ await itemMoved(type, existing, item);
740
+ await termMoved(await contentTypes(), type, existing, item);
741
+ }
742
+ } else {
743
+ await brim.content.setPageSeo(row.key, row.value as SeoSettings);
744
+ }
745
+ await brim.drafts.set(row.target, row.key, undefined, row.page);
746
+ saved++;
747
+ } catch (error) {
748
+ if (!(error instanceof HttpError || error instanceof ValidationError)) throw error;
749
+ failed.push({ page: row.page, error: error.message });
750
+ }
751
+ }
752
+ if (saved > 0) await changed(undefined);
753
+ return { saved, failed };
754
+ }
755
+
756
+ const routes: Record<string, (request: Request, info: RequestInfo) => Promise<Response>> = {
757
+ // What runs here, for a host or a tool checking that it can work with this site. Open to anyone.
758
+ // The icon sets the editor offers and, when asked, the icon a block has now.
759
+ "GET /icons": async (request) => {
760
+ await currentUser(request);
761
+ const value = new URL(request.url).searchParams.get("value");
762
+ return json({ sets: icons.sets(), ...(value !== null && { icon: icons.find(value) ?? null }) });
763
+ },
764
+ "GET /info": async () =>
765
+ json({
766
+ name: "brimjs",
767
+ version: VERSION,
768
+ schemaVersion: SCHEMA_VERSION,
769
+ // The editor reads this too: it offers "Upload video" only when a video host is set up.
770
+ capabilities: [
771
+ "sign-in-link",
772
+ "mail-settings",
773
+ "roles",
774
+ // `/admin/api/users`: an owner (or a host with an owner's token) adds users, changes roles and resets
775
+ // access there, and the site emails the person about it.
776
+ "users",
777
+ "history",
778
+ "drafts",
779
+ // A request that changed what visitors see is answered with `X-Brim-Changed: live`.
780
+ "live-change-header",
781
+ // `query` below: the query parameters each page and route reads.
782
+ ...(options.queryParams ? ["query-params"] : []),
783
+ ...(videos ? ["video-uploads"] : []),
784
+ // Forms can take files from visitors only where the site has a private place to keep them.
785
+ ...(formFiles ? ["form-files"] : []),
786
+ ],
787
+ // The sign-in form offers it beside the password; the host sends its user back through /session/link.
788
+ hostSignIn: options.hostSignIn ?? null,
789
+ brandColors: options.brandColors ?? [],
790
+ // The site's languages, from Astro's i18n in its code: the editor switches and translates between them.
791
+ locales: locales ?? null,
792
+ // What a page falls back to in search results and shared links, for the previews in Page Settings.
793
+ identity: {
794
+ name: options.identity?.name ?? null,
795
+ titleTemplate: options.identity?.titleTemplate ?? null,
796
+ description: options.identity?.description ?? null,
797
+ image: options.identity?.image ?? null,
798
+ },
799
+ ...(options.queryParams && { query: await queryRules() }),
800
+ }),
801
+
802
+ "POST /session": async (request, info) => {
803
+ const body = await readJson(request);
804
+ const email = requireString(body.email, "email");
805
+ const password = requireString(body.password, "password"); // betterleaks:allow
806
+
807
+ // Every attempt is counted before the password is checked, so attempts sent all at once cannot pass the limit
808
+ // together; one that signs in correctly is given back, so it uses up nobody's attempts.
809
+ const counted: string[] = [];
810
+ const giveBack = async () => {
811
+ for (const key of counted) await rateLimiter.release(key, LOGIN_WINDOW_SECONDS);
812
+ };
813
+ for (const key of loginKeys(info, email)) {
814
+ counted.push(key);
815
+ if (await rateLimiter.allow(key, LOGIN_ATTEMPTS, LOGIN_WINDOW_SECONDS)) continue;
816
+ // A refused attempt was not tried: it is given back, so waiting out the window is enough. Nothing after it is
817
+ // counted, so an address past its limit leaves no row for each email it goes on to name.
818
+ await giveBack();
819
+ throw new HttpError(429, "Too many sign-in attempts. Try again in a few minutes.");
820
+ }
821
+
822
+ const user = await brim.accounts.authenticate(email, password);
823
+ if (!user) throw new HttpError(401, "The email or password is wrong.");
824
+ await giveBack();
825
+
826
+ const session = await brim.accounts.startSession(user.id);
827
+ return json(
828
+ { user, permissions: permissionsOf(user.role) },
829
+ { headers: signInHeaders(request, session.token, session.maxAgeSeconds) },
830
+ );
831
+ },
832
+
833
+ /**
834
+ * "Forgot password": emails a one-time link to set a new one, valid for an hour. The answer is the same whether
835
+ * the email belongs to a user or not, and the email goes out after the answer, so neither the words nor the time
836
+ * taken tell who has an account here.
837
+ */
838
+ "POST /password/forgot": async (request, info) => {
839
+ const body = await readJson(request);
840
+ const email = normalizeEmail(requireString(body.email, "email"));
841
+ if (!(await rateLimiter.allow(`reset:address:${info.clientAddress}`, RESET_ASKS_PER_ADDRESS, RESET_WINDOW_SECONDS))) {
842
+ throw new HttpError(429, "Too many requests. Try again in an hour.");
843
+ }
844
+ const settings = await mailSettings.get();
845
+ if (!options.mailer || options.mailer.delivery(settings) === "none") {
846
+ throw new HttpError(501, "This site cannot send email yet. Ask whoever runs it to reset your password.");
847
+ }
848
+ const origin = resetLinkOrigin(request);
849
+ const answer = json({
850
+ sent: true,
851
+ message: "If this email has an account here, a link to set a new password is on its way.",
852
+ });
853
+ if (!(await rateLimiter.allow(`reset:email:${emailKey(email)}`, RESET_ASKS_PER_EMAIL, RESET_WINDOW_SECONDS))) return answer;
854
+ const mailer = options.mailer;
855
+ void (async () => {
856
+ const reset = await brim.accounts.createResetToken(email);
857
+ if (!reset) return;
858
+ // The token is in the address's fragment, which browsers never send to a server or in a Referer.
859
+ const link = `${origin}${ADMIN_PATH}/edit#reset=${reset.token}`;
860
+ await mailer.send(settings, passwordResetNotice(new URL(origin).host, settings, email, link));
861
+ })().catch((error: unknown) => {
862
+ console.error("[brim] The password reset email was not sent:", error instanceof Error ? error.message : error);
863
+ });
864
+ return answer;
865
+ },
866
+
867
+ /** Sets a new password with the emailed link, signs everyone else out, and signs this browser in. */
868
+ "POST /password/reset": async (request, info) => {
869
+ const body = await readJson(request);
870
+ const token = requireString(body.token, "token");
871
+ const password = requireString(body.password, "password"); // betterleaks:allow
872
+ if (!(await rateLimiter.allow(`reset-use:address:${info.clientAddress}`, LOGIN_ATTEMPTS, LOGIN_WINDOW_SECONDS))) {
873
+ throw new HttpError(429, "Too many attempts. Try again in a few minutes.");
874
+ }
875
+ let user: User | undefined;
876
+ try {
877
+ user = await brim.accounts.resetPassword(token, password);
878
+ } catch (error) {
879
+ throw new ValidationError(error instanceof Error ? error.message : String(error));
880
+ }
881
+ if (!user) throw new HttpError(410, "This link has expired or was already used. Ask for a new one.");
882
+ const session = await brim.accounts.startSession(user.id);
883
+ return json(
884
+ { user, permissions: permissionsOf(user.role) },
885
+ { headers: signInHeaders(request, session.token, session.maxAgeSeconds) },
886
+ );
887
+ },
888
+
889
+ /**
890
+ * A signed-in user changes their password, giving the one they have. Every other session and access token ends
891
+ * (whoever knew the old password is out); this browser stays signed in with a new session.
892
+ */
893
+ "PUT /password": async (request, info) => {
894
+ const user = await currentUser(request);
895
+ if (bearerToken(request)) throw new HttpError(403, "Change the password in the editor, signed in.");
896
+ const body = await readJson(request);
897
+ const current = requireString(body.current, "current");
898
+ const password = requireString(body.password, "password"); // betterleaks:allow
899
+ const keys = loginKeys(info, user.email);
900
+ for (const key of keys) {
901
+ if (!(await rateLimiter.allow(key, LOGIN_ATTEMPTS, LOGIN_WINDOW_SECONDS))) {
902
+ throw new HttpError(429, "Too many attempts. Try again in a few minutes.");
903
+ }
904
+ }
905
+ if (!(await brim.accounts.authenticate(user.email, current))) {
906
+ throw new ValidationError("The current password is wrong.");
907
+ }
908
+ for (const key of keys) await rateLimiter.release(key, LOGIN_WINDOW_SECONDS);
909
+ try {
910
+ await brim.accounts.setPassword(user.email, password);
911
+ } catch (error) {
912
+ throw new ValidationError(error instanceof Error ? error.message : String(error));
913
+ }
914
+ const session = await brim.accounts.startSession(user.id);
915
+ return json({ user }, { headers: signInHeaders(request, session.token, session.maxAgeSeconds) });
916
+ },
917
+
918
+ // Who is signed in and what their role allows, so the editor offers only what will work.
919
+ "GET /session": async (request) => {
920
+ const user = await currentUser(request);
921
+ return json({ user, permissions: permissionsOf(user.role) });
922
+ },
923
+
924
+ // A link from `brim user link` (or from a host's dashboard): signs its user in once and opens the editor.
925
+ // A link that is wrong, used or too old opens the editor too, where the sign-in form waits.
926
+ "GET /session/link": async (request, info) => {
927
+ const params = new URL(request.url).searchParams;
928
+ const token = params.get("token") ?? "";
929
+ // `to` opens the editor on one page (`/admin/edit/despre-noi`); only an address inside the editor is followed.
930
+ const to = params.get("to") ?? "";
931
+ const target = /^\/admin\/edit(\/[\w\-/.]*)?$/.test(to) && !to.includes("..") ? to : `${ADMIN_PATH}/edit`;
932
+ const headers = new Headers({
933
+ location: target,
934
+ "cache-control": "no-store",
935
+ "referrer-policy": "no-referrer",
936
+ });
937
+ const allowed = await rateLimiter.allow(
938
+ `link:address:${info.clientAddress}`,
939
+ LOGIN_ATTEMPTS,
940
+ LOGIN_WINDOW_SECONDS,
941
+ );
942
+ const user = allowed && token ? await brim.accounts.redeemSignInToken(token) : undefined;
943
+ if (user) {
944
+ const session = await brim.accounts.startSession(user.id);
945
+ for (const cookie of signInHeaders(request, session.token, session.maxAgeSeconds).getSetCookie()) {
946
+ headers.append("set-cookie", cookie);
947
+ }
948
+ }
949
+ return new Response(null, { status: 303, headers });
950
+ },
951
+
952
+ "DELETE /session": async (request) => {
953
+ for (const token of sessionCookies(request)) await brim.accounts.endSession(token);
954
+ const headers = new Headers({ "set-cookie": sessionCookie(request, "", 0) });
955
+ // Sessions started before the cookie covered the whole site were kept under /admin.
956
+ headers.append("set-cookie", sessionCookie(request, "", 0, ADMIN_PATH));
957
+ return json({}, { headers });
958
+ },
959
+
960
+ // Pages written in code, then the ones added from templates, in one list by address.
961
+ "GET /pages": async (request) => {
962
+ await currentUser(request);
963
+ const paths = [...new Set(pages().map(normalizePagePath))];
964
+ const coded = await Promise.all(paths.map((path) => brim.content.page(path)));
965
+ const added = (await brim.content.templatePages()).filter((page) => !paths.includes(page.path));
966
+ // The editor asks with `?draft`: the SEO settings it shows are the ones it previews.
967
+ const draft = new URL(request.url).searchParams.has("draft");
968
+ const listed = draft
969
+ ? await Promise.all(
970
+ [...coded, ...added].map(async (page) => ({
971
+ ...page,
972
+ seo: await brim.drafts.overlaySeo(page.path, page.seo),
973
+ })),
974
+ )
975
+ : [...coded, ...added];
976
+ return json({ pages: listed.sort((a, b) => a.path.localeCompare(b.path)) });
977
+ },
978
+
979
+ "POST /pages": async (request) => {
980
+ await allowed(request, "pages");
981
+ const body = await readJson(request);
982
+ const template = await pageTemplate(body.template);
983
+ const title = titleOf(body);
984
+ const path = await newPagePath(body, template, title);
985
+ const visibility = visibilityOf(body.visibility ?? "private");
986
+ const page = await brim.content.createPage(path, template.key, title, visibility);
987
+ // A private page shows nobody anything yet.
988
+ await changed(path, visibility === "published");
989
+ return json({ page }, { status: 201 });
990
+ },
991
+
992
+ "PUT /pages": async (request) => {
993
+ await allowed(request, "content");
994
+ const body = await readJson(request);
995
+ const path = pagePathOf(body);
996
+ const seo = body.seo === undefined ? undefined : parseSeo(body.seo);
997
+ // From the editor, SEO settings wait in the draft like the page's content; nothing else here is drafted.
998
+ if (body.draft === true) {
999
+ if (!seo) throw new HttpError(400, "Only a page's SEO settings can be drafted.");
1000
+ const page = await brim.content.page(path);
1001
+ const answer = await writeDraft("seo", path, sameJson(seo, page.seo) ? undefined : seo, path);
1002
+ return json({ ...page, seo, ...answer });
1003
+ }
1004
+ if (body.title !== undefined) {
1005
+ await templatePage(path);
1006
+ await brim.content.setPageTitle(path, titleOf(body));
1007
+ }
1008
+ if (body.visibility !== undefined) await brim.content.setPageVisibility(path, visibilityOf(body.visibility));
1009
+ if (seo) await brim.content.setPageSeo(path, seo);
1010
+ await changed(path);
1011
+ return json(await brim.content.page(path));
1012
+ },
1013
+
1014
+ // A page added from a template gets a new address; the old one keeps working, as a redirect to the new one.
1015
+ "POST /pages/move": async (request) => {
1016
+ await allowed(request, "pages");
1017
+ const body = await readJson(request);
1018
+ const page = await templatePage(pagePathOf(body));
1019
+ const template = (await pageTemplates()).find((candidate) => candidate.key === page.template);
1020
+ if (!template) throw new ValidationError("This page's template is no longer in the site's code.");
1021
+ const requested = typeof body.to === "string" ? normalizePagePath(body.to.trim().replace(/^\/*/, "/")) : "";
1022
+ if (requested === page.path) return json({ page });
1023
+ const to = await newPagePath({ path: body.to }, template, page.title ?? "");
1024
+ await brim.content.movePage(page.path, to);
1025
+ await brim.content.setRedirects(redirectsAfterMove(await brim.content.redirects(), page.path, to));
1026
+ await changed(page.path);
1027
+ await changed(to);
1028
+ return json({ page: await brim.content.page(to) });
1029
+ },
1030
+
1031
+ "GET /redirects": async (request) => {
1032
+ await currentUser(request);
1033
+ return json({ redirects: await brim.content.redirects() });
1034
+ },
1035
+
1036
+ // The whole list, as the owner keeps it in Site Settings.
1037
+ "PUT /redirects": async (request) => {
1038
+ await currentOwner(request);
1039
+ const redirects = parseRedirects((await readJson(request)).redirects);
1040
+ await brim.content.setRedirects(redirects);
1041
+ await changed(undefined);
1042
+ return json({ redirects });
1043
+ },
1044
+
1045
+ "DELETE /pages": async (request) => {
1046
+ const user = await allowed(request, "pages");
1047
+ const page = await templatePage(pagePathOf(await readJson(request)));
1048
+ const { path } = page;
1049
+ await brim.history.record({
1050
+ target: "page",
1051
+ key: path,
1052
+ action: "deleted",
1053
+ page: path,
1054
+ title: page.title || path,
1055
+ before: { page, nodes: await brim.content.loadNodes([pageScope(path)]) },
1056
+ user: user.email,
1057
+ always: true,
1058
+ });
1059
+ await brim.content.deletePage(path);
1060
+ await changed(path);
1061
+ return json({});
1062
+ },
1063
+
1064
+ "GET /templates": async (request) => {
1065
+ await currentUser(request);
1066
+ return json({ templates: (await pageTemplates()).map(templateInfo) });
1067
+ },
1068
+
1069
+ "GET /media": async (request) => {
1070
+ await currentUser(request);
1071
+ // A page of the library at a time (`?search=`, `?folder=` with "" for the gallery, `?after=` the `next` of
1072
+ // the page before), with small copies for the picker, not the uploads at their full size.
1073
+ const params = new URL(request.url).searchParams;
1074
+ const { files, next } = await mediaStore().page({
1075
+ ...(params.has("search") && { search: params.get("search") ?? "" }),
1076
+ ...(params.has("folder") && { folder: params.get("folder") ?? "" }),
1077
+ ...(params.has("after") && { after: params.get("after") ?? "" }),
1078
+ ...(params.has("limit") && { limit: Number(params.get("limit")) || 120 }),
1079
+ });
1080
+ const { thumbnail } = options;
1081
+ return json({
1082
+ files: thumbnail
1083
+ ? files.map((file) => {
1084
+ const small = thumbnail(file.url);
1085
+ return small ? { ...file, thumbnail: small } : file;
1086
+ })
1087
+ : files,
1088
+ ...(next && { next }),
1089
+ });
1090
+ },
1091
+
1092
+ // The image is the request body itself; its original name travels in a header.
1093
+ "POST /media": async (request) => {
1094
+ await allowed(request, "content");
1095
+ const store = mediaStore();
1096
+ if (Number(request.headers.get("content-length") ?? 0) > MAX_UPLOAD_BYTES) {
1097
+ throw new HttpError(413, "The image is larger than 10 MB.");
1098
+ }
1099
+ // An image goes to the gallery, or to the folder of one item: `<type>/<item id>`.
1100
+ const folder = safeDecode(request.headers.get("x-media-folder") ?? "");
1101
+ if (folder) {
1102
+ const [typeKey, itemId, ...rest] = folder.split("/");
1103
+ const item = itemId && rest.length === 0 ? await brim.items.get(itemId) : undefined;
1104
+ if (!item || item.type !== (await contentType(typeKey)).key)
1105
+ throw new HttpError(404, "This folder does not exist.");
1106
+ }
1107
+ const bytes = await readBytes(request, MAX_UPLOAD_BYTES, "The image is larger than 10 MB.");
1108
+ const name = safeDecode(request.headers.get("x-file-name") ?? "");
1109
+ return json({ file: await store.upload(bytes, name, folder) }, { status: 201 });
1110
+ },
1111
+
1112
+ // Asks the video host for a place to upload one video. The bytes then go from the browser straight to
1113
+ // the host: they never pass through the site.
1114
+ "POST /videos": async (request) => {
1115
+ await allowed(request, "content");
1116
+ const host = videoHost();
1117
+ return json(await host.create(parseNewVideo(await readJson(request))), { status: 201 });
1118
+ },
1119
+
1120
+ // The videos uploaded to the host, for the editor to use again or delete. A host need not list them:
1121
+ // `supported` is then false and the editor shows no list.
1122
+ "GET /videos": async (request) => {
1123
+ await allowed(request, "content");
1124
+ const list = await videoHost().list();
1125
+ return json({ supported: list !== undefined, videos: list ?? [] });
1126
+ },
1127
+
1128
+ // The site's email settings. What the server itself was given to send with is never part of the answer.
1129
+ /**
1130
+ * The email the owner gets for a form message, as the site's template writes it (Brim's own without one): with
1131
+ * the newest message received, or an example. `?text` shows its text version. To see it while writing
1132
+ * src/emails.ts.
1133
+ */
1134
+ "GET /emails/form": async (request) => {
1135
+ // It shows the newest message a visitor sent, so it asks for what reading the messages asks for.
1136
+ await allowed(request, "responses");
1137
+ const origin = publicOrigin(request, options.siteUrl);
1138
+ const newest = (await brim.forms.list())[0];
1139
+ const page = newest ? formPage(newest.form) : "/produse/exemplu";
1140
+ const answers = newest?.answers ?? [
1141
+ { label: "Nume", value: "Ana Popescu" },
1142
+ { label: "E-mail", value: "ana@example.com" },
1143
+ { label: "Mesaj", value: "Bună ziua, aș dori o ofertă pentru 40 m²." },
1144
+ ];
1145
+ const email: FormEmail = {
1146
+ form: newest?.title ?? "Contact",
1147
+ site: new URL(origin).host,
1148
+ siteUrl: origin,
1149
+ ...(page && { page: `${origin}${page}` }),
1150
+ answers: answers.map(({ label, value }) => ({ label, value })),
1151
+ responsesUrl: `${origin}/admin/edit`,
1152
+ responseUrl: newest ? `${origin}/admin/edit?response=${encodeURIComponent(newest.id)}` : `${origin}/admin/edit`,
1153
+ sentAt: newest ? new Date(newest.createdAt) : new Date(),
1154
+ };
1155
+ const settings = await mailSettings.get();
1156
+ const base = formNotice({
1157
+ site: email.site,
1158
+ title: email.form,
1159
+ answers: email.answers,
1160
+ ...(email.page && { page: email.page }),
1161
+ responsesUrl: email.responsesUrl,
1162
+ responseUrl: email.responseUrl,
1163
+ settings,
1164
+ to: [],
1165
+ });
1166
+ const template = (await Promise.resolve(options.emails?.()).catch(() => undefined))?.form;
1167
+ const message = await writtenBySite(base, template, { ...email, replyTo: base.replyTo });
1168
+ return emailPreview(request, message);
1169
+ },
1170
+
1171
+ /**
1172
+ * The email someone gets when they are added (`?kind=added`), their role changes (`role`) or their access is
1173
+ * reset (`reset`), as the site's template writes it, addressed to the owner asking and sending nothing. `?text`
1174
+ * shows its text version.
1175
+ */
1176
+ "GET /emails/account": async (request) => {
1177
+ const owner = await allowed(request, "users");
1178
+ const kind = new URL(request.url).searchParams.get("kind") ?? "added";
1179
+ if (kind !== "added" && kind !== "role" && kind !== "reset") {
1180
+ throw new ValidationError('The kind is "added", "role" or "reset".');
1181
+ }
1182
+ const origin = publicOrigin(request, options.siteUrl);
1183
+ const example = { ...owner, email: "ana@example.com", role: "editor" as const };
1184
+ const email = accountEmail(origin, kind, example, owner, kind === "role" ? undefined : "example", kind === "role" ? "owner" : undefined);
1185
+ return emailPreview(request, await accountMessage(email));
1186
+ },
1187
+
1188
+ /**
1189
+ * The confirmation a visitor gets, as the site's `confirmation` template writes it (Brim's own without one), with
1190
+ * an example subject and message: `?subject=` and `?message=` try others, `?text` shows its text version.
1191
+ */
1192
+ "GET /emails/confirmation": async (request) => {
1193
+ await currentUser(request);
1194
+ const origin = publicOrigin(request, options.siteUrl);
1195
+ const query = new URL(request.url).searchParams;
1196
+ const settings = await mailSettings.get();
1197
+ const email: ConfirmationEmail = {
1198
+ form: "Contact",
1199
+ site: new URL(origin).host,
1200
+ siteUrl: origin,
1201
+ page: `${origin}/contact`,
1202
+ subject: query.get("subject")?.slice(0, 150) || "Am primit mesajul tău",
1203
+ message: query.get("message")?.slice(0, 5_000) || "Mulțumim! Am primit mesajul tău și revenim în cel mult o zi lucrătoare.",
1204
+ answers: [],
1205
+ sentAt: new Date(),
1206
+ };
1207
+ const base = confirmationNotice({
1208
+ site: email.site,
1209
+ subject: email.subject,
1210
+ message: email.message,
1211
+ settings: { ...settings, senderName: settings.senderName || options.identity?.name || "" },
1212
+ to: "visitor@example.com",
1213
+ });
1214
+ const template = (await Promise.resolve(options.emails?.()).catch(() => undefined))?.confirmation;
1215
+ const message = await writtenBySite(base, template, email);
1216
+ const text = query.has("text");
1217
+ const headers = {
1218
+ "content-type": text ? "text/plain; charset=utf-8" : "text/html; charset=utf-8",
1219
+ "cache-control": "no-store",
1220
+ "content-security-policy": "default-src 'none'; img-src * data:; style-src 'unsafe-inline'",
1221
+ };
1222
+ const shown = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${message.subject.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`)}</title>${message.html}`;
1223
+ return new Response(text ? `Subject: ${message.subject}\nFrom: ${message.fromName}\n\n${message.text}` : shown, { headers });
1224
+ },
1225
+
1226
+ "GET /mail": async (request) => {
1227
+ await currentOwner(request);
1228
+ return json(await mailView());
1229
+ },
1230
+
1231
+ "PUT /mail": async (request) => {
1232
+ await currentOwner(request);
1233
+ await mailSettings.update(await readJson(request));
1234
+ return json(await mailView());
1235
+ },
1236
+
1237
+ // Sends a short email to the owner asking, to show the settings work.
1238
+ "POST /mail/test": async (request) => {
1239
+ const user = await currentOwner(request);
1240
+ if (!(await rateLimiter.allow(`mail-test:${user.id}`, 5, 10 * 60))) {
1241
+ throw new HttpError(429, "Too many test emails. Try again in a few minutes.");
1242
+ }
1243
+ const settings = await mailSettings.get();
1244
+ if (!options.mailer) throw new HttpError(501, "Email is not set up for this site.");
1245
+ await options.mailer.send(settings, testNotice(new URL(publicOrigin(request, options.siteUrl)).host, settings, user.email));
1246
+ return json({ sentTo: user.email });
1247
+ },
1248
+
1249
+ // The site's users, for its owners, and for a host's dashboard with an owner's token. Adding someone, changing
1250
+ // their role or resetting their access emails them (`notify: false` leaves it to the caller).
1251
+ "GET /users": async (request) => {
1252
+ await allowed(request, "users");
1253
+ const users = await brim.accounts.listUsers();
1254
+ return json({ users: users.map(({ email, role, createdAt, tokens }) => ({ email, role, createdAt, tokens })) });
1255
+ },
1256
+
1257
+ /** Adds a user. Without a password one is made and answered once; the email lets them choose their own. */
1258
+ "POST /users": async (request) => {
1259
+ const owner = await allowed(request, "users");
1260
+ const body = await readJson(request);
1261
+ const email = requireString(body.email, "email");
1262
+ const role = roleOf(body.role ?? "editor");
1263
+ const given = body.password === undefined ? undefined : requireString(body.password, "password"); // betterleaks:allow
1264
+ const password = given ?? generatePassword(); // betterleaks:allow
1265
+ const user = await usersChange(() => brim.accounts.createUser(email, password, role));
1266
+ const told = body.notify === false ? { emailed: false } : await sendAccountEmail(request, "added", user, owner);
1267
+ return json({ user, ...(given === undefined && { password }), ...told }, { status: 201 });
1268
+ },
1269
+
1270
+ "PUT /users": async (request) => {
1271
+ const owner = await allowed(request, "users");
1272
+ const body = await readJson(request);
1273
+ const email = requireString(body.email, "email").trim().toLowerCase();
1274
+ const role = roleOf(body.role);
1275
+ const before = (await brim.accounts.listUsers()).find((user) => user.email === email);
1276
+ if (!before) throw new HttpError(404, `There is no user with the email ${email}.`);
1277
+ if (before.role === role) return json({ user: { id: before.id, email, role }, emailed: false });
1278
+ const user = await usersChange(() => brim.accounts.setRole(email, role));
1279
+ const told =
1280
+ body.notify === false ? { emailed: false } : await sendAccountEmail(request, "role", user, owner, before.role);
1281
+ return json({ user, ...told });
1282
+ },
1283
+
1284
+ /**
1285
+ * "Reset access": a new password (answered once), every session of theirs ends, their access tokens too with
1286
+ * `revokeTokens`, and the email gives them a link to choose a new password.
1287
+ */
1288
+ "POST /users/reset": async (request) => {
1289
+ const owner = await allowed(request, "users");
1290
+ const body = await readJson(request);
1291
+ const email = requireString(body.email, "email");
1292
+ const result = await usersChange(() =>
1293
+ brim.accounts.resetAccess(email, { revokeTokens: body.revokeTokens === true }),
1294
+ );
1295
+ const user = (await brim.accounts.listUsers()).find(
1296
+ (candidate) => candidate.email === email.trim().toLowerCase(),
1297
+ );
1298
+ const told =
1299
+ body.notify === false || !user ? { emailed: false } : await sendAccountEmail(request, "reset", user, owner);
1300
+ return json({ email: email.trim().toLowerCase(), ...result, ...told });
1301
+ },
1302
+
1303
+ "DELETE /users": async (request) => {
1304
+ await allowed(request, "users");
1305
+ const email = requireString((await readJson(request)).email, "email");
1306
+ await usersChange(() => brim.accounts.removeUser(email));
1307
+ return json({ email: email.trim().toLowerCase(), removed: true });
1308
+ },
1309
+
1310
+ "GET /responses": async (request) => {
1311
+ await allowed(request, "responses");
1312
+ return json({ responses: await brim.forms.list() });
1313
+ },
1314
+
1315
+ "DELETE /responses": async (request) => {
1316
+ await allowed(request, "responses");
1317
+ // The files a visitor attached go with their message, at once and for good: they are not in the history.
1318
+ const removed = await brim.forms.remove(requireString((await readJson(request)).id, "id"));
1319
+ if (removed && removed.files.length > 0) await formFiles?.remove(removed.id, removed.files);
1320
+ return json({});
1321
+ },
1322
+
1323
+ // The component cannot travel; the editor only needs to know which types have a page per item.
1324
+ // The site's own settings: the fields it declares, and their values in one language (the saved ones over the
1325
+ // code's defaults). Anyone who changes content changes them: they are the site's words, not its structure.
1326
+ "GET /site-settings": async (request) => {
1327
+ await currentUser(request);
1328
+ const declared = await siteSettings();
1329
+ const locale = localeOf(new URL(request.url).searchParams.get("locale") ?? undefined);
1330
+ const saved = (await brim.content.loadNodes([siteScope(locale)])).find(
1331
+ (node) => node.nodeId === SITE_SETTINGS_NODE,
1332
+ );
1333
+ return json({ fields: declared?.fields ?? [], values: settingsValues(declared, saved?.value) });
1334
+ },
1335
+
1336
+ "PUT /site-settings": async (request) => {
1337
+ const user = await allowed(request, "content");
1338
+ const declared = await siteSettings();
1339
+ if (!declared) throw new HttpError(404, "This site declares no settings of its own (src/site-settings.ts).");
1340
+ const body = await readJson(request);
1341
+ const scope = settingsScope(body.locale);
1342
+ const saved = (await brim.content.loadNodes([scope])).find((node) => node.nodeId === SITE_SETTINGS_NODE);
1343
+ // Only the values given change: an agent or a form can set one setting without sending all of them.
1344
+ const merged = {
1345
+ ...(typeof saved?.value === "object" && saved.value ? (saved.value as object) : {}),
1346
+ ...(body.values as object),
1347
+ };
1348
+ const values = parseSiteSettings(declared.fields, merged, false);
1349
+ await checkReferences(await contentTypes(), brim.items, settingsAsType(declared), {
1350
+ title: "",
1351
+ slug: "x",
1352
+ visibility: "published",
1353
+ data: values,
1354
+ });
1355
+ await rememberNode(user, scope, SITE_SETTINGS_NODE, "/", "changed");
1356
+ await brim.content.saveNode(scope, SITE_SETTINGS_NODE, SITE_SETTINGS_NODE, values);
1357
+ await changed(undefined);
1358
+ return json({ fields: declared.fields, values: settingsValues(declared, values) });
1359
+ },
1360
+
1361
+ "GET /types": async (request) => {
1362
+ await currentUser(request);
1363
+ const types = (await contentTypes()).map(({ component, ...type }) => ({ ...type, hasPage: Boolean(component) }));
1364
+ return json({ types });
1365
+ },
1366
+
1367
+ /** What the content still gets wrong (`brim check --content`): stand-in values, unused terms, unlisted pages. */
1368
+ "GET /check/content": async (request) => {
1369
+ await currentOwner(request);
1370
+ const declared = await siteSettings();
1371
+ const saved = await brim.content.allNodes();
1372
+ const languages = locales ? locales.locales : [undefined];
1373
+ const settings = languages.map((code) => {
1374
+ const scope = siteScope(code);
1375
+ const stored = saved.find((node) => node.scope === scope && node.nodeId === SITE_SETTINGS_NODE);
1376
+ return {
1377
+ locale: code && code !== locales?.defaultLocale ? code : "",
1378
+ values: settingsValues(declared, stored?.value),
1379
+ };
1380
+ });
1381
+ const findings = await checkContent({
1382
+ contentTypes: await contentTypes(),
1383
+ items: brim.items,
1384
+ nodes: saved,
1385
+ settings,
1386
+ patterns: options.patterns?.() ?? [],
1387
+ });
1388
+ return json({ findings });
1389
+ },
1390
+
1391
+ /**
1392
+ * The site's content as a seed (`brim seed --export`): every item, to keep in git as the site's starting
1393
+ * content. Owners only: it holds private items too.
1394
+ */
1395
+ "GET /seed": async (request) => {
1396
+ await currentOwner(request);
1397
+ const types = await contentTypes();
1398
+ const all = (await Promise.all(types.map((type) => brim.items.list(type.key)))).flat();
1399
+ return json({ items: exportSeed(types, all) });
1400
+ },
1401
+
1402
+ /**
1403
+ * Adds a seed's items that the site does not have yet (`brim seed`). Only adds: an item that exists (same type,
1404
+ * slug and language) stays exactly as it is. Everything is checked first, and one mistake adds nothing;
1405
+ * `dryRun` answers what would be added without adding it. Owners only.
1406
+ */
1407
+ "POST /seed": async (request) => {
1408
+ await currentOwner(request);
1409
+ const body = await readJson(request, MAX_SEED_BYTES);
1410
+ const plan = await planSeed(await contentTypes(), brim.items, body.items, localeOf);
1411
+ // `index` is the item's place in the seed, which the CLI uploads the pictures of before adding it.
1412
+ const planned = plan.create.map(({ index, type, draft, locale }) => ({
1413
+ index,
1414
+ type: type.key,
1415
+ slug: draft.slug,
1416
+ title: draft.title,
1417
+ locale,
1418
+ }));
1419
+ if (body.dryRun === true) return json({ create: planned, existing: plan.existing });
1420
+ const added = await applySeed(brim.items, plan);
1421
+ if (added.length > 0) await changed(undefined);
1422
+ return json({
1423
+ added: added.map(({ id, type, slug, locale }) => ({ id, type, slug, locale })),
1424
+ existing: plan.existing,
1425
+ });
1426
+ },
1427
+
1428
+ "GET /items": async (request) => {
1429
+ await currentUser(request);
1430
+ const params = new URL(request.url).searchParams;
1431
+ const type = await contentType(params.get("type"));
1432
+ const locale = params.has("locale") ? localeOf(params.get("locale")) : undefined;
1433
+ // An `ordered` type is listed in the owner's order, so the editor shows it as the site does. The list kept in
1434
+ // the server's memory is read again only where items changed: read whole, a type with a thousand items took
1435
+ // seconds on a remote database, each time the content browser opened.
1436
+ const items = await brim.items.listCached(type.key, {
1437
+ ...(type.ordered && { sort: "position" as const }),
1438
+ ...(locale !== undefined && { locale }),
1439
+ });
1440
+ // The editor asks with `?draft`: items as its preview shows them.
1441
+ return json({ items: params.has("draft") ? await brim.drafts.overlayItems(items) : items });
1442
+ },
1443
+
1444
+ /** The owner's order of an `ordered` type's items: `{ type, ids }`, its items written first, first to last. */
1445
+ "PUT /items/order": async (request) => {
1446
+ await allowed(request, "content");
1447
+ const body = await readJson(request);
1448
+ const type = await contentType(body.type);
1449
+ if (!type.ordered) {
1450
+ throw new ValidationError(`"${type.label}" is not put in order by hand: declare it with \`ordered: true\`.`);
1451
+ }
1452
+ if (!Array.isArray(body.ids) || body.ids.some((id: unknown) => typeof id !== "string")) {
1453
+ throw new ValidationError('"ids" must be a list of item ids.');
1454
+ }
1455
+ const items = await brim.items.reorder(type.key, body.ids as string[]);
1456
+ await changed(undefined);
1457
+ return json({ items: items.map(({ id, position }) => ({ id, position })) });
1458
+ },
1459
+
1460
+ "POST /items": async (request) => {
1461
+ await allowed(request, "content");
1462
+ const body = await readJson(request);
1463
+ const type = await contentType(body.type);
1464
+ // A new item stays out of sight until it is published, like a new page.
1465
+ const draft = parseItem(type, { ...body, visibility: body.visibility ?? "private" });
1466
+ await checkReferences(await contentTypes(), brim.items, type, draft);
1467
+ const locale = localeOf(body.locale);
1468
+ if (draft.visibility === "published") draft.data = withPublishedDate(type, draft.data);
1469
+ // An address made from the title that another item already has gets a number (lake-house-2), as the person
1470
+ // asked for no address of their own; one they typed themselves is refused instead, so they choose.
1471
+ const typedSlug = typeof body.slug === "string" && body.slug.trim() !== "";
1472
+ if (!typedSlug) draft.slug = await freeSlug(type.key, draft.slug, locale);
1473
+ const item = await brim.items.create(type.key, draft, { locale });
1474
+ const cleared = await clearRedirectFrom(normalizePagePath(itemPagePath(type, item, locales)));
1475
+ // A private item shows nobody anything yet, unless a redirect at its address went.
1476
+ await changed(undefined, item.visibility === "published" || cleared);
1477
+ return json({ item }, { status: 201 });
1478
+ },
1479
+
1480
+ /** A translation of an item into another of the site's languages: a private copy, linked to the original. */
1481
+ "POST /items/translate": async (request) => {
1482
+ await allowed(request, "content");
1483
+ const body = await readJson(request);
1484
+ const source = await existingItem(body);
1485
+ const type = await contentType(source.type);
1486
+ const locale = localeOf(body.locale);
1487
+ const family = await brim.items.translations(source);
1488
+ if (family.some((item) => item.locale === locale)) {
1489
+ throw new ValidationError("This item already has a translation in that language.");
1490
+ }
1491
+ const original = source.translationOf ?? source.id;
1492
+ const item = await brim.items.create(
1493
+ type.key,
1494
+ { title: source.title, slug: source.slug, visibility: "private", data: source.data },
1495
+ { locale, translationOf: original },
1496
+ );
1497
+ // Its page starts from the original's words where it has none yet: those on the template in the original's
1498
+ // language, or, for a page written in code, those on the original's own page.
1499
+ // The translation itself is private; words copied to the template of its language show on that language's
1500
+ // published items at once.
1501
+ let template = 0;
1502
+ if (type.component && locales) {
1503
+ const code = (stored: string): string => stored || locales.defaultLocale;
1504
+ template = await brim.content.copyNodes(typeScope(type.key, code(source.locale)), typeScope(type.key, code(locale)));
1505
+ } else if (!type.component) {
1506
+ await brim.content.copyNodes(ownPageScope(type, source, locales), ownPageScope(type, item, locales));
1507
+ }
1508
+ await changed(undefined, template > 0);
1509
+ return json({ item }, { status: 201 });
1510
+ },
1511
+
1512
+ /**
1513
+ * The same page in another language, filled with this page's content where it has none yet. A page written
1514
+ * in code must exist in that language in the code; a page added from a template is added there too.
1515
+ */
1516
+ "POST /pages/translate": async (request) => {
1517
+ await allowed(request, "content");
1518
+ if (!locales) throw new ValidationError("This site has one language: add others to Astro's i18n in its code.");
1519
+ const body = await readJson(request);
1520
+ const from = pagePathOf(body);
1521
+ const locale = requireString(body.locale, "locale");
1522
+ if (!locales.locales.includes(locale))
1523
+ throw new ValidationError(`"${locale}" is not one of the site's languages.`);
1524
+ const to = pathInLocale(from, locale, locales);
1525
+ if (to === from) throw new ValidationError("This page is already in that language.");
1526
+ const coded = pages().some((page) => normalizePagePath(page) === to);
1527
+ const target = await brim.content.page(to);
1528
+ let created = false;
1529
+ if (!coded && !target.template) {
1530
+ const source = await brim.content.page(from);
1531
+ if (!source.template) {
1532
+ throw new ValidationError(
1533
+ `This page has no ${locale.toUpperCase()} version in the site yet (${to}). It has to be added in the site's code first (src/pages), then it can be translated here.`,
1534
+ );
1535
+ }
1536
+ await brim.content.createPage(to, source.template, source.title ?? "", "private");
1537
+ created = true;
1538
+ }
1539
+ const copied = await brim.content.copyNodes(pageScope(from), pageScope(to));
1540
+ const source = await brim.content.page(from);
1541
+ const seo = Object.keys(target.seo).length === 0 && Object.keys(source.seo).length > 0;
1542
+ if (seo) await brim.content.setPageSeo(to, source.seo);
1543
+ // A page added here is private; one that was there already shows what was copied to it.
1544
+ await changed(to, !created && (copied > 0 || seo));
1545
+ return json({ path: to, created, copied });
1546
+ },
1547
+
1548
+ "PUT /items": async (request) => {
1549
+ const user = await allowed(request, "content");
1550
+ const body = await readJson(request);
1551
+ const existing = await existingItem(body);
1552
+ const type = await contentType(existing.type);
1553
+ if (body.draft === true) {
1554
+ const parsed = parseItem(type, { ...body, visibility: existing.visibility });
1555
+ assertTermSlug(await contentTypes(), existing, parsed.slug);
1556
+ return json(await draftItem(existing, parsed, pagePathOf(body)));
1557
+ }
1558
+ const draft = parseItem(type, body);
1559
+ assertTermSlug(await contentTypes(), existing, draft.slug);
1560
+ if (draft.visibility === "published" && existing.visibility === "private")
1561
+ draft.data = withPublishedDate(type, draft.data);
1562
+ const types = await contentTypes();
1563
+ await checkReferences(types, brim.items, type, draft);
1564
+ await rememberItem(user, existing, "changed");
1565
+ const item = await brim.items.update(existing, draft);
1566
+ await itemMoved(type, existing, item);
1567
+ await termMoved(types, type, existing, item);
1568
+ // Saved as a whole from its form: what was drafted of it is settled.
1569
+ await brim.drafts.set("item", existing.id, undefined, "");
1570
+ await changed(undefined);
1571
+ return json({ item });
1572
+ },
1573
+
1574
+ "DELETE /items": async (request) => {
1575
+ const user = await allowed(request, "publish");
1576
+ const existing = await existingItem(await readJson(request));
1577
+ // An item whose type was removed from the code can still be deleted; there is no page of it to clear.
1578
+ const types = await contentTypes();
1579
+ const type = types.find((candidate) => candidate.key === existing.type);
1580
+ // A term items still point at stays until they point elsewhere; its translations share its slug, so only the
1581
+ // last one in use is guarded.
1582
+ if (
1583
+ !(await brim.items.list(existing.type)).some(
1584
+ (other) => other.id !== existing.id && other.slug === existing.slug,
1585
+ )
1586
+ ) {
1587
+ await assertUnused(types, brim.items, existing);
1588
+ }
1589
+ const ownScope = type && !type.component ? ownPageScope(type, existing, locales) : undefined;
1590
+ // An original's translations are remembered, so putting it back makes it their original again.
1591
+ const translations = existing.translationOf ? [] : await brim.items.translationIds(existing.id);
1592
+ await rememberItem(
1593
+ user,
1594
+ existing,
1595
+ "deleted",
1596
+ ownScope ? await brim.content.loadNodes([ownScope]) : [],
1597
+ true,
1598
+ translations,
1599
+ );
1600
+ await brim.items.remove(existing.id);
1601
+ if (ownScope) await brim.content.removeNodes(ownScope);
1602
+ await changed(undefined);
1603
+ return json({});
1604
+ },
1605
+
1606
+ // Who can see an item changes at once, never with the draft: it leaves the item's drafted content alone.
1607
+ "PUT /items/visibility": async (request) => {
1608
+ const user = await allowed(request, "publish");
1609
+ const body = await readJson(request);
1610
+ const existing = await existingItem(body);
1611
+ const visibility = visibilityOf(body.visibility);
1612
+ await rememberItem(user, existing, "changed");
1613
+ const publishing = visibility === "published" && existing.visibility === "private";
1614
+ const type = publishing ? (await contentTypes()).find(({ key }) => key === existing.type) : undefined;
1615
+ const data = type ? withPublishedDate(type, existing.data) : existing.data;
1616
+ const item = await brim.items.update(existing, { ...existing, data, visibility });
1617
+ // What waits in the draft is saved over the item later, so it gets the date too.
1618
+ const draft = type && ((await brim.drafts.get("item", item.id)) as ItemContentDraft | undefined);
1619
+ if (type && draft) {
1620
+ const page = (await brim.drafts.all()).find((row) => row.target === "item" && row.key === item.id)?.page ?? "";
1621
+ await brim.drafts.set("item", item.id, { ...draft, data: withPublishedDate(type, draft.data) }, page);
1622
+ }
1623
+ await changed(undefined);
1624
+ return json({ item: await brim.drafts.overlayItem(item) });
1625
+ },
1626
+
1627
+ // How many changes nobody has saved yet, and on which pages.
1628
+ "GET /drafts": async (request) => {
1629
+ await currentUser(request);
1630
+ const rows = await brim.drafts.all();
1631
+ return json({ drafts: rows.length, pages: [...new Set(rows.map((row) => row.page).filter(Boolean))] });
1632
+ },
1633
+
1634
+ // Undo and redo: one thing's draft put back as it was before or after a change. `null` is no draft.
1635
+ "PUT /drafts": async (request) => {
1636
+ const user = await allowed(request, "content");
1637
+ const body = await readJson(request);
1638
+ const target = requireString(body.target, "target") as DraftTarget;
1639
+ const key = requireString(body.key, "key");
1640
+ const value = await checkedDraft(user, target, key, body.value ?? null);
1641
+ const answer = await writeDraft(target, key, value, typeof body.path === "string" ? body.path : "");
1642
+ const live = target === "item" ? await brim.items.get(key) : undefined;
1643
+ return json({ ...answer, ...(live && { item: await brim.drafts.overlayItem(live) }) });
1644
+ },
1645
+
1646
+ // Save: every draft becomes what visitors see.
1647
+ "POST /drafts/save": async (request) => {
1648
+ const user = await allowed(request, "content");
1649
+ const result = await saveDrafts(user);
1650
+ return json({ ...result, drafts: await brim.drafts.count() });
1651
+ },
1652
+
1653
+ // Discard: every draft is thrown away and the editor shows what is saved.
1654
+ "DELETE /drafts": async (request) => {
1655
+ await allowed(request, "content");
1656
+ await brim.drafts.clear();
1657
+ return json({ drafts: 0 });
1658
+ },
1659
+
1660
+ /**
1661
+ * What the owner saved on a page (`?path=/contact`): its own elements, the template's when it is an item's page,
1662
+ * and the site's shared ones (header, footer, settings), each with its kind and value. What code alone draws,
1663
+ * untouched in the editor, is not here: the page shows the code's own words for it. To see, before a change to a
1664
+ * page's code, what the owner wrote there.
1665
+ */
1666
+ "GET /nodes": async (request) => {
1667
+ await currentUser(request);
1668
+ const path = normalizePagePath(new URL(request.url).searchParams.get("path") ?? "/");
1669
+ const itemPage = itemPageOf(await contentTypes(), path, locales);
1670
+ const locale = localeOfPath(path, locales);
1671
+ const scopes = {
1672
+ page: pageScope(path),
1673
+ ...(itemPage && { template: typeScope(itemPage.type.key, locale) }),
1674
+ site: siteScope(locale),
1675
+ };
1676
+ const saved = await brim.content.loadNodes(Object.values(scopes));
1677
+ const of = (scope: string) =>
1678
+ saved
1679
+ .filter((node) => node.scope === scope)
1680
+ .map(({ nodeId, kind, value }) => ({ nodeId, kind, value }))
1681
+ .sort((a, b) => a.nodeId.localeCompare(b.nodeId));
1682
+ return json({
1683
+ path,
1684
+ page: of(scopes.page),
1685
+ ...(scopes.template && { template: of(scopes.template) }),
1686
+ site: of(scopes.site),
1687
+ });
1688
+ },
1689
+
1690
+ "PUT /nodes": async (request) => {
1691
+ const user = await allowed(request, "content");
1692
+ const body = await readJson(request);
1693
+ const path = pagePathOf(body);
1694
+ const nodeId = nodeIdOf(body);
1695
+ const kind = requireString(body.kind, "kind");
1696
+ // A field element has nothing of its own to keep: its value is the item's field, checked like the item form.
1697
+ if (kind === FIELD_KIND) {
1698
+ if (body.item === undefined) {
1699
+ throw new ValidationError(`A ${FIELD_KIND} element is changed through its item: pass "item" and "field".`);
1700
+ }
1701
+ if (typeof body.value !== "object" || body.value === null) {
1702
+ throw new ValidationError('"value" must be an object.');
1703
+ }
1704
+ return saveToItem(user, body, nodeId, kind, body.value as Record<string, unknown>);
1705
+ }
1706
+ const value = nodeValueOf(kind, body.value);
1707
+ if (body.item !== undefined) return saveToItem(user, body, nodeId, kind, value as Record<string, unknown>);
1708
+ if (body.scope === "template") need(user, "templates");
1709
+ const scope = await scopeOf(body, path);
1710
+ if (body.draft === true) {
1711
+ return json({ nodeId, kind, value, ...(await writeDraft("node", `${scope}\n${nodeId}`, { kind, value }, path)) });
1712
+ }
1713
+ await rememberNode(user, scope, nodeId, path, "changed");
1714
+ await brim.content.saveNode(scope, nodeId, kind, value);
1715
+ await changed(body.scope === "page" ? path : undefined);
1716
+ return json({ nodeId, kind, value });
1717
+ },
1718
+
1719
+ "DELETE /nodes": async (request) => {
1720
+ const user = await allowed(request, "content");
1721
+ const body = await readJson(request);
1722
+ const path = pagePathOf(body);
1723
+ if (body.scope === "template") need(user, "templates");
1724
+ const scope = await scopeOf(body, path);
1725
+ if (body.draft === true) return json(await writeDraft("node", `${scope}\n${nodeIdOf(body)}`, { reset: true }, path));
1726
+ await rememberNode(user, scope, nodeIdOf(body), path, "reset");
1727
+ await brim.content.resetNode(scope, nodeIdOf(body));
1728
+ await changed(body.scope === "page" ? path : undefined);
1729
+ return json({});
1730
+ },
1731
+
1732
+ // What changed lately, newest first: on one page (`?path=`), or on the whole site.
1733
+ "GET /history": async (request) => {
1734
+ await currentUser(request);
1735
+ const params = new URL(request.url).searchParams;
1736
+ const path = params.get("path");
1737
+ return json({
1738
+ history: await brim.history.list({
1739
+ page: path === null ? undefined : normalizePagePath(path),
1740
+ limit: Number(params.get("limit")) || undefined,
1741
+ }),
1742
+ });
1743
+ },
1744
+
1745
+ // Takes one change back: the element, item or deleted page becomes what it was before that change.
1746
+ "POST /history/restore": async (request) => {
1747
+ const user = await currentUser(request);
1748
+ const record = await brim.history.get(requireString((await readJson(request)).id, "id"));
1749
+ if (!record) throw new HttpError(404, "This change is no longer in the site's history.");
1750
+ await restore(user, record);
1751
+ await changed(undefined);
1752
+
1753
+ return json({ restored: { target: record.target, title: record.title, page: record.page } });
1754
+ },
1755
+ };
1756
+
1757
+ /** Routes with a name in their address, tried when no fixed route matches. */
1758
+ const namedRoutes: {
1759
+ method: string;
1760
+ pattern: RegExp;
1761
+ handle: (request: Request, name: string) => Promise<Response>;
1762
+ }[] = [
1763
+ {
1764
+ // One set's icons whose name contains `q`: a pack can hold thousands, so the editor asks as it is typed.
1765
+ method: "GET",
1766
+ pattern: /^\/icons\/([^/]+)$/,
1767
+ handle: async (request, set) => {
1768
+ await currentUser(request);
1769
+ const query = new URL(request.url).searchParams;
1770
+ return json(icons.search(safeDecode(set), query.get("q") ?? "", Number(query.get("limit")) || undefined));
1771
+ },
1772
+ },
1773
+ {
1774
+ /**
1775
+ * One file a visitor attached to a form message, for a role that may read messages (never a visitor). The file is
1776
+ * found through the message's own list, by two ids: no name or path from the request reaches the storage. Always a download, never shown in the page, never cached.
1777
+ */
1778
+ method: "GET",
1779
+ pattern: /^\/responses\/([^/]+\/files\/[^/]+)$/,
1780
+ handle: async (request, ids) => {
1781
+ await allowed(request, "responses");
1782
+ const [responseId = "", , fileId = ""] = ids.split("/");
1783
+ const uuid = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
1784
+ if (!uuid.test(responseId) || !uuid.test(fileId)) throw new HttpError(404, "This file does not exist.");
1785
+ const file = (await brim.forms.get(responseId))?.files.find((candidate) => candidate.id === fileId);
1786
+ if (!file || !formFiles) throw new HttpError(404, "This file does not exist.");
1787
+ const bytes = await formFiles.read(responseId, fileId);
1788
+ // Listed but not there: the site's content was moved (export, restore) without its files.
1789
+ if (!bytes) throw new HttpError(404, "This file is no longer kept on this site.");
1790
+ return fileDownload(file, bytes);
1791
+ },
1792
+ },
1793
+ {
1794
+ // Whether an uploaded video is ready to play yet.
1795
+ method: "GET",
1796
+ pattern: /^\/videos\/([^/]+)$/,
1797
+ handle: async (request, id) => {
1798
+ await currentUser(request);
1799
+ return json(await videoHost().status(safeDecode(id)));
1800
+ },
1801
+ },
1802
+ {
1803
+ // Removes an uploaded video from the host for good. No content changes: a block that showed it keeps its
1804
+ // address, so this is not a change that marks the request as one visitors can see.
1805
+ method: "DELETE",
1806
+ pattern: /^\/videos\/([^/]+)$/,
1807
+ handle: async (request, id) => {
1808
+ await allowed(request, "content");
1809
+ await videoHost().delete(safeDecode(id));
1810
+ return json({ deleted: true });
1811
+ },
1812
+ },
1813
+ ];
1814
+
1815
+ async function api(request: Request, info: RequestInfo, route: string): Promise<Response> {
1816
+ try {
1817
+ const fixed = routes[`${request.method} ${route}`];
1818
+ const named = fixed
1819
+ ? undefined
1820
+ : namedRoutes.find((entry) => entry.method === request.method && entry.pattern.test(route));
1821
+ if (!fixed && !named) throw new HttpError(404, "Not found.");
1822
+ // A browser could be tricked into sending the cookie from another site, never a bearer token.
1823
+ if (request.method !== "GET" && !bearerToken(request)) assertSameOrigin(request);
1824
+ if (fixed) return await fixed(request, info);
1825
+ return await named!.handle(request, named!.pattern.exec(route)?.[1] ?? "");
1826
+ } catch (error) {
1827
+ if (error instanceof HttpError) return json({ error: error.message }, { status: error.status });
1828
+ if (error instanceof ValidationError) return json({ error: error.message }, { status: 422 });
1829
+ throw error;
1830
+ }
1831
+ }
1832
+
1833
+ /** Tools of the site's MCP go through the same API as the editor, with the same checks. */
1834
+ async function mcp(request: Request, info: RequestInfo): Promise<Response> {
1835
+ const authorization = request.headers.get("authorization") ?? "";
1836
+ try {
1837
+ if (!bearerToken(request)) throw new HttpError(401, "Send an access token: Authorization: Bearer <token>.");
1838
+ await currentUser(request);
1839
+ } catch (error) {
1840
+ if (!(error instanceof HttpError)) throw error;
1841
+ return json({ error: error.message }, { status: error.status, headers: { "www-authenticate": "Bearer" } });
1842
+ }
1843
+
1844
+ return handleMcp(request, toolContext(request, info, { authorization }));
1845
+ }
1846
+
1847
+ /**
1848
+ * What the MCP's tools run with: the editor's API called as the person asking, with their token or their signed-in
1849
+ * session, so their role and every check of the API apply.
1850
+ */
1851
+ function toolContext(request: Request, info: RequestInfo, credentials: Record<string, string>): ToolContext {
1852
+ const origin = requestOrigin(request);
1853
+ // A session's cookie is sent with the site's own origin: the API checks it on every change.
1854
+ const headers = credentials.authorization ? credentials : { ...credentials, origin };
1855
+ return {
1856
+ api: async (method, route, body) => {
1857
+ const url = new URL(`${API_PATH}${route}`, origin);
1858
+ const response = await api(
1859
+ new Request(url, {
1860
+ method,
1861
+ headers: { ...headers, ...(body && { "content-type": "application/json" }) },
1862
+ ...(body && { body: JSON.stringify(body) }),
1863
+ }),
1864
+ info,
1865
+ url.pathname.slice(API_PATH.length),
1866
+ );
1867
+ const answer = (await response.json()) as Record<string, unknown>;
1868
+ if (!response.ok) throw new Error(String(answer.error ?? `The site answered ${response.status}.`));
1869
+ return answer;
1870
+ },
1871
+ renderPage: async (path) => {
1872
+ // Asked from this server itself, never from an address the request's headers name: those are the
1873
+ // caller's to write, and the token must not travel to a host of their choosing.
1874
+ const origin = info.serverOrigin ?? new URL(request.url).origin;
1875
+ // "//host/x" and "/\\host/x" are addresses of another host for the URL parser: refused, so the token stays here.
1876
+ if (!path.startsWith("/") || /^\/[/\\]/.test(path) || path.includes("\\")) {
1877
+ throw new HttpError(400, `"${path}" is not a page of this site.`);
1878
+ }
1879
+ const url = new URL(normalizePagePath(path), origin);
1880
+ if (url.origin !== new URL(origin).origin) throw new HttpError(400, `"${path}" is not a page of this site.`);
1881
+ if (options.renderPage) return options.renderPage(url);
1882
+ // The token (or session) travels along, so the server draws the page as its editor sees it.
1883
+ const response = await fetch(url, { headers, redirect: "manual" });
1884
+ if (!response.ok) throw new Error(`The page ${path} answered ${response.status}.`);
1885
+ return response.text();
1886
+ },
1887
+ storedValue: async (path, scope, nodeId) => {
1888
+ const nodes = await brim.content.loadNodes([await scopeOf({ scope }, normalizePagePath(path))]);
1889
+ return nodes.find((node) => node.nodeId === nodeId)?.value;
1890
+ },
1891
+ // Through the API's own route, so the token's role, the size limit and the folder check all apply.
1892
+ upload: async (bytes, name, folder) => {
1893
+ const url = new URL(`${API_PATH}/media`, origin);
1894
+ const response = await api(
1895
+ new Request(url, {
1896
+ method: "POST",
1897
+ headers: {
1898
+ ...headers,
1899
+ "content-length": String(bytes.byteLength),
1900
+ "x-file-name": encodeURIComponent(name),
1901
+ ...(folder && { "x-media-folder": encodeURIComponent(folder) }),
1902
+ },
1903
+ body: new Uint8Array(bytes),
1904
+ }),
1905
+ info,
1906
+ "/media",
1907
+ );
1908
+ const answer = (await response.json()) as Record<string, unknown>;
1909
+ if (!response.ok) throw new Error(String(answer.error ?? `The site answered ${response.status}.`));
1910
+ return answer;
1911
+ },
1912
+ fetchImage: (url) => fetchImage(url, options.fetch),
1913
+ };
1914
+ }
1915
+
1916
+ async function asset(name: string): Promise<Response> {
1917
+ const contentType = ASSETS[name];
1918
+ if (!contentType) return new Response("Not found", { status: 404 });
1919
+ try {
1920
+ const body = await readFile(new URL(name, assetsDirectory));
1921
+ return new Response(body, { headers: { "content-type": contentType, "cache-control": "no-cache" } });
1922
+ } catch {
1923
+ return new Response("The editor is not built. Run `pnpm --filter @brimsites/brimjs build:editor`.", { status: 500 });
1924
+ }
1925
+ }
1926
+
1927
+ async function respond(request: Request, info: RequestInfo, pathname: string): Promise<Response> {
1928
+ if (pathname.startsWith(`${API_PATH}/`)) return api(request, info, pathname.slice(API_PATH.length));
1929
+ if (pathname === MCP_PATH) return mcp(request, info);
1930
+ if (pathname.startsWith(`${ASSETS_PATH}/`)) return asset(pathname.slice(ASSETS_PATH.length + 1));
1931
+ // `/admin` is where people look first: it opens the editor at its own address.
1932
+ if (pathname === ADMIN_PATH || pathname === `${ADMIN_PATH}/`) {
1933
+ return new Response(null, {
1934
+ status: 302,
1935
+ headers: { location: `${ADMIN_PATH}/edit`, "cache-control": "no-store" },
1936
+ });
1937
+ }
1938
+ return new Response(editorPage(options.identity ?? {}), {
1939
+ headers: {
1940
+ "content-type": "text/html; charset=utf-8",
1941
+ "cache-control": "no-store",
1942
+
1943
+ "x-robots-tag": "noindex",
1944
+ },
1945
+ });
1946
+ }
1947
+
1948
+ return async (request, info) => {
1949
+ const { pathname } = new URL(request.url);
1950
+ if (pathname !== ADMIN_PATH && !pathname.startsWith(`${ADMIN_PATH}/`)) return undefined;
1951
+ const changes = { live: false };
1952
+ const response = await liveChanges.run(changes, () => respond(request, info, pathname));
1953
+ // Only a change that was accepted: a refused one (an error after a partial write included) says nothing.
1954
+ if (changes.live && response.status < 400) response.headers.set(LIVE_CHANGE_HEADER, "live");
1955
+ for (const [name, value] of Object.entries(ADMIN_HEADERS)) {
1956
+ if (!response.headers.has(name)) response.headers.set(name, value);
1957
+ }
1958
+ return response;
1959
+ };
1960
+ }
1961
+
1962
+ /**
1963
+ * On everything under /admin. The editor is never shown inside another site's page, where a visitor could be led
1964
+ * to click in it without seeing it; its answers are read as the type they say; and its addresses, which can carry a
1965
+ * sign-in link's token, are not passed on to other sites.
1966
+ */
1967
+ const ADMIN_HEADERS: Record<string, string> = {
1968
+ "content-security-policy": "frame-ancestors 'self'",
1969
+ "x-frame-options": "SAMEORIGIN",
1970
+ "x-content-type-options": "nosniff",
1971
+ "referrer-policy": "same-origin",
1972
+ };
1973
+
1974
+ /** The editor's page: the site's name in its tab title, and the site's favicon when it has one. */
1975
+ function editorPage(identity: SiteIdentity): string {
1976
+ const escape = (text: string) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
1977
+ const favicon = identity.favicon;
1978
+ const type = favicon ? faviconType(favicon) : undefined;
1979
+ const link = favicon ? `<link rel="icon" href="${escape(favicon)}"${type ? ` type="${type}"` : ""} />` : "";
1980
+ return EDITOR_PAGE.replace("<!--favicon-->", link).replace(
1981
+ "<title>Edit site</title>",
1982
+ `<title>${identity.name ? `Edit · ${escape(identity.name)}` : "Edit site"}</title>`,
1983
+ );
1984
+ }
1985
+
1986
+ const EDITOR_PAGE = `<!doctype html>
1987
+ <html lang="en">
1988
+ <head>
1989
+ <meta charset="utf-8" />
1990
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1991
+ <meta name="robots" content="noindex" />
1992
+ <title>Edit site</title>
1993
+ <!--favicon-->
1994
+ <link rel="stylesheet" href="${ASSETS_PATH}/editor.css" />
1995
+ </head>
1996
+ <body>
1997
+ <div id="brim-editor"></div>
1998
+ <script type="module" src="${ASSETS_PATH}/editor.js"></script>
1999
+ </body>
2000
+ </html>
2001
+ `;
2002
+
2003
+ /**
2004
+ * The cookie of a new session, and the removal of an old one under /admin (kept there before the cookie covered
2005
+ * the whole site): the browser would send that one first on every editor request.
2006
+ */
2007
+ function signInHeaders(request: Request, token: string, maxAgeSeconds: number): Headers {
2008
+ const headers = new Headers({ "set-cookie": sessionCookie(request, token, maxAgeSeconds) });
2009
+ headers.append("set-cookie", sessionCookie(request, "", 0, ADMIN_PATH));
2010
+ return headers;
2011
+ }
2012
+
2013
+ function sessionCookie(request: Request, token: string, maxAgeSeconds: number, path = "/"): string {
2014
+ const secure = requestOrigin(request).startsWith("https:") ? "; Secure" : "";
2015
+ // Sent with page requests too: the server shows a signed-in editor the live, editable page.
2016
+ return `${SESSION_COOKIE}=${token}; Path=${path}; Max-Age=${maxAgeSeconds}; HttpOnly; SameSite=Lax${secure}`;
2017
+ }
2018
+
2019
+ /** An email in the name of a limit: as accounts know it, and hashed, so what was typed is neither kept nor long. */
2020
+ function emailKey(email: string): string {
2021
+ return createHash("sha256").update(normalizeEmail(email)).digest("hex").slice(0, 32);
2022
+ }
2023
+
2024
+ /** What wrong passwords are counted by: the visitor's address first, then the account. */
2025
+ function loginKeys(info: RequestInfo, email: string): string[] {
2026
+ return [`login:address:${info.clientAddress}`, `login:email:${emailKey(email)}`];
2027
+ }
2028
+
2029
+ /** `text` is a primitive with its own value shape, though BrimCMS also had a block by that name. */
2030
+ function isPrimitive(kind: string): boolean {
2031
+ return kind === "text";
2032
+ }
2033
+
2034
+ function requireString(input: unknown, name: string): string {
2035
+ if (typeof input !== "string" || input === "") throw new HttpError(400, `"${name}" is required.`);
2036
+ return input;
2037
+ }
2038
+
2039
+ /** Whether two JSON values say the same, so a draft that changes nothing is no draft. */
2040
+ function sameJson(a: unknown, b: unknown): boolean {
2041
+ return JSON.stringify(a) === JSON.stringify(b);
2042
+ }
2043
+
2044
+ function pagePathOf(body: Record<string, unknown>): string {
2045
+ const path = requireString(body.path, "path");
2046
+ if (!path.startsWith("/")) throw new HttpError(400, '"path" must start with "/".');
2047
+ return normalizePagePath(path);
2048
+ }
2049
+
2050
+ const MAX_TITLE = 300;
2051
+
2052
+ function titleOf(body: Record<string, unknown>): string {
2053
+ const title = typeof body.title === "string" ? body.title.trim() : "";
2054
+ if (title === "") throw new ValidationError("The title is required.");
2055
+ if (title.length > MAX_TITLE) throw new ValidationError("The title is too long.");
2056
+ return title;
2057
+ }
2058
+
2059
+ /** An article's data as it is published: dated today, unless it says a date already. */
2060
+ function withPublishedDate(type: ContentType, data: Record<string, unknown>): Record<string, unknown> {
2061
+ if (!type.article || !standardField(type, "published") || data.published) return data;
2062
+ return { ...data, published: new Date().toISOString().slice(0, 10) };
2063
+ }
2064
+
2065
+ function visibilityOf(input: unknown): Visibility {
2066
+ if (input !== "private" && input !== "published") {
2067
+ throw new HttpError(400, '"visibility" must be "private" or "published".');
2068
+ }
2069
+ return input;
2070
+ }
2071
+
2072
+ /** The first segments of a type's addresses, which no page the owner adds may start with. */
2073
+ function addressPrefixes(type: ContentType): string[] {
2074
+ const first = itemPathSegments(type)[0];
2075
+ return [...new Set([type.slug, ...(first && "fixed" in first ? [first.fixed] : [])])];
2076
+ }
2077
+
2078
+ /**
2079
+ * Where the page of an item of a type without a template, written in the site's code, keeps what the owner placed on
2080
+ * it. A type with a template keeps that on the template instead, shared by all its items.
2081
+ */
2082
+ function ownPageScope(type: ContentType, item: Pick<Item, "slug" | "locale" | "data">, locales?: LocaleConfig): string {
2083
+ return pageScope(itemPagePath(type, item, locales));
2084
+ }
2085
+
2086
+ /** Site Settings are kept beside the elements but checked field by field: they are not saved as an element. */
2087
+ function assertElement(nodeId: string): void {
2088
+ if (nodeId !== SITE_SETTINGS_NODE) return;
2089
+ throw new HttpError(400, "Site Settings are changed in Site Settings, or with brim_set_site_settings.");
2090
+ }
2091
+
2092
+ function nodeIdOf(body: Record<string, unknown>): string {
2093
+ const nodeId = requireString(body.nodeId, "nodeId");
2094
+ if (!isNodeId(nodeId)) throw new HttpError(400, `"${nodeId}" is not a valid nodeId.`);
2095
+ assertElement(nodeId);
2096
+ return nodeId;
2097
+ }
2098
+
2099
+ /** A name taken from an address; one that is not valid percent-encoding matches nothing. */
2100
+ function safeDecode(value: string): string {
2101
+ try {
2102
+ return decodeURIComponent(value);
2103
+ } catch {
2104
+ return "";
2105
+ }
2106
+ }