@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.
- package/LICENSE +110 -0
- package/README.md +22 -2
- package/bin/brim.js +5 -0
- package/dist/cli.js +3802 -0
- package/editor-dist/editor.css +1 -0
- package/editor-dist/editor.js +91 -0
- package/package.json +71 -3
- package/skills/brim-convert/SKILL.md +256 -0
- package/skills/brim-hosting/SKILL.md +221 -0
- package/src/astro-shim.d.ts +5 -0
- package/src/auth/accounts.ts +341 -0
- package/src/auth/password.ts +34 -0
- package/src/auth/permissions.ts +44 -0
- package/src/blocks/accordion/Accordion.astro +48 -0
- package/src/blocks/accordion/accordion.css +63 -0
- package/src/blocks/analytics/Analytics.astro +45 -0
- package/src/blocks/analytics/ConsentBanner.astro +41 -0
- package/src/blocks/analytics/analytics.client.ts +125 -0
- package/src/blocks/analytics/analytics.css +51 -0
- package/src/blocks/analytics/consent.ts +51 -0
- package/src/blocks/button/Button.astro +64 -0
- package/src/blocks/button/button.css +100 -0
- package/src/blocks/carousel/Carousel.astro +140 -0
- package/src/blocks/carousel/carousel.client.ts +153 -0
- package/src/blocks/carousel/carousel.css +181 -0
- package/src/blocks/data/icons.ts +285 -0
- package/src/blocks/data/image-shapes.ts +91 -0
- package/src/blocks/data/social-icons.ts +41 -0
- package/src/blocks/data/social-networks.ts +256 -0
- package/src/blocks/divider/Divider.astro +27 -0
- package/src/blocks/divider/divider.css +17 -0
- package/src/blocks/form/Captcha.astro +27 -0
- package/src/blocks/form/Form.astro +250 -0
- package/src/blocks/form/FormField.astro +138 -0
- package/src/blocks/form/Newsletter.astro +80 -0
- package/src/blocks/form/form.client.ts +339 -0
- package/src/blocks/form/form.css +271 -0
- package/src/blocks/gallery/ImageGallery.astro +126 -0
- package/src/blocks/gallery/gallery.css +43 -0
- package/src/blocks/gallery/lightbox.client.ts +178 -0
- package/src/blocks/gallery/lightbox.css +134 -0
- package/src/blocks/icon/Icon.astro +41 -0
- package/src/blocks/icon/icon.css +16 -0
- package/src/blocks/image/Image.astro +158 -0
- package/src/blocks/image/image.css +42 -0
- package/src/blocks/images.ts +64 -0
- package/src/blocks/in-editor.client.ts +8 -0
- package/src/blocks/listing/Listing.astro +288 -0
- package/src/blocks/listing/ListingCards.astro +48 -0
- package/src/blocks/listing/listing.css +136 -0
- package/src/blocks/listing/query.ts +363 -0
- package/src/blocks/map/Map.astro +75 -0
- package/src/blocks/map/map.css +32 -0
- package/src/blocks/schemas/accordion.ts +118 -0
- package/src/blocks/schemas/button.ts +78 -0
- package/src/blocks/schemas/carousel.ts +133 -0
- package/src/blocks/schemas/divider.ts +29 -0
- package/src/blocks/schemas/form-field-types.ts +29 -0
- package/src/blocks/schemas/form.ts +350 -0
- package/src/blocks/schemas/icon.ts +24 -0
- package/src/blocks/schemas/image-gallery.ts +54 -0
- package/src/blocks/schemas/image.ts +87 -0
- package/src/blocks/schemas/index.ts +33 -0
- package/src/blocks/schemas/listing.ts +14 -0
- package/src/blocks/schemas/map.ts +81 -0
- package/src/blocks/schemas/newsletter.ts +324 -0
- package/src/blocks/schemas/social-media.ts +348 -0
- package/src/blocks/schemas/text.ts +151 -0
- package/src/blocks/schemas/video.ts +57 -0
- package/src/blocks/search/Search.astro +147 -0
- package/src/blocks/search/search.css +69 -0
- package/src/blocks/search/state.ts +28 -0
- package/src/blocks/settings.ts +94 -0
- package/src/blocks/social/SocialMedia.astro +102 -0
- package/src/blocks/social/social-links.ts +16 -0
- package/src/blocks/social/social.css +31 -0
- package/src/blocks/theme.ts +35 -0
- package/src/blocks/types.ts +52 -0
- package/src/blocks/video/Video.astro +90 -0
- package/src/blocks/video/video-source.ts +77 -0
- package/src/blocks/video/video.client.ts +43 -0
- package/src/blocks/video/video.css +29 -0
- package/src/check.ts +1119 -0
- package/src/cli.ts +493 -0
- package/src/components/Blocks.astro +68 -0
- package/src/components/Field.astro +61 -0
- package/src/components/Footer.astro +36 -0
- package/src/components/Link.astro +18 -0
- package/src/components/MobileMenu.astro +77 -0
- package/src/components/Navbar.astro +42 -0
- package/src/components/RichText.astro +32 -0
- package/src/components/Seo.astro +202 -0
- package/src/components/Setting.astro +46 -0
- package/src/components/Shared.astro +17 -0
- package/src/components/Text.astro +91 -0
- package/src/components/blocks.css +86 -0
- package/src/components/index.ts +27 -0
- package/src/components/mobile-menu.client.ts +21 -0
- package/src/components/mobile-menu.css +52 -0
- package/src/components/text.css +48 -0
- package/src/config.ts +413 -0
- package/src/content/block-layout.ts +63 -0
- package/src/content/block-values.ts +48 -0
- package/src/content/content-check.ts +174 -0
- package/src/content/content-types.ts +408 -0
- package/src/content/drafts.ts +115 -0
- package/src/content/feed.ts +237 -0
- package/src/content/field-types.ts +107 -0
- package/src/content/history.ts +140 -0
- package/src/content/ids.ts +50 -0
- package/src/content/image-size.ts +212 -0
- package/src/content/image-sizes.ts +126 -0
- package/src/content/item-fields.ts +110 -0
- package/src/content/item-head.ts +126 -0
- package/src/content/item-image.ts +26 -0
- package/src/content/item-path.ts +122 -0
- package/src/content/items.ts +580 -0
- package/src/content/language-scopes.ts +40 -0
- package/src/content/media.ts +271 -0
- package/src/content/menus.ts +51 -0
- package/src/content/page-templates.ts +52 -0
- package/src/content/redirects.ts +112 -0
- package/src/content/references.ts +165 -0
- package/src/content/rich-text.ts +63 -0
- package/src/content/search.ts +167 -0
- package/src/content/seed.ts +229 -0
- package/src/content/site-settings.ts +111 -0
- package/src/content/sitemap.ts +143 -0
- package/src/content/store.ts +225 -0
- package/src/content/tags.ts +67 -0
- package/src/content/text-default.ts +139 -0
- package/src/content/types.ts +137 -0
- package/src/content/validate.ts +253 -0
- package/src/content/validation-error.ts +2 -0
- package/src/db/cached.ts +140 -0
- package/src/db/database.ts +15 -0
- package/src/db/libsql.ts +29 -0
- package/src/db/schema.ts +189 -0
- package/src/db/url.ts +44 -0
- package/src/editor/client/BlockSettings.tsx +1063 -0
- package/src/editor/client/Chrome.tsx +284 -0
- package/src/editor/client/ContentBrowser.tsx +1299 -0
- package/src/editor/client/Editor.tsx +1756 -0
- package/src/editor/client/HistoryPanel.tsx +114 -0
- package/src/editor/client/ImagesWidget.tsx +113 -0
- package/src/editor/client/Inspector.tsx +127 -0
- package/src/editor/client/ItemForm.tsx +535 -0
- package/src/editor/client/LinkWidget.tsx +440 -0
- package/src/editor/client/ListingPanel.tsx +99 -0
- package/src/editor/client/Login.tsx +338 -0
- package/src/editor/client/Menu.tsx +64 -0
- package/src/editor/client/PageSettings.tsx +270 -0
- package/src/editor/client/RedirectsSettings.tsx +130 -0
- package/src/editor/client/Resize.tsx +204 -0
- package/src/editor/client/Sidebar.tsx +51 -0
- package/src/editor/client/SiteMap.tsx +568 -0
- package/src/editor/client/SiteSettings.tsx +409 -0
- package/src/editor/client/TextTools.tsx +391 -0
- package/src/editor/client/Toolbar.tsx +449 -0
- package/src/editor/client/VideoUpload.tsx +251 -0
- package/src/editor/client/api.ts +417 -0
- package/src/editor/client/brand.ts +20 -0
- package/src/editor/client/connection.ts +98 -0
- package/src/editor/client/context.ts +19 -0
- package/src/editor/client/css.d.ts +2 -0
- package/src/editor/client/editor.css +4656 -0
- package/src/editor/client/fields.tsx +812 -0
- package/src/editor/client/icons.tsx +174 -0
- package/src/editor/client/keys.ts +15 -0
- package/src/editor/client/kinds.ts +289 -0
- package/src/editor/client/languages.ts +32 -0
- package/src/editor/client/main.tsx +100 -0
- package/src/editor/client/responses.ts +26 -0
- package/src/editor/client/rich-text.ts +326 -0
- package/src/editor/client/site-tree.ts +239 -0
- package/src/editor/client/theme.ts +55 -0
- package/src/editor/client/tsconfig.json +18 -0
- package/src/editor/client/tus.ts +137 -0
- package/src/editor/client/use-rect.ts +50 -0
- package/src/editor/client/widgets.tsx +1218 -0
- package/src/forms/captcha.ts +83 -0
- package/src/forms/define.ts +166 -0
- package/src/forms/fields.ts +197 -0
- package/src/forms/file-types.ts +108 -0
- package/src/forms/files.ts +216 -0
- package/src/forms/form-page.ts +9 -0
- package/src/forms/handler.ts +622 -0
- package/src/forms/spec.ts +89 -0
- package/src/forms/store.ts +96 -0
- package/src/forms/work.ts +50 -0
- package/src/icons/library.ts +144 -0
- package/src/icons/load.ts +63 -0
- package/src/index.ts +99 -0
- package/src/init.ts +257 -0
- package/src/integration.ts +469 -0
- package/src/mail/mailer.ts +197 -0
- package/src/mail/notify.ts +272 -0
- package/src/mail/settings.ts +173 -0
- package/src/mail/templates.ts +191 -0
- package/src/mcp/page-nodes.ts +209 -0
- package/src/mcp/server.ts +111 -0
- package/src/mcp/tools.ts +637 -0
- package/src/runtime/TemplatePage.astro +39 -0
- package/src/runtime/TemplatePageStatic.astro +13 -0
- package/src/runtime/admin-route.ts +80 -0
- package/src/runtime/connect.ts +53 -0
- package/src/runtime/content.ts +188 -0
- package/src/runtime/context.ts +131 -0
- package/src/runtime/form-files.ts +18 -0
- package/src/runtime/forms-route.ts +33 -0
- package/src/runtime/forms.ts +28 -0
- package/src/runtime/icons.ts +5 -0
- package/src/runtime/media.ts +175 -0
- package/src/runtime/middleware.ts +186 -0
- package/src/runtime/nav.ts +13 -0
- package/src/runtime/query-reads.ts +49 -0
- package/src/runtime/query-store.ts +16 -0
- package/src/runtime/request-state.ts +69 -0
- package/src/runtime/robots.ts +29 -0
- package/src/runtime/rss-static.ts +16 -0
- package/src/runtime/rss.ts +29 -0
- package/src/runtime/server.ts +29 -0
- package/src/runtime/sitemap.ts +34 -0
- package/src/runtime/template-paths.ts +34 -0
- package/src/runtime/uploads-route.ts +13 -0
- package/src/seed-cli.ts +253 -0
- package/src/server/auth.ts +31 -0
- package/src/server/fetch-image.ts +219 -0
- package/src/server/handler.ts +2106 -0
- package/src/server/http.ts +162 -0
- package/src/server/locales.ts +73 -0
- package/src/server/node.ts +57 -0
- package/src/server/query-params.ts +249 -0
- package/src/server/rate-limit.ts +72 -0
- package/src/server/video-host.ts +162 -0
- package/src/starter.ts +70 -0
- package/src/version.ts +4 -0
- package/src/virtual.d.ts +65 -0
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { join, relative, sep } from "node:path";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
import type { AstroConfig, AstroIntegration } from "astro";
|
|
7
|
+
import {
|
|
8
|
+
type BrimOptions,
|
|
9
|
+
type DatabaseConfig,
|
|
10
|
+
type OutputMode,
|
|
11
|
+
resolveDatabase,
|
|
12
|
+
resolveMail,
|
|
13
|
+
resolveOutput,
|
|
14
|
+
resolveHostSignIn,
|
|
15
|
+
resolveVideoUploads,
|
|
16
|
+
checkMedia,
|
|
17
|
+
resolveBrandColors,
|
|
18
|
+
resolveMedia,
|
|
19
|
+
resolveIdentity,
|
|
20
|
+
type BrandColor,
|
|
21
|
+
type SiteIdentity,
|
|
22
|
+
} from "./config.ts";
|
|
23
|
+
import { Mailer } from "./mail/mailer.ts";
|
|
24
|
+
import type { SiteEmails } from "./mail/templates.ts";
|
|
25
|
+
import type { SiteSettings } from "./content/site-settings.ts";
|
|
26
|
+
import type { ContentType } from "./content/content-types.ts";
|
|
27
|
+
import type { PageTemplate } from "./content/page-templates.ts";
|
|
28
|
+
import type { SiteRoutes } from "./content/sitemap.ts";
|
|
29
|
+
import { captchaCheck, resolveCaptcha } from "./forms/captcha.ts";
|
|
30
|
+
import { FORMS_PATH, createFormsHandler } from "./forms/handler.ts";
|
|
31
|
+
import { formFilesDirectory, resolveFormFiles } from "./forms/files.ts";
|
|
32
|
+
import { IconLibrary } from "./icons/library.ts";
|
|
33
|
+
import { iconPackSources, iconsModule, loadIconPacks } from "./icons/load.ts";
|
|
34
|
+
import { MAX_UPLOAD_BYTES, storageFiles, uploadResponse } from "./content/media.ts";
|
|
35
|
+
import { connect } from "./runtime/connect.ts";
|
|
36
|
+
import { adoptLanguageScopes } from "./content/language-scopes.ts";
|
|
37
|
+
import { ADMIN_PATH, createAdminHandler } from "./server/handler.ts";
|
|
38
|
+
import type { LocaleConfig } from "./server/locales.ts";
|
|
39
|
+
import { toNodeMiddleware } from "./server/node.ts";
|
|
40
|
+
import { type QueryRules, parseQueryRules, undeclaredQueryReads } from "./server/query-params.ts";
|
|
41
|
+
import { VERSION } from "./version.ts";
|
|
42
|
+
|
|
43
|
+
export type { BrimOptions };
|
|
44
|
+
|
|
45
|
+
const CONFIG_MODULE = "virtual:brim/config";
|
|
46
|
+
const RESOLVED_CONFIG_MODULE = `\0${CONFIG_MODULE}`;
|
|
47
|
+
const ICONS_MODULE = "virtual:brim/icons";
|
|
48
|
+
const RESOLVED_ICONS_MODULE = `\0${ICONS_MODULE}`;
|
|
49
|
+
const ROUTES_MODULE = "virtual:brim/routes";
|
|
50
|
+
const RESOLVED_ROUTES_MODULE = `\0${ROUTES_MODULE}`;
|
|
51
|
+
/**
|
|
52
|
+
* Astro's Node adapter is brimjs's own dependency, so it is found from this file, not from the site. It is
|
|
53
|
+
* loaded by Node itself and only while the config is set up: pages import `@brimsites/brimjs` too, and a bundler that
|
|
54
|
+
* could follow an import here would carry the adapter and its build tools into the site's server.
|
|
55
|
+
*/
|
|
56
|
+
const NODE_ADAPTER = "@astrojs/node";
|
|
57
|
+
const fromBrim = createRequire(import.meta.url);
|
|
58
|
+
/** The SQLite client, also brimjs's own dependency. */
|
|
59
|
+
const DATABASE_CLIENT = "@libsql/client";
|
|
60
|
+
const EDITOR_ASSETS = new URL("../editor-dist/", import.meta.url);
|
|
61
|
+
/** Where uploaded images are served from, on the dev server and on the built one. */
|
|
62
|
+
const UPLOADS_PATH = "/uploads/";
|
|
63
|
+
const MAX_REQUEST_BYTES = MAX_UPLOAD_BYTES + 1024 * 1024;
|
|
64
|
+
/**
|
|
65
|
+
* Where a site declares its content types, relative to `src/`: a module exporting `contentTypes`.
|
|
66
|
+
* It is loaded through Vite, never imported by the Astro config, so a change shows up without a restart.
|
|
67
|
+
*/
|
|
68
|
+
const CONTENT_TYPES_MODULE = "content-types/index.ts";
|
|
69
|
+
/** Where a site declares the templates of pages the owner adds: a module exporting `pageTemplates`. */
|
|
70
|
+
const PAGE_TEMPLATES_MODULE = "page-templates/index.ts";
|
|
71
|
+
/** Where a site declares its own settings (phone, email, social profiles…): a module exporting `siteSettings`. */
|
|
72
|
+
const SITE_SETTINGS_MODULE = "site-settings.ts";
|
|
73
|
+
/** The emails the site writes itself: `export const emails = defineEmails({ form: … })`. */
|
|
74
|
+
const EMAILS_MODULE = "emails.ts";
|
|
75
|
+
|
|
76
|
+
export default function brim(options: BrimOptions = {}): AstroIntegration {
|
|
77
|
+
let database: DatabaseConfig;
|
|
78
|
+
/** How this run makes pages: live in dev, from the database per request on the server, or once in a static build. */
|
|
79
|
+
let mode: "dev" | OutputMode = "dev";
|
|
80
|
+
/** True when Brim set up the Node adapter itself because the site has none. */
|
|
81
|
+
let ownAdapter = false;
|
|
82
|
+
let locales: LocaleConfig | undefined;
|
|
83
|
+
let pages: string[] = [];
|
|
84
|
+
/** What the sitemap reads of the code; read when its module loads, so it is the resolved routes. */
|
|
85
|
+
let siteRoutes: SiteRoutes = { pages: [], patterns: [] };
|
|
86
|
+
let devServer: DevServer | undefined;
|
|
87
|
+
let mediaDirectory: URL;
|
|
88
|
+
let projectRoot = "";
|
|
89
|
+
let contentTypesFile: string | undefined;
|
|
90
|
+
let pageTemplatesFile: string | undefined;
|
|
91
|
+
let siteSettingsFile: string | undefined;
|
|
92
|
+
let emailsFile: string | undefined;
|
|
93
|
+
let icons: IconLibrary;
|
|
94
|
+
let brandColors: BrandColor[] = [];
|
|
95
|
+
let identity: SiteIdentity = {};
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
name: "brimjs",
|
|
99
|
+
hooks: {
|
|
100
|
+
"astro:config:setup": ({ config, command, updateConfig, addMiddleware, injectRoute, logger }) => {
|
|
101
|
+
database = resolveDatabase(options, fileURLToPath(config.root));
|
|
102
|
+
locales = localeConfig(config.i18n);
|
|
103
|
+
mediaDirectory = new URL("uploads/", config.publicDir);
|
|
104
|
+
projectRoot = fileURLToPath(config.root);
|
|
105
|
+
contentTypesFile = siteModule(config.srcDir, CONTENT_TYPES_MODULE);
|
|
106
|
+
pageTemplatesFile = siteModule(config.srcDir, PAGE_TEMPLATES_MODULE);
|
|
107
|
+
siteSettingsFile = siteModule(config.srcDir, SITE_SETTINGS_MODULE);
|
|
108
|
+
emailsFile = siteModule(config.srcDir, EMAILS_MODULE);
|
|
109
|
+
mode = command === "dev" ? "dev" : resolveOutput(options);
|
|
110
|
+
// The site's address from its host when the code names none (`BRIM_SITE_URL`, e.g. its domain on Brimsites):
|
|
111
|
+
// canonical links, the sitemap, feeds and shared pictures then name the address visitors use.
|
|
112
|
+
const hostAddress = config.site ? undefined : siteAddress(process.env.BRIM_SITE_URL);
|
|
113
|
+
if (hostAddress) updateConfig({ site: hostAddress });
|
|
114
|
+
const site = config.site ?? hostAddress;
|
|
115
|
+
// Read here, so a pack that is missing or malformed stops the site with the reason, not a page later.
|
|
116
|
+
const iconSources = iconPackSources(options.icons, fileURLToPath(config.root));
|
|
117
|
+
icons = new IconLibrary(options.icons, loadIconPacks(iconSources));
|
|
118
|
+
const iconsCode = iconsModule(options.icons, iconSources);
|
|
119
|
+
brandColors = resolveBrandColors(options.brandColors);
|
|
120
|
+
checkMedia(options.media);
|
|
121
|
+
identity = resolveIdentity(options.identity, fileURLToPath(config.publicDir), existsSync);
|
|
122
|
+
if (options.assistant !== undefined)
|
|
123
|
+
logger.warn("brim({ assistant }) is ignored: Brim.js no longer has an AI assistant.");
|
|
124
|
+
const query = parseQueryRules(options.query);
|
|
125
|
+
const siteCode = mode === "server" ? readSiteCode(config.root, config.srcDir) : [];
|
|
126
|
+
// What the site's own code reads of the query without saying so: pages Brim sees drawn then declare nothing,
|
|
127
|
+
// since such code could be part of any of them.
|
|
128
|
+
const undeclared = undeclaredQueryReads(siteCode, query);
|
|
129
|
+
if (undeclared.length > 0) {
|
|
130
|
+
logger.warn(
|
|
131
|
+
`Reads the query without declaring it: ${undeclared.map(({ file, line }) => `${file}:${line}`).join(", ")}. ` +
|
|
132
|
+
'Say what it reads with readsQuery() from "@brimsites/brimjs/server" or brim({ query }), so a host can cache pages ' +
|
|
133
|
+
"precisely; until then only declared pages are.",
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
// The feeds of content types with `feed` set; their links are full addresses, so a build needs `site`.
|
|
137
|
+
// A site with its own `src/pages/rss/` keeps it.
|
|
138
|
+
const feeds =
|
|
139
|
+
contentTypesFile !== undefined &&
|
|
140
|
+
(Boolean(site) || command !== "build") &&
|
|
141
|
+
!existsSync(new URL("pages/rss", config.srcDir));
|
|
142
|
+
const runtimeConfig = {
|
|
143
|
+
command,
|
|
144
|
+
mode,
|
|
145
|
+
feeds,
|
|
146
|
+
locales,
|
|
147
|
+
mediaDirectory: fileURLToPath(mediaDirectory),
|
|
148
|
+
editorAssets: fileURLToPath(EDITOR_ASSETS),
|
|
149
|
+
// As written in the config; BRIM_VIDEO_UPLOADS_URL and _TOKEN are read when the server starts.
|
|
150
|
+
videoUploads: options.videoUploads,
|
|
151
|
+
// As written in the config; BRIM_SMTP_URL, BRIM_MAIL_FROM, _URL and _TOKEN are read when the server starts.
|
|
152
|
+
mail: options.mail,
|
|
153
|
+
// As written in the config; BRIM_MEDIA_STORAGE_URL, _TOKEN, BRIM_MEDIA_PUBLIC_URL and _RESIZE are read
|
|
154
|
+
// when the server starts.
|
|
155
|
+
media: options.media,
|
|
156
|
+
brandColors,
|
|
157
|
+
identity,
|
|
158
|
+
// The public key only; BRIM_CAPTCHA_SECRET is read when the server starts.
|
|
159
|
+
captcha: resolveCaptcha(options.forms?.captcha),
|
|
160
|
+
query,
|
|
161
|
+
build: buildId(siteCode, query),
|
|
162
|
+
learnQuery: undeclared.length === 0,
|
|
163
|
+
// Kept beside the database the server runs with; BRIM_PRIVATE_STORAGE_URL and _TOKEN are read when the
|
|
164
|
+
// server starts.
|
|
165
|
+
formFiles: { storage: options.forms?.files?.storage },
|
|
166
|
+
};
|
|
167
|
+
// The built server reads where its database is when it starts, so the same build runs anywhere and a
|
|
168
|
+
// remote database's token is never written into it. A database named in the config stays as written.
|
|
169
|
+
const databaseModule = options.database
|
|
170
|
+
? `{ databaseUrl: ${JSON.stringify(database.databaseUrl)}, authToken: process.env.BRIM_DATABASE_TOKEN }` // betterleaks:allow
|
|
171
|
+
: `{ databaseUrl: process.env.BRIM_DATABASE_URL ?? ${JSON.stringify(database.databaseUrl)}, authToken: process.env.BRIM_DATABASE_TOKEN }`; // betterleaks:allow
|
|
172
|
+
if (database.authToken && database.authToken !== process.env.BRIM_DATABASE_TOKEN) {
|
|
173
|
+
// For this process only (the dev server, the pages a build writes); the build itself never holds it.
|
|
174
|
+
process.env.BRIM_DATABASE_TOKEN = database.authToken; // betterleaks:allow
|
|
175
|
+
if (command === "build" && mode === "server") {
|
|
176
|
+
logger.warn(
|
|
177
|
+
"The database token of astro.config is not written into the build: set BRIM_DATABASE_TOKEN where the server runs.",
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
// Pages read the declarations through this module, so Vite reloads them when a file changes.
|
|
182
|
+
const configModule = [
|
|
183
|
+
contentTypesFile && `import { contentTypes } from ${JSON.stringify(contentTypesFile)};`,
|
|
184
|
+
pageTemplatesFile && `import { pageTemplates } from ${JSON.stringify(pageTemplatesFile)};`,
|
|
185
|
+
siteSettingsFile && `import { siteSettings } from ${JSON.stringify(siteSettingsFile)};`,
|
|
186
|
+
emailsFile && `import { emails } from ${JSON.stringify(emailsFile)};`,
|
|
187
|
+
`export default { ...${JSON.stringify(runtimeConfig)}, ...${databaseModule},`,
|
|
188
|
+
` contentTypes: ${contentTypesFile ? "contentTypes ?? []" : "[]"},`,
|
|
189
|
+
` pageTemplates: ${pageTemplatesFile ? "pageTemplates ?? []" : "[]"},`,
|
|
190
|
+
` siteSettings: ${siteSettingsFile ? "siteSettings ?? null" : "null"},`,
|
|
191
|
+
` emails: ${emailsFile ? "emails ?? null" : "null"} };`,
|
|
192
|
+
]
|
|
193
|
+
.filter(Boolean)
|
|
194
|
+
.join("\n");
|
|
195
|
+
|
|
196
|
+
updateConfig({
|
|
197
|
+
vite: {
|
|
198
|
+
plugins: [
|
|
199
|
+
{
|
|
200
|
+
name: "brimjs:config",
|
|
201
|
+
// Before Vite's own resolver, which would find the database client and bundle it.
|
|
202
|
+
enforce: "pre",
|
|
203
|
+
resolveId: (id) =>
|
|
204
|
+
id === CONFIG_MODULE
|
|
205
|
+
? RESOLVED_CONFIG_MODULE
|
|
206
|
+
: id === ROUTES_MODULE
|
|
207
|
+
? RESOLVED_ROUTES_MODULE
|
|
208
|
+
: id === ICONS_MODULE
|
|
209
|
+
? RESOLVED_ICONS_MODULE
|
|
210
|
+
: ownAdapter && id.startsWith("@astrojs/node/")
|
|
211
|
+
? // The adapter is brimjs's dependency, not the site's: its files are found from here.
|
|
212
|
+
fromBrim.resolve(id)
|
|
213
|
+
: command === "build" && id === DATABASE_CLIENT
|
|
214
|
+
? // Left out of the bundle and named by where it is installed: it loads a native module
|
|
215
|
+
// that only its own folder can find.
|
|
216
|
+
{ id: pathToFileURL(fromBrim.resolve(id)).href, external: true }
|
|
217
|
+
: undefined,
|
|
218
|
+
load: (id) =>
|
|
219
|
+
id === RESOLVED_CONFIG_MODULE
|
|
220
|
+
? configModule
|
|
221
|
+
: id === RESOLVED_ROUTES_MODULE
|
|
222
|
+
? `export default ${JSON.stringify(siteRoutes)};`
|
|
223
|
+
: id === RESOLVED_ICONS_MODULE
|
|
224
|
+
? iconsCode
|
|
225
|
+
: undefined,
|
|
226
|
+
},
|
|
227
|
+
],
|
|
228
|
+
},
|
|
229
|
+
});
|
|
230
|
+
addMiddleware({ entrypoint: "@brimsites/brimjs/middleware", order: "pre" });
|
|
231
|
+
// Every link is fetched as the pointer reaches it (or as it is focused or touched), so the page is there by
|
|
232
|
+
// the time it is clicked. A site that sets `prefetch` itself keeps its own.
|
|
233
|
+
if (config.prefetch === undefined) {
|
|
234
|
+
updateConfig({ prefetch: { prefetchAll: true, defaultStrategy: "hover" } });
|
|
235
|
+
}
|
|
236
|
+
// The dev server draws pages on each request, like the Node server: a page then reads its address's query
|
|
237
|
+
// (a listing's facets, search and pages), which Astro hides from pages it would write once at build time.
|
|
238
|
+
if (mode === "dev" && config.output !== "server") updateConfig({ output: "server" });
|
|
239
|
+
if (mode === "server") {
|
|
240
|
+
// Pages are drawn on each request. The site keeps its own adapter when it has one.
|
|
241
|
+
// Astro runs an adapter as an integration and also asks the config whether one is set.
|
|
242
|
+
const node = config.adapter ? undefined : (fromBrim(NODE_ADAPTER) as typeof import("@astrojs/node")).default;
|
|
243
|
+
// The largest thing the server is sent is an image (10 MB); videos go from the browser straight to their
|
|
244
|
+
// host. The adapter's own limit is 1 GB, which a visitor could fill the server's memory with.
|
|
245
|
+
const adapter = node?.({ mode: "standalone", bodySizeLimit: MAX_REQUEST_BYTES });
|
|
246
|
+
ownAdapter = adapter !== undefined;
|
|
247
|
+
updateConfig({ output: "server", ...(adapter && { adapter, integrations: [adapter] }) });
|
|
248
|
+
injectRoute({ pattern: `${ADMIN_PATH}/[...path]`, entrypoint: "@brimsites/brimjs/admin-route", prerender: false });
|
|
249
|
+
injectRoute({ pattern: `${FORMS_PATH}/[...path]`, entrypoint: "@brimsites/brimjs/forms-route", prerender: false });
|
|
250
|
+
injectRoute({ pattern: `${UPLOADS_PATH}[...file]`, entrypoint: "@brimsites/brimjs/uploads-route", prerender: false });
|
|
251
|
+
}
|
|
252
|
+
// Pages added from templates and the pages of items answer any address the site's own pages leave free.
|
|
253
|
+
if (pageTemplatesFile || contentTypesFile) {
|
|
254
|
+
// A static build lists their pages (`getStaticPaths`); the server looks each one up, and has no list to ignore.
|
|
255
|
+
injectRoute({
|
|
256
|
+
pattern: "/[...page]",
|
|
257
|
+
entrypoint: mode === "static" ? "@brimsites/brimjs/template-page-static" : "@brimsites/brimjs/template-page",
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
// The sitemap lists pages by their full address, so a build needs the site's address to write one.
|
|
261
|
+
// A site that writes its own sitemap or robots.txt keeps it.
|
|
262
|
+
const own = (file: string): boolean =>
|
|
263
|
+
["ts", "js", "xml", "txt"].some((extension) => siteModule(config.srcDir, `pages/${file}.${extension}`));
|
|
264
|
+
if (feeds) {
|
|
265
|
+
// A static build lists its feeds (`getStaticPaths`); the server makes each when it is asked.
|
|
266
|
+
injectRoute({ pattern: "/rss/[...feed]", entrypoint: mode === "static" ? "@brimsites/brimjs/rss-static" : "@brimsites/brimjs/rss" });
|
|
267
|
+
}
|
|
268
|
+
// A server answers with its own address when `site` is not set; a static build has only `site` to write.
|
|
269
|
+
const sitemap = !own("sitemap.xml") && (Boolean(site) || mode !== "static" || command !== "build");
|
|
270
|
+
if (!own("sitemap.xml") && !sitemap) {
|
|
271
|
+
logger.warn('No sitemap.xml: set `site` in astro.config (e.g. "https://example.com").');
|
|
272
|
+
}
|
|
273
|
+
if (sitemap) injectRoute({ pattern: "/sitemap.xml", entrypoint: "@brimsites/brimjs/sitemap" });
|
|
274
|
+
// Without one, every crawler that asks for it gets the 404 page, drawn by the server each time.
|
|
275
|
+
if (!own("robots.txt") && !existsSync(new URL("robots.txt", config.publicDir))) {
|
|
276
|
+
injectRoute({ pattern: "/robots.txt", entrypoint: "@brimsites/brimjs/robots" });
|
|
277
|
+
}
|
|
278
|
+
},
|
|
279
|
+
// The sitemap, robots.txt and feeds are written once by a static build; the server makes them on each request.
|
|
280
|
+
"astro:route:setup": ({ route }) => {
|
|
281
|
+
if (mode === "server" && /brim(js)?[/\\]src[/\\]runtime[/\\](sitemap|robots|rss)\.ts$/.test(route.component)) {
|
|
282
|
+
route.prerender = false;
|
|
283
|
+
}
|
|
284
|
+
},
|
|
285
|
+
"astro:config:done": ({ injectTypes }) => {
|
|
286
|
+
injectTypes({
|
|
287
|
+
filename: "brim.d.ts",
|
|
288
|
+
content: `declare namespace App { interface Locals { brim: import("@brimsites/brimjs").BrimContext } }`,
|
|
289
|
+
});
|
|
290
|
+
},
|
|
291
|
+
"astro:routes:resolved": ({ routes }) => {
|
|
292
|
+
// Pages with a fixed address. The pages of items are listed with their content type, pages added from
|
|
293
|
+
// templates with their own records.
|
|
294
|
+
pages = routes.flatMap((route) =>
|
|
295
|
+
route.type === "page" && route.pathname && !route.pathname.startsWith(ADMIN_PATH) && route.pathname !== "/404"
|
|
296
|
+
? [route.pathname]
|
|
297
|
+
: [],
|
|
298
|
+
);
|
|
299
|
+
const patterns = routes.flatMap((route) => (route.type === "page" && !route.pathname ? [route.pattern] : []));
|
|
300
|
+
siteRoutes = { pages, patterns };
|
|
301
|
+
// A page added to or removed from src/pages reaches the sitemap without a restart.
|
|
302
|
+
for (const name of ["ssr", "prerender"]) {
|
|
303
|
+
const environment = devServer?.environments[name];
|
|
304
|
+
const module = environment?.moduleGraph.getModuleById(RESOLVED_ROUTES_MODULE);
|
|
305
|
+
if (environment && module) environment.moduleGraph.invalidateModule(module);
|
|
306
|
+
}
|
|
307
|
+
},
|
|
308
|
+
// Where the editor is, said where people look when the dev server starts.
|
|
309
|
+
"astro:server:start": ({ address, logger }) => {
|
|
310
|
+
const host =
|
|
311
|
+
address.family === "IPv6" || address.address === "::" || address.address === "0.0.0.0"
|
|
312
|
+
? "localhost"
|
|
313
|
+
: address.address;
|
|
314
|
+
logger.info(`Editor: http://${host}:${address.port}/admin/edit (or npx brim open, already signed in)`);
|
|
315
|
+
},
|
|
316
|
+
"astro:server:setup": async ({ server }) => {
|
|
317
|
+
devServer = server;
|
|
318
|
+
const connection = await connect(database.databaseUrl, database.authToken);
|
|
319
|
+
// A site that just turned languages on keeps what was saved before, as its default language's.
|
|
320
|
+
if (locales) await adoptLanguageScopes(connection.db, locales.defaultLocale);
|
|
321
|
+
const mailer = new Mailer(resolveMail(options.mail));
|
|
322
|
+
const formFiles = resolveFormFiles({
|
|
323
|
+
storage: options.forms?.files?.storage,
|
|
324
|
+
mediaInStorage: Boolean(resolveMedia(options.media).storage),
|
|
325
|
+
directory: formFilesDirectory(database.databaseUrl, projectRoot),
|
|
326
|
+
});
|
|
327
|
+
const admin = createAdminHandler({
|
|
328
|
+
brim: connection,
|
|
329
|
+
locales,
|
|
330
|
+
assetsDirectory: EDITOR_ASSETS,
|
|
331
|
+
contentTypes: async () => (await loadSiteModule(server, contentTypesFile)).contentTypes ?? [],
|
|
332
|
+
pageTemplates: async () => (await loadSiteModule(server, pageTemplatesFile)).pageTemplates ?? [],
|
|
333
|
+
siteSettings: async () => (await loadSiteModule(server, siteSettingsFile)).siteSettings ?? null,
|
|
334
|
+
emails: async () => (await loadSiteModule(server, emailsFile)).emails ?? null,
|
|
335
|
+
mediaDirectory,
|
|
336
|
+
mediaFiles: storageFiles(resolveMedia(options.media).storage),
|
|
337
|
+
formFiles,
|
|
338
|
+
videoUploads: resolveVideoUploads(options.videoUploads),
|
|
339
|
+
hostSignIn: resolveHostSignIn(),
|
|
340
|
+
mailer,
|
|
341
|
+
icons,
|
|
342
|
+
brandColors,
|
|
343
|
+
identity,
|
|
344
|
+
pages: () => pages,
|
|
345
|
+
patterns: () => siteRoutes.patterns,
|
|
346
|
+
// Astro keeps what getStaticPaths returned until it is told content changed: pages and items
|
|
347
|
+
// added or hidden in the editor would otherwise answer 404, or stay listed, until a restart.
|
|
348
|
+
onChange: () => {
|
|
349
|
+
for (const name of ["ssr", "prerender"]) server.environments[name]?.hot.send("astro:content-changed", {});
|
|
350
|
+
},
|
|
351
|
+
});
|
|
352
|
+
// Uploads are read from disk when asked, as on the built server: Vite would answer 404 for an image uploaded a
|
|
353
|
+
// moment ago, which is when the page drawn after the upload asks for it.
|
|
354
|
+
server.middlewares.use(
|
|
355
|
+
toNodeMiddleware(async (request) => {
|
|
356
|
+
const { pathname } = new URL(request.url);
|
|
357
|
+
if (!pathname.startsWith(UPLOADS_PATH)) return undefined;
|
|
358
|
+
// Brim names its files with letters, digits, dashes and dots only, so nothing needs decoding.
|
|
359
|
+
return uploadResponse(
|
|
360
|
+
fileURLToPath(mediaDirectory),
|
|
361
|
+
pathname.slice(UPLOADS_PATH.length),
|
|
362
|
+
resolveMedia(options.media).publicUrl,
|
|
363
|
+
);
|
|
364
|
+
}),
|
|
365
|
+
);
|
|
366
|
+
server.middlewares.use(toNodeMiddleware(admin));
|
|
367
|
+
server.middlewares.use(
|
|
368
|
+
toNodeMiddleware(
|
|
369
|
+
createFormsHandler(connection, {
|
|
370
|
+
mailer,
|
|
371
|
+
files: formFiles,
|
|
372
|
+
siteName: identity.name,
|
|
373
|
+
captcha: captchaCheck(resolveCaptcha(options.forms?.captcha)),
|
|
374
|
+
// Read at each message: a change to src/emails.ts shows in the next email, without a restart.
|
|
375
|
+
emails: async () => (await loadSiteModule(server, emailsFile)).emails ?? null,
|
|
376
|
+
}),
|
|
377
|
+
),
|
|
378
|
+
);
|
|
379
|
+
},
|
|
380
|
+
},
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const CODE_FILE = /\.(?:astro|[cm]?[jt]sx?|mdx?)$/;
|
|
385
|
+
const SKIPPED = new Set(["node_modules", ".git", ".astro", "dist"]);
|
|
386
|
+
|
|
387
|
+
/** The site's code in `src/`, by path relative to the site's folder. */
|
|
388
|
+
function readSiteCode(root: URL, srcDir: URL): { file: string; text: string }[] {
|
|
389
|
+
const rootPath = fileURLToPath(root);
|
|
390
|
+
const files: { file: string; text: string }[] = [];
|
|
391
|
+
const walk = (folder: string): void => {
|
|
392
|
+
let entries;
|
|
393
|
+
try {
|
|
394
|
+
entries = readdirSync(folder, { withFileTypes: true });
|
|
395
|
+
} catch {
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
for (const entry of entries) {
|
|
399
|
+
const path = join(folder, entry.name);
|
|
400
|
+
if (entry.isDirectory()) {
|
|
401
|
+
if (!SKIPPED.has(entry.name)) walk(path);
|
|
402
|
+
} else if (entry.isFile() && CODE_FILE.test(entry.name) && !entry.name.endsWith(".d.ts")) {
|
|
403
|
+
files.push({ file: relative(rootPath, path).split(sep).join("/"), text: readFileSync(path, "utf8") });
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
walk(fileURLToPath(srcDir));
|
|
408
|
+
return files.sort((a, b) => a.file.localeCompare(b.file));
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* The same code builds with the same name, whatever the environment it was built with: what its pages read is
|
|
413
|
+
* remembered across rebuilds and restarts, and forgotten when the code (or Brim.js) changes.
|
|
414
|
+
*/
|
|
415
|
+
function buildId(siteCode: { file: string; text: string }[], query: QueryRules): string {
|
|
416
|
+
const hash = createHash("sha256").update(VERSION).update(JSON.stringify(query));
|
|
417
|
+
for (const { file, text } of siteCode) hash.update(`\0${file}\0${text}`);
|
|
418
|
+
return hash.digest("hex").slice(0, 24);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function siteModule(srcDir: URL, name: string): string | undefined {
|
|
422
|
+
const file = fileURLToPath(new URL(name, srcDir));
|
|
423
|
+
return existsSync(file) ? file : undefined;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
interface SiteModule {
|
|
427
|
+
contentTypes?: ContentType[];
|
|
428
|
+
pageTemplates?: PageTemplate[];
|
|
429
|
+
siteSettings?: SiteSettings;
|
|
430
|
+
emails?: SiteEmails;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* One of the site's declarations, loaded through the dev server's SSR environment: the same module the pages
|
|
435
|
+
* render with, which Vite replaces when the file changes.
|
|
436
|
+
*/
|
|
437
|
+
async function loadSiteModule(server: DevServer, file: string | undefined): Promise<SiteModule> {
|
|
438
|
+
const environment: object = server.environments.ssr;
|
|
439
|
+
// Only a runnable environment has a runner; Astro's SSR environment in dev is one.
|
|
440
|
+
const runner = "runner" in environment ? (environment.runner as ModuleRunner) : undefined;
|
|
441
|
+
if (!file || !runner) return {};
|
|
442
|
+
return (await runner.import(file)) as SiteModule;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** Vite's dev server, as Astro hands it to integrations; brimjs does not depend on Vite directly. */
|
|
446
|
+
type DevServer = Parameters<NonNullable<AstroIntegration["hooks"]["astro:server:setup"]>>[0]["server"];
|
|
447
|
+
|
|
448
|
+
interface ModuleRunner {
|
|
449
|
+
import(url: string): Promise<unknown>;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function localeConfig(i18n: AstroConfig["i18n"]): LocaleConfig | undefined {
|
|
453
|
+
if (!i18n) return undefined;
|
|
454
|
+
return {
|
|
455
|
+
defaultLocale: i18n.defaultLocale,
|
|
456
|
+
locales: i18n.locales.map((locale) => (typeof locale === "string" ? locale : locale.path)),
|
|
457
|
+
prefixDefaultLocale: typeof i18n.routing === "object" && i18n.routing.prefixDefaultLocale === true,
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** `BRIM_SITE_URL` as Astro's `site`: an http(s) address, its origin only; anything else is not one. */
|
|
462
|
+
export function siteAddress(value: string | undefined): string | undefined {
|
|
463
|
+
try {
|
|
464
|
+
const url = new URL(String(value ?? "").trim());
|
|
465
|
+
return url.protocol === "https:" || url.protocol === "http:" ? url.origin : undefined;
|
|
466
|
+
} catch {
|
|
467
|
+
return undefined;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { createTransport } from "nodemailer";
|
|
2
|
+
import type { MailOptions } from "../config.ts";
|
|
3
|
+
import { HttpError, isLocalHost } from "../server/http.ts";
|
|
4
|
+
import { assertPublicHost } from "../server/fetch-image.ts";
|
|
5
|
+
import { type MailSettings, type SmtpServer, isEmail } from "./settings.ts";
|
|
6
|
+
|
|
7
|
+
export interface MailMessage {
|
|
8
|
+
to: string[];
|
|
9
|
+
subject: string;
|
|
10
|
+
text: string;
|
|
11
|
+
html: string;
|
|
12
|
+
/** Where "Reply" goes: the visitor who wrote, when the form asked for their email. */
|
|
13
|
+
replyTo?: string | undefined;
|
|
14
|
+
/** The sender's name. The address comes from whoever sends. */
|
|
15
|
+
fromName: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Who sends the site's email, as the editor may know it. The server's own setup is never described further:
|
|
20
|
+
* its addresses and passwords stay on the server.
|
|
21
|
+
* - `site`: the owner's own SMTP server, from Site Settings;
|
|
22
|
+
* - `server`: an SMTP server set where the site runs (`BRIM_SMTP_URL`);
|
|
23
|
+
* - `service`: a mail service set where the site runs (`BRIM_MAIL_URL`), e.g. the site's host;
|
|
24
|
+
* - `none`: nothing; form messages are only kept in the editor.
|
|
25
|
+
*/
|
|
26
|
+
export type MailDelivery = "site" | "server" | "service" | "none";
|
|
27
|
+
|
|
28
|
+
type Send = (message: MailMessage) => Promise<void>;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A value on its way into an email's headers (the subject, the sender's name): one line, with no control character.
|
|
32
|
+
* A line end there would start a header of the writer's choosing (`Bcc:`), so none ever gets that far.
|
|
33
|
+
*/
|
|
34
|
+
export function headerText(value: string, max = 200): string {
|
|
35
|
+
return value
|
|
36
|
+
.replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029]+/g, " ")
|
|
37
|
+
.replace(/\s+/g, " ")
|
|
38
|
+
.trim()
|
|
39
|
+
.slice(0, max);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The message as it may leave, whoever wrote it: every address is one plain address (no name, no list, no line
|
|
44
|
+
* end), and the subject and sender's name are one clean line. Every email of the site passes here, so no caller
|
|
45
|
+
* can forget.
|
|
46
|
+
*/
|
|
47
|
+
export function safeMessage(message: MailMessage): MailMessage {
|
|
48
|
+
const to = message.to.filter((address) => isEmail(address));
|
|
49
|
+
if (to.length === 0) throw new HttpError(400, "The email has no valid recipient.");
|
|
50
|
+
const replyTo = message.replyTo && isEmail(message.replyTo) ? message.replyTo : undefined;
|
|
51
|
+
// Quotes and angle brackets are what a display name could close itself with.
|
|
52
|
+
const fromName = headerText(message.fromName, 80).replace(/["<>]/g, "");
|
|
53
|
+
return { ...message, to, replyTo, subject: headerText(message.subject), fromName };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Sends one message the way the settings and the server's setup say. */
|
|
57
|
+
export class Mailer {
|
|
58
|
+
readonly #options: MailOptions;
|
|
59
|
+
readonly #fetch: typeof fetch;
|
|
60
|
+
/** Tests replace SMTP with this. */
|
|
61
|
+
readonly #smtp: (server: SmtpServer, from: string, message: MailMessage) => Promise<void>;
|
|
62
|
+
/** Refuses an owner's email server that resolves inside the host's network; tests that replace SMTP skip it. */
|
|
63
|
+
readonly #checkHost: (host: string) => Promise<void>;
|
|
64
|
+
|
|
65
|
+
constructor(
|
|
66
|
+
options: MailOptions = {},
|
|
67
|
+
deps: { fetch?: typeof fetch; smtp?: (server: SmtpServer, from: string, message: MailMessage) => Promise<void> } = {},
|
|
68
|
+
) {
|
|
69
|
+
this.#options = options;
|
|
70
|
+
this.#fetch = deps.fetch ?? fetch;
|
|
71
|
+
this.#smtp = deps.smtp ?? sendSmtp;
|
|
72
|
+
this.#checkHost = deps.smtp ? async () => {} : (host) => assertPublicHost(host);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
delivery(settings: MailSettings): MailDelivery {
|
|
76
|
+
if (settings.smtp) return "site";
|
|
77
|
+
if (this.#options.smtp && parseSmtpUrl(this.#options.smtp) && this.#options.from) return "server";
|
|
78
|
+
if (serviceUrl(this.#options.url)) return "service";
|
|
79
|
+
return "none";
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async send(settings: MailSettings, written: MailMessage): Promise<void> {
|
|
83
|
+
// Cleaned here, before any of the ways of sending sees it.
|
|
84
|
+
const message = safeMessage(written);
|
|
85
|
+
const via = this.delivery(settings);
|
|
86
|
+
const send: Send | undefined = {
|
|
87
|
+
site: async () => {
|
|
88
|
+
if (!settings.smtp) return;
|
|
89
|
+
const server = settings.smtp;
|
|
90
|
+
await this.#checkHost(server.host).catch(() => {
|
|
91
|
+
throw new HttpError(502, "The email server must be a public address, e.g. smtp.example.com.");
|
|
92
|
+
});
|
|
93
|
+
await this.#smtp(server, server.from, message);
|
|
94
|
+
},
|
|
95
|
+
// The server's own setup is not the owner's to see, so its errors are not passed on.
|
|
96
|
+
server: () =>
|
|
97
|
+
this.#smtp(parseSmtpUrl(this.#options.smtp ?? "") as SmtpServer, this.#options.from ?? "", message).catch(
|
|
98
|
+
(error: unknown) => {
|
|
99
|
+
console.error("[brim] Sending email failed:", error instanceof Error ? error.message : error);
|
|
100
|
+
throw new HttpError(502, "The site's email server did not send the email.");
|
|
101
|
+
},
|
|
102
|
+
),
|
|
103
|
+
service: () => this.#service(message),
|
|
104
|
+
none: undefined,
|
|
105
|
+
}[via] as Send | undefined;
|
|
106
|
+
if (!send) throw new HttpError(501, "Email is not set up for this site. Add your email server in Site Settings.");
|
|
107
|
+
await send(message);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async #service(message: MailMessage): Promise<void> {
|
|
111
|
+
const url = serviceUrl(this.#options.url) as string;
|
|
112
|
+
let response: Response;
|
|
113
|
+
try {
|
|
114
|
+
response = await this.#fetch(url, {
|
|
115
|
+
method: "POST",
|
|
116
|
+
headers: {
|
|
117
|
+
"content-type": "application/json",
|
|
118
|
+
accept: "application/json",
|
|
119
|
+
...(this.#options.token && { authorization: `Bearer ${this.#options.token}` }),
|
|
120
|
+
},
|
|
121
|
+
body: JSON.stringify(message),
|
|
122
|
+
signal: AbortSignal.timeout(15_000),
|
|
123
|
+
});
|
|
124
|
+
} catch {
|
|
125
|
+
throw new HttpError(502, "The mail service could not be reached.");
|
|
126
|
+
}
|
|
127
|
+
if (!response.ok) {
|
|
128
|
+
const answer = (await response.json().catch(() => ({}))) as { error?: unknown };
|
|
129
|
+
throw new HttpError(
|
|
130
|
+
502,
|
|
131
|
+
typeof answer.error === "string" ? answer.error : `The mail service refused the email (${response.status}).`,
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** HTTPS, or plain HTTP on this machine for development. */
|
|
138
|
+
function serviceUrl(value: string | undefined): string | undefined {
|
|
139
|
+
const url = value?.trim();
|
|
140
|
+
if (!url || !URL.canParse(url)) return undefined;
|
|
141
|
+
const { protocol, hostname } = new URL(url);
|
|
142
|
+
const local = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
143
|
+
return protocol === "https:" || (protocol === "http:" && local) ? url : undefined;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** `smtps://user:password@host:465` or `smtp://user:password@host:587`; user and password may be absent. */ // betterleaks:allow
|
|
147
|
+
export function parseSmtpUrl(value: string): Omit<SmtpServer, "from"> | undefined {
|
|
148
|
+
if (!URL.canParse(value)) return undefined;
|
|
149
|
+
const url = new URL(value);
|
|
150
|
+
if (url.protocol !== "smtp:" && url.protocol !== "smtps:") return undefined;
|
|
151
|
+
const secure = url.protocol === "smtps:";
|
|
152
|
+
return {
|
|
153
|
+
host: url.hostname,
|
|
154
|
+
port: Number(url.port) || (secure ? 465 : 587),
|
|
155
|
+
secure,
|
|
156
|
+
user: decodeURIComponent(url.username),
|
|
157
|
+
password: decodeURIComponent(url.password), // betterleaks:allow
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* How a mail server is reached. With a password the connection is encrypted before it is sent, from the start or with
|
|
163
|
+
* STARTTLS, or nothing is sent: a server that offers no STARTTLS, or someone on the way who hides that it does, would
|
|
164
|
+
* otherwise be given the password as it is. A server on this computer may do without.
|
|
165
|
+
*/
|
|
166
|
+
export function smtpOptions(server: Omit<SmtpServer, "from">) {
|
|
167
|
+
return {
|
|
168
|
+
host: server.host,
|
|
169
|
+
port: server.port,
|
|
170
|
+
secure: server.secure,
|
|
171
|
+
...(server.user && { auth: { user: server.user, pass: server.password } }), // betterleaks:allow
|
|
172
|
+
requireTLS: !server.secure && server.user !== "" && !isLocalHost(server.host),
|
|
173
|
+
connectionTimeout: 10_000,
|
|
174
|
+
greetingTimeout: 10_000,
|
|
175
|
+
socketTimeout: 20_000,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function sendSmtp(server: SmtpServer, from: string, message: MailMessage): Promise<void> {
|
|
180
|
+
const transport = createTransport(smtpOptions(server));
|
|
181
|
+
const address = from.match(/<([^<>]+)>\s*$/)?.[1] ?? from;
|
|
182
|
+
try {
|
|
183
|
+
await transport.sendMail({
|
|
184
|
+
from: { name: message.fromName, address: address.trim() },
|
|
185
|
+
to: message.to,
|
|
186
|
+
...(message.replyTo && { replyTo: message.replyTo }),
|
|
187
|
+
subject: message.subject,
|
|
188
|
+
text: message.text,
|
|
189
|
+
html: message.html,
|
|
190
|
+
});
|
|
191
|
+
} catch (error) {
|
|
192
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
193
|
+
throw new HttpError(502, `The email server refused the email: ${reason.slice(0, 200)}`);
|
|
194
|
+
} finally {
|
|
195
|
+
transport.close();
|
|
196
|
+
}
|
|
197
|
+
}
|