@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,162 @@
|
|
|
1
|
+
export class HttpError extends Error {
|
|
2
|
+
readonly status: number;
|
|
3
|
+
|
|
4
|
+
constructor(status: number, message: string) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.status = status;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const MAX_BODY_BYTES = 64 * 1024;
|
|
11
|
+
|
|
12
|
+
export function json(body: unknown, init: ResponseInit = {}): Response {
|
|
13
|
+
const headers = new Headers(init.headers);
|
|
14
|
+
headers.set("content-type", "application/json; charset=utf-8");
|
|
15
|
+
headers.set("cache-control", "no-store");
|
|
16
|
+
return new Response(JSON.stringify(body), { ...init, headers });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The request's body, up to `max` bytes. A larger one is refused as soon as it is known to be larger: by its
|
|
21
|
+
* declared length before anything is read, else while reading, so no more than `max` is ever held in memory.
|
|
22
|
+
*/
|
|
23
|
+
export async function readBytes(
|
|
24
|
+
request: Request,
|
|
25
|
+
max: number,
|
|
26
|
+
tooLarge = "The request is too large.",
|
|
27
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
28
|
+
if (Number(request.headers.get("content-length") ?? 0) > max) throw new HttpError(413, tooLarge);
|
|
29
|
+
if (!request.body) return new Uint8Array(0);
|
|
30
|
+
const reader = request.body.getReader();
|
|
31
|
+
const chunks: Uint8Array[] = [];
|
|
32
|
+
let size = 0;
|
|
33
|
+
for (;;) {
|
|
34
|
+
const { done, value } = await reader.read();
|
|
35
|
+
if (done) break;
|
|
36
|
+
size += value.byteLength;
|
|
37
|
+
if (size > max) {
|
|
38
|
+
await reader.cancel().catch(() => undefined);
|
|
39
|
+
throw new HttpError(413, tooLarge);
|
|
40
|
+
}
|
|
41
|
+
chunks.push(value);
|
|
42
|
+
}
|
|
43
|
+
const bytes = new Uint8Array(size);
|
|
44
|
+
let offset = 0;
|
|
45
|
+
for (const chunk of chunks) {
|
|
46
|
+
bytes.set(chunk, offset);
|
|
47
|
+
offset += chunk.byteLength;
|
|
48
|
+
}
|
|
49
|
+
return bytes;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** `maxBytes` raises the limit for the few requests that carry a lot at once, such as a site's seed. */
|
|
53
|
+
export async function readJson(request: Request, maxBytes = MAX_BODY_BYTES): Promise<Record<string, unknown>> {
|
|
54
|
+
if (!request.headers.get("content-type")?.startsWith("application/json")) {
|
|
55
|
+
throw new HttpError(415, "Send the request as JSON.");
|
|
56
|
+
}
|
|
57
|
+
const text = new TextDecoder().decode(await readBytes(request, maxBytes));
|
|
58
|
+
let body: unknown;
|
|
59
|
+
try {
|
|
60
|
+
body = JSON.parse(text);
|
|
61
|
+
} catch {
|
|
62
|
+
throw new HttpError(400, "The request is not valid JSON.");
|
|
63
|
+
}
|
|
64
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
65
|
+
throw new HttpError(400, "The request must be a JSON object.");
|
|
66
|
+
}
|
|
67
|
+
return body as Record<string, unknown>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function readCookie(request: Request, name: string): string | undefined {
|
|
71
|
+
return readCookies(request, name)[0];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Every value the browser sent under `name`, in its order. A browser can hold several cookies of one name, for
|
|
76
|
+
* different paths or set by another app on the same host (every port of localhost shares cookies), and sends the
|
|
77
|
+
* most specific path first.
|
|
78
|
+
*/
|
|
79
|
+
export function readCookies(request: Request, name: string): string[] {
|
|
80
|
+
const values: string[] = [];
|
|
81
|
+
for (const part of request.headers.get("cookie")?.split(";") ?? []) {
|
|
82
|
+
const [key, ...value] = part.trim().split("=");
|
|
83
|
+
if (key === name) values.push(value.join("="));
|
|
84
|
+
}
|
|
85
|
+
return values;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The site's public address as it was set: by its host (`BRIM_SITE_URL`, its own domain on Brimsites), else by its
|
|
90
|
+
* code (`site` in the Astro config).
|
|
91
|
+
*/
|
|
92
|
+
export function givenOrigin(siteUrl?: string | URL): string | undefined {
|
|
93
|
+
for (const value of [process.env.BRIM_SITE_URL, siteUrl]) {
|
|
94
|
+
try {
|
|
95
|
+
const url = new URL(String(value ?? "").trim());
|
|
96
|
+
if (url.protocol === "https:" || url.protocol === "http:") return url.origin;
|
|
97
|
+
} catch {
|
|
98
|
+
// Not set, or not an address: the next one says it.
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The site's public address, as it was set or else as the request names it. Never the server's own address behind a
|
|
106
|
+
* proxy (`localhost:43967`), which `request.url` holds there. Only for an answer to whoever asked: what is sent to
|
|
107
|
+
* someone else takes `trustedOrigin`.
|
|
108
|
+
*/
|
|
109
|
+
export function publicOrigin(request: Request, siteUrl?: string | URL): string {
|
|
110
|
+
return givenOrigin(siteUrl) ?? requestOrigin(request);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The site's public address for what reaches someone other than the sender of the request (emails): the one that was
|
|
115
|
+
* set. The request's own `Host` is its sender's to write, so it is believed only on this computer, and otherwise
|
|
116
|
+
* there is none.
|
|
117
|
+
*/
|
|
118
|
+
export function trustedOrigin(request: Request, siteUrl?: string | URL): string | undefined {
|
|
119
|
+
const given = givenOrigin(siteUrl);
|
|
120
|
+
if (given) return given;
|
|
121
|
+
const origin = requestOrigin(request);
|
|
122
|
+
return URL.canParse(origin) && isLocalHost(new URL(origin).hostname) ? origin : undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function isLocalHost(hostname: string): boolean {
|
|
126
|
+
return ["localhost", "127.0.0.1", "[::1]", "::1"].includes(hostname) || hostname.endsWith(".localhost");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The address the visitor used. A server behind a reverse proxy, or one that does not trust the `Host` header
|
|
131
|
+
* for building URLs, sees an internal address in `request.url`; the visitor's browser names the real one in
|
|
132
|
+
* `Host`, and a proxy in `X-Forwarded-Host` / `X-Forwarded-Proto`. A page of another site cannot change these
|
|
133
|
+
* headers on a request its visitor's browser sends, so they are safe to compare `Origin` with.
|
|
134
|
+
*/
|
|
135
|
+
export function requestOrigin(request: Request): string {
|
|
136
|
+
const url = new URL(request.url);
|
|
137
|
+
const first = (name: string) => request.headers.get(name)?.split(",")[0]?.trim() || undefined;
|
|
138
|
+
const protocol = first("x-forwarded-proto");
|
|
139
|
+
const scheme = protocol === "https" || protocol === "http" ? protocol : url.protocol.slice(0, -1);
|
|
140
|
+
return `${scheme}://${first("x-forwarded-host") ?? first("host") ?? url.host}`;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The visitor's address, which the limits on wrong passwords and form messages count by. Behind a reverse proxy the
|
|
145
|
+
* connection comes from the proxy, so every visitor would share one address: `BRIM_CLIENT_IP_HEADER` names the
|
|
146
|
+
* header in which the proxy gives the visitor's own (e.g. `x-real-ip`). Set it only when the proxy always writes
|
|
147
|
+
* that header itself, or a visitor could write any address there.
|
|
148
|
+
*/
|
|
149
|
+
export function clientAddress(request: Request, connection: string): string {
|
|
150
|
+
const header = process.env.BRIM_CLIENT_IP_HEADER?.trim();
|
|
151
|
+
const given = header ? request.headers.get(header)?.split(",")[0]?.trim() : undefined;
|
|
152
|
+
return given && given.length <= 64 ? given : connection;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** A browser sends `Origin` on every state-changing request; another site's page cannot fake ours. */
|
|
156
|
+
export function assertSameOrigin(request: Request): void {
|
|
157
|
+
const origin = request.headers.get("origin");
|
|
158
|
+
// Hosts are compared, not schemes: a proxy that ends TLS may not say so, and the browser's `Origin` does.
|
|
159
|
+
if (!origin || !URL.canParse(origin) || new URL(origin).host !== new URL(requestOrigin(request)).host) {
|
|
160
|
+
throw new HttpError(403, "This request did not come from the site itself.");
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { normalizePagePath } from "../content/ids.ts";
|
|
2
|
+
import { type ItemPathType, fillItemPath, matchItemPath } from "../content/item-path.ts";
|
|
3
|
+
|
|
4
|
+
/** The part of Astro's `i18n` config Brim needs to tell which language a page is in. */
|
|
5
|
+
export interface LocaleConfig {
|
|
6
|
+
defaultLocale: string;
|
|
7
|
+
/** URL path segment of every language, e.g. `["en", "ro"]`. */
|
|
8
|
+
locales: string[];
|
|
9
|
+
/** Astro's `routing.prefixDefaultLocale`: the default language's pages are under `/en/` too. */
|
|
10
|
+
prefixDefaultLocale?: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Mirrors Astro's routing: `/ro/despre` is Romanian, anything without a language prefix is the default. */
|
|
14
|
+
export function localeOfPath(pathname: string, config: LocaleConfig | undefined): string | undefined {
|
|
15
|
+
if (!config) return undefined;
|
|
16
|
+
const firstSegment = normalizePagePath(pathname).split("/")[1] ?? "";
|
|
17
|
+
return config.locales.includes(firstSegment) ? firstSegment : config.defaultLocale;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The same page in another language: `/about` → `/ro/about`, `/ro/about` → `/about` (or `/en/about`). */
|
|
21
|
+
export function pathInLocale(pathname: string, locale: string, config: LocaleConfig): string {
|
|
22
|
+
const path = normalizePagePath(pathname);
|
|
23
|
+
const segments = path.split("/").slice(1).filter(Boolean);
|
|
24
|
+
if (config.locales.includes(segments[0] ?? "")) segments.shift();
|
|
25
|
+
const prefixed = locale !== config.defaultLocale || config.prefixDefaultLocale === true;
|
|
26
|
+
return normalizePagePath(`/${[...(prefixed ? [locale] : []), ...segments].join("/")}`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* How an item's language is stored: "" for the default language, the language's code for the others.
|
|
31
|
+
* `undefined` for a code the site does not have.
|
|
32
|
+
*/
|
|
33
|
+
export function storedLocale(locale: string | undefined, config: LocaleConfig | undefined): string | undefined {
|
|
34
|
+
if (!locale || !config || locale === config.defaultLocale) return "";
|
|
35
|
+
return config.locales.includes(locale) ? locale : undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The address of an item's page: `/projects/lake-house` (or its type's `path`), under its language unless that is the default one. */
|
|
39
|
+
export function itemPagePath(
|
|
40
|
+
type: Pick<ItemPathType, "slug" | "path">,
|
|
41
|
+
item: { slug: string; locale?: string; data?: Record<string, unknown> },
|
|
42
|
+
config: LocaleConfig | undefined,
|
|
43
|
+
): string {
|
|
44
|
+
const locale = item.locale ?? "";
|
|
45
|
+
const code = locale || config?.defaultLocale;
|
|
46
|
+
const prefixed = config && code && (locale !== "" || config.prefixDefaultLocale === true);
|
|
47
|
+
return `${prefixed ? `/${code}` : ""}${fillItemPath(type, item)}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Which of `types` an address is an item's page of, the item's slug and its language as stored ("" for the default
|
|
52
|
+
* one). The address must have the shape `itemPagePath` gives: `/en/projects/lake` is not an item's when the default
|
|
53
|
+
* language has no prefix, nor `/projects/lake` when it has one. Whether the item's own values (its category in
|
|
54
|
+
* `/produse/[category]/[slug]`) agree is for the caller to check, with `itemPagePath`, once it has the item.
|
|
55
|
+
*/
|
|
56
|
+
export function readItemPath<T extends Pick<ItemPathType, "slug" | "path">>(
|
|
57
|
+
types: T[],
|
|
58
|
+
pathname: string,
|
|
59
|
+
config: LocaleConfig | undefined,
|
|
60
|
+
): { type: T; slug: string; locale: string } | undefined {
|
|
61
|
+
const path = normalizePagePath(pathname);
|
|
62
|
+
const segments = path.split("/").slice(1);
|
|
63
|
+
const code = config?.locales.includes(segments[0] ?? "") ? segments.shift() : undefined;
|
|
64
|
+
const locale = storedLocale(code, config);
|
|
65
|
+
if (locale === undefined) return undefined;
|
|
66
|
+
const prefixed = config && (locale !== "" || config.prefixDefaultLocale === true);
|
|
67
|
+
if (Boolean(code) !== Boolean(prefixed)) return undefined;
|
|
68
|
+
for (const type of types) {
|
|
69
|
+
const slug = matchItemPath(type, segments);
|
|
70
|
+
if (slug !== undefined) return { type, slug, locale };
|
|
71
|
+
}
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { Readable } from "node:stream";
|
|
3
|
+
import type { AdminHandler } from "./handler.ts";
|
|
4
|
+
import { clientAddress } from "./http.ts";
|
|
5
|
+
|
|
6
|
+
type Next = (error?: unknown) => void;
|
|
7
|
+
/** Connect-style servers set `originalUrl` when a middleware is mounted on a sub-path. */
|
|
8
|
+
type NodeRequest = IncomingMessage & { originalUrl?: string | undefined };
|
|
9
|
+
|
|
10
|
+
/** Adapts the admin handler to Node's `(req, res, next)` middleware shape used by Vite and Express. */
|
|
11
|
+
export function toNodeMiddleware(handler: AdminHandler) {
|
|
12
|
+
async function respond(req: NodeRequest, res: ServerResponse, next: Next): Promise<void> {
|
|
13
|
+
const request = toRequest(req);
|
|
14
|
+
const response = await handler(request, {
|
|
15
|
+
clientAddress: clientAddress(request, req.socket.remoteAddress ?? "unknown"),
|
|
16
|
+
serverOrigin: serverOrigin(req),
|
|
17
|
+
});
|
|
18
|
+
if (!response) return next();
|
|
19
|
+
|
|
20
|
+
res.statusCode = response.status;
|
|
21
|
+
// Each Set-Cookie is its own header: set one by one, the last would replace the others (signing in sets the
|
|
22
|
+
// session and removes the old /admin cookie).
|
|
23
|
+
response.headers.forEach((value, name) => {
|
|
24
|
+
if (name !== "set-cookie") res.setHeader(name, value);
|
|
25
|
+
});
|
|
26
|
+
const cookies = response.headers.getSetCookie();
|
|
27
|
+
if (cookies.length > 0) res.setHeader("set-cookie", cookies);
|
|
28
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return (req: NodeRequest, res: ServerResponse, next: Next): void => {
|
|
32
|
+
respond(req, res, next).catch(next);
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The address the connection reached this server on, read from the socket rather than from any header. */
|
|
37
|
+
function serverOrigin(req: NodeRequest): string | undefined {
|
|
38
|
+
const { localAddress, localPort } = req.socket;
|
|
39
|
+
if (!localAddress || !localPort) return undefined;
|
|
40
|
+
const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
|
|
41
|
+
return `${protocol}://${localAddress.includes(":") ? `[${localAddress}]` : localAddress}:${localPort}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function toRequest(req: NodeRequest): Request {
|
|
45
|
+
const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
|
|
46
|
+
const url = new URL(req.originalUrl ?? req.url ?? "/", `${protocol}://${req.headers.host ?? "localhost"}`);
|
|
47
|
+
const headers = new Headers();
|
|
48
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
49
|
+
if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
50
|
+
}
|
|
51
|
+
const hasBody = req.method !== "GET" && req.method !== "HEAD";
|
|
52
|
+
return new Request(url, {
|
|
53
|
+
method: req.method ?? "GET",
|
|
54
|
+
headers,
|
|
55
|
+
...(hasBody && { body: Readable.toWeb(req) as ReadableStream, duplex: "half" }),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import type { Database } from "../db/database.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The query parameters each page or route reads, for a host that keeps pages in a CDN (`query` in
|
|
5
|
+
* /admin/api/info, capability `query-params`): a path, or a pattern where `*` stands for any run of characters,
|
|
6
|
+
* → the names it reads, or "all". The host keeps exactly those parameters in its cache key (and drops the others
|
|
7
|
+
* from the request), so `?utm_source=…` or `?ref=…` on a page that reads none is the same cached copy. A path that
|
|
8
|
+
* is not declared keeps every parameter, as before. The most specific pattern that matches wins: the longest.
|
|
9
|
+
*/
|
|
10
|
+
export type QueryRules = Record<string, readonly string[] | "all">;
|
|
11
|
+
|
|
12
|
+
/** What a host takes of a path and a name (the platform drops the rest, so Brim never sends one it would drop). */
|
|
13
|
+
export const QUERY_PATH = /^\/[\w\-./~%*[\]@+,:]{0,300}$/;
|
|
14
|
+
export const QUERY_NAME = /^[\w.\-[\]]{1,64}$/;
|
|
15
|
+
/** A host takes at most this many names per path; a path that reads more keeps all of them. */
|
|
16
|
+
const MAX_NAMES = 100;
|
|
17
|
+
/** At most this many paths are declared, within this size: what is left out keeps every parameter. */
|
|
18
|
+
const MAX_RULES = 450;
|
|
19
|
+
const MAX_JSON = 90_000;
|
|
20
|
+
/** At most this many pages are remembered per build (the pages of items each count as one). */
|
|
21
|
+
const MAX_LEARNED = 1000;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Every page of a Brim.js site reads `?edit` (it opens the page in the editor), so every declared path keeps it.
|
|
25
|
+
*/
|
|
26
|
+
export const ALWAYS_READ = ["edit"] as const;
|
|
27
|
+
|
|
28
|
+
/** `brim({ query })` as written in the config: checked when the config loads, so a mistake stops the build. */
|
|
29
|
+
export function parseQueryRules(input: unknown): QueryRules {
|
|
30
|
+
if (input === undefined || input === null) return {};
|
|
31
|
+
if (typeof input !== "object" || Array.isArray(input)) {
|
|
32
|
+
throw new Error('brim({ query }) must be an object: { "/api/products": ["sort", "id"], "/shop/*": "all" }.');
|
|
33
|
+
}
|
|
34
|
+
const rules: QueryRules = {};
|
|
35
|
+
for (const [path, names] of Object.entries(input as Record<string, unknown>)) {
|
|
36
|
+
if (!QUERY_PATH.test(path)) {
|
|
37
|
+
throw new Error(`brim({ query }): "${path}" is not a path (it starts with "/"; "*" stands for any characters).`);
|
|
38
|
+
}
|
|
39
|
+
if (names === "all") {
|
|
40
|
+
rules[path] = "all";
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (!Array.isArray(names) || names.some((name) => typeof name !== "string" || !QUERY_NAME.test(name))) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
`brim({ query }): "${path}" must list parameter names (letters, digits, "_", "-", ".", "[]"), or be "all".`,
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
rules[path] = [...new Set(names as string[])];
|
|
49
|
+
}
|
|
50
|
+
return rules;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Whether a rule's path (or pattern) covers a path, as the host matches it. */
|
|
54
|
+
export function ruleMatches(pattern: string, pathname: string): boolean {
|
|
55
|
+
if (pattern.includes("*")) {
|
|
56
|
+
const source = pattern
|
|
57
|
+
.split("*")
|
|
58
|
+
.map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
|
|
59
|
+
.join(".*");
|
|
60
|
+
return new RegExp(`^${source}$`).test(pathname);
|
|
61
|
+
}
|
|
62
|
+
return pattern === pathname || (pattern !== "/" && pattern === pathname.replace(/\/+$/, ""));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The rule that applies to a path: the longest pattern that matches, as the host decides. */
|
|
66
|
+
export function ruleFor(rules: QueryRules, pathname: string): readonly string[] | "all" | undefined {
|
|
67
|
+
let best: string | undefined;
|
|
68
|
+
for (const pattern of Object.keys(rules)) {
|
|
69
|
+
if (best !== undefined && pattern.length <= best.length) continue;
|
|
70
|
+
if (ruleMatches(pattern, pathname)) best = pattern;
|
|
71
|
+
}
|
|
72
|
+
return best === undefined ? undefined : rules[best];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A page's address as it is remembered and declared: without a trailing slash, except the home page. */
|
|
76
|
+
export function queryPath(pathname: string): string {
|
|
77
|
+
return pathname.replace(/\/+$/, "") || "/";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function union(...lists: (readonly string[] | "all" | undefined)[]): string[] | "all" {
|
|
81
|
+
const names = new Set<string>();
|
|
82
|
+
for (const list of lists) {
|
|
83
|
+
if (list === "all") return "all";
|
|
84
|
+
for (const name of list ?? []) names.add(name);
|
|
85
|
+
}
|
|
86
|
+
return [...names].sort();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A rule as a host takes it: a name it would drop, or too many names, and the path keeps every parameter. */
|
|
90
|
+
function sendable(names: string[] | "all"): string[] | "all" {
|
|
91
|
+
if (names === "all") return "all";
|
|
92
|
+
return names.length > MAX_NAMES || names.some((name) => !QUERY_NAME.test(name)) ? "all" : names;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* What /admin/api/info answers as `query`: the site's own declarations (`brim({ query })`) and the pages Brim saw
|
|
97
|
+
* drawn and what they read. A page also keeps what every declaration covering it says, since its exact path is the
|
|
98
|
+
* longest pattern and wins over them at the host. Every path keeps `edit`. Kept within what a host accepts; a path
|
|
99
|
+
* left out keeps every parameter, so nothing is ever cut that a page reads.
|
|
100
|
+
*/
|
|
101
|
+
export function composeQueryRules(declared: QueryRules, learned: QueryRules): QueryRules {
|
|
102
|
+
const rules: QueryRules = {};
|
|
103
|
+
let size = 2;
|
|
104
|
+
const add = (path: string, names: string[] | "all"): void => {
|
|
105
|
+
if (!QUERY_PATH.test(path) || Object.keys(rules).length >= MAX_RULES) return;
|
|
106
|
+
const entry = JSON.stringify(path).length + JSON.stringify(names).length + 2;
|
|
107
|
+
if (size + entry > MAX_JSON) return;
|
|
108
|
+
size += entry;
|
|
109
|
+
rules[path] = names;
|
|
110
|
+
};
|
|
111
|
+
for (const [path, names] of Object.entries(declared)) add(path, sendable(union(names, ALWAYS_READ)));
|
|
112
|
+
for (const [path, names] of Object.entries(learned)) {
|
|
113
|
+
if (Object.hasOwn(rules, path)) continue;
|
|
114
|
+
const covering = Object.entries(declared)
|
|
115
|
+
.filter(([pattern]) => ruleMatches(pattern, path))
|
|
116
|
+
.map(([, list]) => list);
|
|
117
|
+
add(path, sendable(union(names, ALWAYS_READ, ...covering)));
|
|
118
|
+
}
|
|
119
|
+
return rules;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The parameters each page read when it was drawn, remembered in the site's database for the build that drew them
|
|
124
|
+
* (`brim_query_reads`), so a restarted server declares them at once. Another build may read others, so what an
|
|
125
|
+
* earlier build learned is dropped. What a page reads only grows: a page that read `color` once keeps it.
|
|
126
|
+
*/
|
|
127
|
+
export class QueryReads {
|
|
128
|
+
readonly #db: Database;
|
|
129
|
+
readonly #build: string;
|
|
130
|
+
#loaded: Promise<Map<string, string[] | "all">> | undefined;
|
|
131
|
+
|
|
132
|
+
constructor(db: Database, build: string) {
|
|
133
|
+
this.#db = db;
|
|
134
|
+
this.#build = build;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
#load(): Promise<Map<string, string[] | "all">> {
|
|
138
|
+
this.#loaded ??= (async () => {
|
|
139
|
+
await this.#db.query(
|
|
140
|
+
"CREATE TABLE IF NOT EXISTS brim_query_reads (path TEXT PRIMARY KEY, build TEXT NOT NULL, names TEXT NOT NULL) WITHOUT ROWID",
|
|
141
|
+
);
|
|
142
|
+
await this.#db.query("DELETE FROM brim_query_reads WHERE build <> ?", [this.#build]);
|
|
143
|
+
const rows = await this.#db.query("SELECT path, names FROM brim_query_reads WHERE build = ?", [this.#build]);
|
|
144
|
+
const reads = new Map<string, string[] | "all">();
|
|
145
|
+
for (const row of rows) {
|
|
146
|
+
try {
|
|
147
|
+
const names = JSON.parse(String(row.names)) as unknown;
|
|
148
|
+
if (names === "all" || (Array.isArray(names) && names.every((name) => typeof name === "string"))) {
|
|
149
|
+
reads.set(String(row.path), names as string[] | "all");
|
|
150
|
+
}
|
|
151
|
+
} catch {
|
|
152
|
+
// A row that cannot be read is learned again.
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return reads;
|
|
156
|
+
})();
|
|
157
|
+
// A failure (the database not reachable a moment) is tried again on the next page.
|
|
158
|
+
this.#loaded.catch(() => (this.#loaded = undefined));
|
|
159
|
+
return this.#loaded;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Remembers what a page read; written only when it adds something. */
|
|
163
|
+
async record(pathname: string, read: readonly string[] | "all"): Promise<void> {
|
|
164
|
+
const path = queryPath(pathname);
|
|
165
|
+
if (!QUERY_PATH.test(path)) return;
|
|
166
|
+
const reads = await this.#load();
|
|
167
|
+
const known = reads.get(path);
|
|
168
|
+
if (!known && reads.size >= MAX_LEARNED) return;
|
|
169
|
+
const next = union(known, read);
|
|
170
|
+
if (known && (known === "all" || (next !== "all" && next.length === known.length))) return;
|
|
171
|
+
reads.set(path, next);
|
|
172
|
+
await this.#db.query(
|
|
173
|
+
"INSERT INTO brim_query_reads (path, build, names) VALUES (?, ?, ?) ON CONFLICT (path) DO UPDATE SET build = excluded.build, names = excluded.names",
|
|
174
|
+
[path, this.#build, JSON.stringify(next)],
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async learned(): Promise<QueryRules> {
|
|
179
|
+
return Object.fromEntries(await this.#load());
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
184
|
+
// Reading the site's code: where it reads the query itself, and whether it said what it reads.
|
|
185
|
+
|
|
186
|
+
/** Code that reads a request's query: `Astro.url.searchParams`, `new URL(request.url).searchParams`, `url.search`. */
|
|
187
|
+
const READS_QUERY = /\bsearchParams\b|\bURLSearchParams\b|\burl\.search\b/;
|
|
188
|
+
/** The browser's own address (`location.search`) is not the request's: the host leaves it as it was. */
|
|
189
|
+
const BROWSER_ADDRESS = /\blocation\b/;
|
|
190
|
+
/** The site's code saying what it reads. */
|
|
191
|
+
const DECLARES = /\breadsQuery\s*\(/;
|
|
192
|
+
|
|
193
|
+
/** The lines of a file of the site's code that read the request's query (1-based). */
|
|
194
|
+
export function queryReadLines(text: string): number[] {
|
|
195
|
+
const lines: number[] = [];
|
|
196
|
+
text.split("\n").forEach((line, index) => {
|
|
197
|
+
const code = line.trimStart();
|
|
198
|
+
if (code.startsWith("//") || code.startsWith("*") || code.startsWith("/*")) return;
|
|
199
|
+
if (READS_QUERY.test(line) && !BROWSER_ADDRESS.test(line)) lines.push(index + 1);
|
|
200
|
+
});
|
|
201
|
+
return lines;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* The address a file of `src/pages` answers at, with each `[param]` as a stand-in value, to see whether a declaration
|
|
206
|
+
* covers it: `src/pages/shop/[slug].astro` → `/shop/_`. `undefined` for a file outside `src/pages`.
|
|
207
|
+
*/
|
|
208
|
+
export function pageRouteOf(file: string): string | undefined {
|
|
209
|
+
const match = /(?:^|\/)src\/pages\/(.+)\.[a-z]+$/.exec(file.replaceAll("\\", "/"));
|
|
210
|
+
if (!match?.[1]) return undefined;
|
|
211
|
+
const segments = match[1].split("/").map((segment) => segment.replace(/\[[^\]]*\]/g, "_"));
|
|
212
|
+
if (segments.at(-1) === "index") segments.pop();
|
|
213
|
+
return `/${segments.join("/")}`;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export interface UndeclaredRead {
|
|
217
|
+
/** As given. */
|
|
218
|
+
file: string;
|
|
219
|
+
line: number;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Files of the site's code that read the request's query without saying what they read: neither calling
|
|
224
|
+
* `readsQuery()` nor being a page of `src/pages` that a declaration in `brim({ query })` covers. While any is left,
|
|
225
|
+
* Brim declares nothing for pages it saw drawn (it cannot know which page such code is part of): only the pages
|
|
226
|
+
* that called `readsQuery()` and the config's own declarations.
|
|
227
|
+
*/
|
|
228
|
+
export function undeclaredQueryReads(files: { file: string; text: string }[], declared: QueryRules): UndeclaredRead[] {
|
|
229
|
+
const found: UndeclaredRead[] = [];
|
|
230
|
+
for (const { file, text } of files) {
|
|
231
|
+
const lines = queryReadLines(text);
|
|
232
|
+
if (lines.length === 0 || DECLARES.test(text)) continue;
|
|
233
|
+
const route = pageRouteOf(file);
|
|
234
|
+
if (route !== undefined && ruleFor(declared, route) !== undefined) continue;
|
|
235
|
+
found.push({ file, line: lines[0] ?? 1 });
|
|
236
|
+
}
|
|
237
|
+
return found;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** The paths an astro.config names in a `query` map, read from its text (for `brim check`, which does not run it). */
|
|
241
|
+
export function queryPathsInConfig(text: string): QueryRules {
|
|
242
|
+
const start = text.search(/\bquery\s*:\s*\{/);
|
|
243
|
+
if (start < 0) return {};
|
|
244
|
+
const rules: QueryRules = {};
|
|
245
|
+
for (const match of text.slice(start).matchAll(/["'`](\/[^"'`]*)["'`]\s*:/g)) {
|
|
246
|
+
if (match[1]) rules[match[1]] = "all";
|
|
247
|
+
}
|
|
248
|
+
return rules;
|
|
249
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { Database } from "../db/database.ts";
|
|
2
|
+
|
|
3
|
+
/** The longest window a limit may count in. Rows older than twice this are spent, whatever their key. */
|
|
4
|
+
export const MAX_WINDOW_SECONDS = 24 * 60 * 60;
|
|
5
|
+
/** How often one limiter clears spent rows away. */
|
|
6
|
+
const PRUNE_EVERY_MS = 60 * 60 * 1000;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Fixed-window counter in SQLite, for sign-ins and forms. Every key leaves a row (a form's token
|
|
10
|
+
* leaves one per message), so rows whose window ended long ago are deleted now and then: without that, anyone
|
|
11
|
+
* sending forms all day would make the table, and the database, grow without end.
|
|
12
|
+
*/
|
|
13
|
+
export class RateLimiter {
|
|
14
|
+
readonly #db: Database;
|
|
15
|
+
#prunedAt = 0;
|
|
16
|
+
|
|
17
|
+
constructor(db: Database) {
|
|
18
|
+
this.#db = db;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Deletes the rows of windows that ended long ago, at most once an hour, never failing the caller. */
|
|
22
|
+
async #prune(now: number): Promise<void> {
|
|
23
|
+
if (Date.now() - this.#prunedAt < PRUNE_EVERY_MS) return;
|
|
24
|
+
this.#prunedAt = Date.now();
|
|
25
|
+
try {
|
|
26
|
+
await this.#db.query("DELETE FROM brim_rate_limits WHERE window_start < ?", [now - 2 * MAX_WINDOW_SECONDS]);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
console.error("[brim] Old rate limit rows were not cleared:", error instanceof Error ? error.message : error);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Gives back an attempt counted with `allow` in this window (one that turned out fine). Counting first and giving
|
|
34
|
+
* back after is what keeps concurrent attempts within the limit: a check that counts only afterwards lets any
|
|
35
|
+
* number of requests sent at once through before the first one is counted.
|
|
36
|
+
*/
|
|
37
|
+
async release(key: string, windowSeconds: number): Promise<void> {
|
|
38
|
+
const now = Math.floor(Date.now() / 1000);
|
|
39
|
+
await this.#db.query(
|
|
40
|
+
"UPDATE brim_rate_limits SET count = count - 1 WHERE key = ? AND window_start = ? AND count > 0",
|
|
41
|
+
[key, now - (now % windowSeconds)],
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** How many attempts the key counted in its latest window (0 when none). For keys that name their window. */
|
|
46
|
+
async count(key: string): Promise<number> {
|
|
47
|
+
const rows = await this.#db.query("SELECT count FROM brim_rate_limits WHERE key = ?", [key]);
|
|
48
|
+
return Number(rows[0]?.count ?? 0);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Counts one attempt and says whether it is still within `limit` per `windowSeconds`. */
|
|
52
|
+
allow(key: string, limit: number, windowSeconds: number): Promise<boolean> {
|
|
53
|
+
return this.add(key, 1, limit, windowSeconds);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Counts `amount` at once (the bytes of a message's files) and says whether the total is still within `limit`. */
|
|
57
|
+
async add(key: string, amount: number, limit: number, windowSeconds: number): Promise<boolean> {
|
|
58
|
+
if (windowSeconds > MAX_WINDOW_SECONDS) throw new Error(`A rate limit window is at most ${MAX_WINDOW_SECONDS}s.`);
|
|
59
|
+
const now = Math.floor(Date.now() / 1000);
|
|
60
|
+
await this.#prune(now);
|
|
61
|
+
const windowStart = now - (now % windowSeconds);
|
|
62
|
+
const rows = await this.#db.query(
|
|
63
|
+
`INSERT INTO brim_rate_limits (key, window_start, count) VALUES (?, ?, ?)
|
|
64
|
+
ON CONFLICT (key) DO UPDATE SET
|
|
65
|
+
count = CASE WHEN window_start = excluded.window_start THEN count + excluded.count ELSE excluded.count END,
|
|
66
|
+
window_start = excluded.window_start
|
|
67
|
+
RETURNING count`,
|
|
68
|
+
[key, windowStart, amount],
|
|
69
|
+
);
|
|
70
|
+
return Number(rows[0]?.count ?? amount) <= limit;
|
|
71
|
+
}
|
|
72
|
+
}
|