@stamhoofd/backend-renderer 2.137.2 → 2.137.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stamhoofd/backend-renderer",
3
- "version": "2.137.2",
3
+ "version": "2.137.4",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "exports": {
@@ -24,17 +24,17 @@
24
24
  "dependencies": {
25
25
  "@simonbackx/simple-database": "1.37.1",
26
26
  "@simonbackx/simple-encoding": "2.26.11",
27
- "@simonbackx/simple-endpoints": "1.21.1",
27
+ "@simonbackx/simple-endpoints": "1.22.0",
28
28
  "@simonbackx/simple-errors": "1.5.0",
29
29
  "@simonbackx/simple-logging": "1.0.1",
30
- "@stamhoofd/backend-env": "2.137.2",
31
- "@stamhoofd/backend-i18n": "2.137.2",
32
- "@stamhoofd/backend-middleware": "2.137.2",
33
- "@stamhoofd/logging": "2.137.2",
34
- "@stamhoofd/queues": "2.137.2",
35
- "@stamhoofd/structures": "2.137.2",
36
- "@stamhoofd/types": "2.137.2",
37
- "@stamhoofd/utility": "2.137.2",
30
+ "@stamhoofd/backend-env": "2.137.4",
31
+ "@stamhoofd/backend-i18n": "2.137.4",
32
+ "@stamhoofd/backend-middleware": "2.137.4",
33
+ "@stamhoofd/logging": "2.137.4",
34
+ "@stamhoofd/queues": "2.137.4",
35
+ "@stamhoofd/structures": "2.137.4",
36
+ "@stamhoofd/types": "2.137.4",
37
+ "@stamhoofd/utility": "2.137.4",
38
38
  "formidable": "3.5.4",
39
39
  "luxon": "3.7.2",
40
40
  "mockdate": "3.0.5",
@@ -42,7 +42,7 @@
42
42
  "puppeteer": "25.3.0"
43
43
  },
44
44
  "devDependencies": {
45
- "@stamhoofd/test-utils": "2.137.2",
45
+ "@stamhoofd/test-utils": "2.137.4",
46
46
  "@types/formidable": "3.5.1",
47
47
  "@types/luxon": "3.7.2",
48
48
  "@types/node": "22.20.1",
@@ -53,5 +53,5 @@
53
53
  "publishConfig": {
54
54
  "access": "public"
55
55
  },
56
- "gitHead": "e0a970fd52c4f5a57f1e5a41cf40940859277ddf"
56
+ "gitHead": "22cb2b32de8f785d8e0d94f324940d6419fbe7ea"
57
57
  }
package/src/boot.ts CHANGED
@@ -2,6 +2,8 @@ import { CORSPreflightEndpoint, Router, RouterServer } from '@simonbackx/simple-
2
2
  import { I18n } from '@stamhoofd/backend-i18n';
3
3
  import { CORSMiddleware, LogMiddleware } from '@stamhoofd/backend-middleware';
4
4
  import { loadLogger } from '@stamhoofd/logging';
5
+ import { CpuService } from '@stamhoofd/logging/CpuService';
6
+ import { TrustedIPWhitelist } from './classes/TrustedIPWhitelist.js';
5
7
 
6
8
  process.on('unhandledRejection', (error: Error) => {
7
9
  console.error('unhandledRejection');
@@ -21,6 +23,11 @@ const start = async () => {
21
23
  console.log('Started Renderer.');
22
24
  loadLogger();
23
25
  await I18n.load();
26
+
27
+ // Load the trusted IP whitelist that guards the /prerender endpoint (no-op when not configured).
28
+ await TrustedIPWhitelist.shared.load();
29
+ TrustedIPWhitelist.shared.startAutoRefresh();
30
+
24
31
  const router = new Router();
25
32
  await router.loadEndpoints(import.meta.dirname + '/endpoints');
26
33
  router.endpoints.push(new CORSPreflightEndpoint());
@@ -37,6 +44,11 @@ const start = async () => {
37
44
 
38
45
  routerServer.listen(STAMHOOFD.PORT ?? 9090);
39
46
 
47
+ // Monitor CPU load so the /health endpoint can report an overloaded renderer as unhealthy.
48
+ if (STAMHOOFD.environment !== 'development' && STAMHOOFD.environment !== 'test') {
49
+ CpuService.startMonitoring();
50
+ }
51
+
40
52
  if (routerServer.server) {
41
53
  // Default timeout is a bit too short
42
54
  routerServer.server.timeout = 15000;
@@ -0,0 +1,161 @@
1
+ import { STExpect, TestUtils } from '@stamhoofd/test-utils';
2
+ import fs from 'fs/promises';
3
+ import path from 'path';
4
+ import { TrustedIPWhitelist } from './TrustedIPWhitelist.js';
5
+
6
+ describe('TrustedIPWhitelist', () => {
7
+ const whitelist = TrustedIPWhitelist.shared;
8
+
9
+ afterEach(() => {
10
+ whitelist.setFromText('');
11
+ });
12
+
13
+ describe('when disabled (no URL configured, non-deployment environment)', () => {
14
+ test('enabled is false and assertAllowed is a no-op', () => {
15
+ expect(whitelist.enabled).toBe(false);
16
+ expect(whitelist.url).toBeUndefined();
17
+ expect(() => whitelist.assertAllowed('8.8.8.8')).not.toThrow();
18
+ expect(() => whitelist.assertAllowed('?')).not.toThrow();
19
+ });
20
+ });
21
+
22
+ describe('default URL in real deployments', () => {
23
+ test('production defaults to the built-in list URL', () => {
24
+ TestUtils.setEnvironment('environment', 'production');
25
+ expect(whitelist.enabled).toBe(true);
26
+ expect(whitelist.url).toBe(TrustedIPWhitelist.DEFAULT_URL);
27
+ });
28
+
29
+ test('staging defaults to the built-in list URL', () => {
30
+ TestUtils.setEnvironment('environment', 'staging');
31
+ expect(whitelist.url).toBe(TrustedIPWhitelist.DEFAULT_URL);
32
+ });
33
+
34
+ test('an explicit URL overrides the default', () => {
35
+ TestUtils.setEnvironment('environment', 'production');
36
+ TestUtils.setEnvironment('PRERENDER_IP_WHITELIST_URL', 'https://example.com/list.txt');
37
+ expect(whitelist.url).toBe('https://example.com/list.txt');
38
+ });
39
+ });
40
+
41
+ describe('when enabled', () => {
42
+ beforeEach(() => {
43
+ TestUtils.setEnvironment('PRERENDER_IP_WHITELIST_URL', 'https://example.com/list.txt');
44
+ });
45
+
46
+ test('enabled reflects the configured URL', () => {
47
+ expect(whitelist.enabled).toBe(true);
48
+ expect(whitelist.url).toBe('https://example.com/list.txt');
49
+ });
50
+
51
+ test('setFromText parses entries and skips comments/blank lines', () => {
52
+ const count = whitelist.setFromText('# a comment\n1.2.3.4\n\n10.0.0.0/8\n \nnot-an-ip\n');
53
+ // '1.2.3.4' and '10.0.0.0/8' are valid; the comment, blanks and 'not-an-ip' are ignored
54
+ expect(count).toBe(2);
55
+ expect(whitelist.count).toBe(2);
56
+ });
57
+
58
+ test('allows whitelisted IPs and blocks the rest', () => {
59
+ whitelist.setFromText('1.2.3.4\n10.0.0.0/8');
60
+
61
+ expect(whitelist.isWhitelisted('1.2.3.4')).toBe(true);
62
+ expect(whitelist.isWhitelisted('10.255.255.255')).toBe(true);
63
+ expect(whitelist.isWhitelisted('8.8.8.8')).toBe(false);
64
+
65
+ expect(() => whitelist.assertAllowed('10.1.2.3')).not.toThrow();
66
+ expect(() => whitelist.assertAllowed('8.8.8.8')).toThrow(
67
+ STExpect.simpleError({ code: 'ip_not_whitelisted', statusCode: 403 }),
68
+ );
69
+ });
70
+
71
+ test('blocks everything when no list is loaded (fail-closed)', () => {
72
+ expect(whitelist.count).toBe(0);
73
+ expect(() => whitelist.assertAllowed('1.2.3.4')).toThrow(
74
+ STExpect.simpleError({ code: 'ip_not_whitelisted', statusCode: 403 }),
75
+ );
76
+ });
77
+
78
+ test('blocks unknown/unparseable IPs', () => {
79
+ whitelist.setFromText('1.2.3.4');
80
+ expect(() => whitelist.assertAllowed('?')).toThrow(
81
+ STExpect.simpleError({ code: 'ip_not_whitelisted', statusCode: 403 }),
82
+ );
83
+ });
84
+ });
85
+
86
+ describe('load', () => {
87
+ const cacheFile = () => path.join(STAMHOOFD.CACHE_PATH, TrustedIPWhitelist.CACHE_FILE_NAME);
88
+
89
+ const removeCache = () => fs.rm(cacheFile(), { force: true });
90
+
91
+ function stubFetch(impl: () => Promise<unknown>) {
92
+ vi.stubGlobal('fetch', vi.fn(impl));
93
+ }
94
+
95
+ const okBody = (body: string) => Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve(body) });
96
+
97
+ beforeEach(async () => {
98
+ TestUtils.setEnvironment('PRERENDER_IP_WHITELIST_URL', 'https://example.com/list.txt');
99
+ await removeCache();
100
+ });
101
+
102
+ afterEach(async () => {
103
+ vi.unstubAllGlobals();
104
+ await removeCache();
105
+ });
106
+
107
+ test('fetches from the remote, installs the list and writes the cache', async () => {
108
+ stubFetch(() => okBody('1.2.3.4\n10.0.0.0/8'));
109
+
110
+ await whitelist.load();
111
+
112
+ expect(whitelist.count).toBe(2);
113
+ expect(whitelist.isWhitelisted('10.1.2.3')).toBe(true);
114
+ expect(await fs.readFile(cacheFile(), 'utf-8')).toBe('1.2.3.4\n10.0.0.0/8');
115
+ });
116
+
117
+ test('falls back to the disk cache when the remote fetch fails', async () => {
118
+ // A first successful load populates the disk cache.
119
+ stubFetch(() => okBody('5.6.7.8'));
120
+ await whitelist.load();
121
+ expect(whitelist.isWhitelisted('5.6.7.8')).toBe(true);
122
+
123
+ // The remote now fails: we keep serving the cached copy rather than dropping the list.
124
+ stubFetch(() => Promise.reject(new Error('network down')));
125
+ await whitelist.load();
126
+ expect(whitelist.count).toBe(1);
127
+ expect(whitelist.isWhitelisted('5.6.7.8')).toBe(true);
128
+ });
129
+
130
+ test('an empty remote response falls back to the disk cache', async () => {
131
+ stubFetch(() => okBody('9.9.9.9'));
132
+ await whitelist.load();
133
+
134
+ stubFetch(() => okBody(' \n# nothing useful\n'));
135
+ await whitelist.load();
136
+ expect(whitelist.isWhitelisted('9.9.9.9')).toBe(true);
137
+ });
138
+
139
+ test('blocks everything (fail-closed) when the remote fails and there is no cache', async () => {
140
+ stubFetch(() => Promise.reject(new Error('network down')));
141
+
142
+ await whitelist.load();
143
+
144
+ expect(whitelist.count).toBe(0);
145
+ expect(() => whitelist.assertAllowed('1.2.3.4')).toThrow(
146
+ STExpect.simpleError({ code: 'ip_not_whitelisted', statusCode: 403 }),
147
+ );
148
+ });
149
+
150
+ test('is a no-op (no fetch) when whitelisting is disabled', async () => {
151
+ TestUtils.setEnvironment('PRERENDER_IP_WHITELIST_URL', undefined);
152
+ const fetchSpy = vi.fn(() => okBody('1.2.3.4'));
153
+ vi.stubGlobal('fetch', fetchSpy);
154
+
155
+ await whitelist.load();
156
+
157
+ expect(fetchSpy).not.toHaveBeenCalled();
158
+ expect(whitelist.count).toBe(0);
159
+ });
160
+ });
161
+ });
@@ -0,0 +1,232 @@
1
+ import { SimpleError } from '@simonbackx/simple-errors';
2
+ import { IPRangeSet } from '@stamhoofd/utility/IPRange.js';
3
+ import fs from 'fs/promises';
4
+ import path from 'path';
5
+
6
+ /**
7
+ * Guards the /prerender endpoint against being overloaded by (spam) bots by only allowing
8
+ * requests from a whitelist of trusted IP addresses (legitimate crawlers, AI bots, monitoring, ...).
9
+ *
10
+ * The whitelist is fetched from a public, plain-text list and cached on disk. On boot and on every
11
+ * refresh we try the remote source first and fall back to the local cache when it's unavailable, so
12
+ * a transient outage never wipes the whitelist. If no list is available at all (neither remote nor
13
+ * cache), the set stays empty and every request is blocked (fail-closed) — a state our monitoring
14
+ * should alert on.
15
+ *
16
+ * The source URL defaults to {@link TrustedIPWhitelist.DEFAULT_URL} in real deployments (production
17
+ * and staging) and can be overridden with PRERENDER_IP_WHITELIST_URL. In local development and tests
18
+ * it's off by default and only enabled when PRERENDER_IP_WHITELIST_URL is explicitly set.
19
+ */
20
+ export class TrustedIPWhitelist {
21
+ static shared = new TrustedIPWhitelist();
22
+
23
+ /**
24
+ * Default trusted-IP source: the "all safe IPs" list (crawlers, AI bots, infrastructure,
25
+ * monitoring and DNS resolvers) from https://github.com/sefinek/trusted-ips-whitelist.
26
+ */
27
+ static readonly DEFAULT_URL = 'https://raw.githubusercontent.com/sefinek/trusted-ips-whitelist/main/lists/all-safe-ips.txt';
28
+
29
+ /** The upstream list is regenerated roughly every 6 hours. */
30
+ static readonly REFRESH_INTERVAL_MS = 6 * 60 * 60 * 1000;
31
+ /** While we have no list at all (fail-closed, blocking everything), retry much more often. */
32
+ static readonly EMPTY_RETRY_INTERVAL_MS = 5 * 60 * 1000;
33
+ static readonly FETCH_TIMEOUT_MS = 30 * 1000;
34
+ static readonly CACHE_FILE_NAME = 'trusted-ips-whitelist.txt';
35
+
36
+ private set = new IPRangeSet();
37
+ private refreshTimer: NodeJS.Timeout | null = null;
38
+ private autoRefreshActive = false;
39
+
40
+ get enabled(): boolean {
41
+ return !!this.url;
42
+ }
43
+
44
+ get url(): string | undefined {
45
+ if (STAMHOOFD.PRERENDER_IP_WHITELIST_URL) {
46
+ return STAMHOOFD.PRERENDER_IP_WHITELIST_URL;
47
+ }
48
+
49
+ // Enabled by default in real deployments; opt-in (via the env var) for local dev and tests.
50
+ if (STAMHOOFD.environment === 'production' || STAMHOOFD.environment === 'staging') {
51
+ return TrustedIPWhitelist.DEFAULT_URL;
52
+ }
53
+
54
+ return undefined;
55
+ }
56
+
57
+ /** Number of ranges currently loaded (for logging/monitoring/tests). */
58
+ get count(): number {
59
+ return this.set.size;
60
+ }
61
+
62
+ private get cacheFilePath(): string {
63
+ return path.join(STAMHOOFD.CACHE_PATH, TrustedIPWhitelist.CACHE_FILE_NAME);
64
+ }
65
+
66
+ /**
67
+ * Parse raw list text into a set of ranges. Lines that are empty or start with '#' are
68
+ * ignored; unparseable lines are skipped (and logged).
69
+ */
70
+ private parse(text: string): IPRangeSet {
71
+ const set = new IPRangeSet();
72
+ set.addText(text, (line, error) => {
73
+ console.error(`[trusted-ips] Failed to parse line: ${line}`, error);
74
+ });
75
+ return set;
76
+ }
77
+
78
+ /**
79
+ * Replace the in-memory ranges from raw list text. Returns the number of parsed entries.
80
+ */
81
+ setFromText(text: string): number {
82
+ this.set = this.parse(text);
83
+ return this.set.size;
84
+ }
85
+
86
+ private async fetchRemote(): Promise<string> {
87
+ const url = this.url;
88
+ if (!url) {
89
+ throw new Error('No PRERENDER_IP_WHITELIST_URL configured');
90
+ }
91
+
92
+ const controller = new AbortController();
93
+ const timeout = setTimeout(() => controller.abort(), TrustedIPWhitelist.FETCH_TIMEOUT_MS);
94
+
95
+ try {
96
+ const response = await fetch(url, { signal: controller.signal });
97
+ if (!response.ok) {
98
+ throw new Error(`Unexpected status ${response.status} while fetching ${url}`);
99
+ }
100
+ return await response.text();
101
+ } finally {
102
+ clearTimeout(timeout);
103
+ }
104
+ }
105
+
106
+ private async readCache(): Promise<string | null> {
107
+ try {
108
+ return await fs.readFile(this.cacheFilePath, 'utf-8');
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ private async writeCache(text: string): Promise<void> {
115
+ try {
116
+ await fs.mkdir(STAMHOOFD.CACHE_PATH, { recursive: true });
117
+ await fs.writeFile(this.cacheFilePath, text, 'utf-8');
118
+ } catch (error) {
119
+ console.error('[trusted-ips] Failed to persist whitelist cache', error);
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Fetch the whitelist from the remote source and persist it locally. Falls back to the
125
+ * locally cached copy when the remote fetch fails or returns an empty list, so a transient
126
+ * outage doesn't drop the whitelist. Never throws: a failure just leaves the previous set
127
+ * in place, or an empty set if nothing could be loaded.
128
+ */
129
+ async load(): Promise<void> {
130
+ if (!this.enabled) {
131
+ return;
132
+ }
133
+
134
+ try {
135
+ const text = await this.fetchRemote();
136
+ const set = this.parse(text);
137
+
138
+ if (set.size > 0) {
139
+ // Only install and persist a valid, non-empty list.
140
+ this.set = set;
141
+ await this.writeCache(text);
142
+ console.log(`[trusted-ips] Loaded ${set.size} trusted IP ranges from ${this.url}`);
143
+ return;
144
+ }
145
+
146
+ console.error('[trusted-ips] Remote whitelist was empty, falling back to local cache');
147
+ } catch (error) {
148
+ console.error('[trusted-ips] Failed to fetch remote whitelist, falling back to local cache', error);
149
+ }
150
+
151
+ // Fall back to the last known good copy on disk. We keep the current in-memory set until
152
+ // we have a valid replacement, so a failed refresh never blocks requests it was serving.
153
+ const cached = await this.readCache();
154
+ if (cached !== null) {
155
+ const set = this.parse(cached);
156
+ if (set.size > 0) {
157
+ this.set = set;
158
+ console.log(`[trusted-ips] Loaded ${set.size} trusted IP ranges from local cache`);
159
+ return;
160
+ }
161
+ }
162
+
163
+ // No usable list at all: block every request (fail-closed). Monitoring should alert on this.
164
+ this.set = new IPRangeSet();
165
+ console.error('[trusted-ips] No trusted IP whitelist available (remote and cache both failed). Prerender requests will be blocked.');
166
+ }
167
+
168
+ /**
169
+ * Delay until the next background refresh. While we have a usable list we only need to keep up
170
+ * with the upstream (regenerated ~every 6h); while we have nothing (fail-closed, blocking every
171
+ * request) we retry much more often so a brief upstream outage doesn't blackhole prerendering.
172
+ */
173
+ private nextRefreshDelay(): number {
174
+ return this.count > 0
175
+ ? TrustedIPWhitelist.REFRESH_INTERVAL_MS
176
+ : TrustedIPWhitelist.EMPTY_RETRY_INTERVAL_MS;
177
+ }
178
+
179
+ /** Periodically refresh the whitelist in the background. Safe to call multiple times. */
180
+ startAutoRefresh(): void {
181
+ if (!this.enabled || this.autoRefreshActive) {
182
+ return;
183
+ }
184
+
185
+ this.autoRefreshActive = true;
186
+ this.scheduleNextRefresh();
187
+ }
188
+
189
+ private scheduleNextRefresh(): void {
190
+ if (!this.autoRefreshActive) {
191
+ return;
192
+ }
193
+
194
+ this.refreshTimer = setTimeout(() => {
195
+ // load() never rejects (it handles its own errors); reschedule once it settles.
196
+ void this.load().finally(() => this.scheduleNextRefresh());
197
+ }, this.nextRefreshDelay());
198
+
199
+ // Don't keep the event loop alive just for refreshing.
200
+ this.refreshTimer.unref?.();
201
+ }
202
+
203
+ stopAutoRefresh(): void {
204
+ this.autoRefreshActive = false;
205
+ if (this.refreshTimer) {
206
+ clearTimeout(this.refreshTimer);
207
+ this.refreshTimer = null;
208
+ }
209
+ }
210
+
211
+ isWhitelisted(ip: string): boolean {
212
+ return this.set.includes(ip);
213
+ }
214
+
215
+ /**
216
+ * Throws a 403 when whitelisting is enabled and the IP is not allowed (including when the
217
+ * whitelist could not be loaded). When disabled this is a no-op.
218
+ */
219
+ assertAllowed(ip: string): void {
220
+ if (!this.enabled) {
221
+ return;
222
+ }
223
+
224
+ if (!this.isWhitelisted(ip)) {
225
+ throw new SimpleError({
226
+ statusCode: 403,
227
+ code: 'ip_not_whitelisted',
228
+ message: `IP ${ip} is not in the trusted IP whitelist`,
229
+ });
230
+ }
231
+ }
232
+ }
@@ -0,0 +1,66 @@
1
+ import { Request, TestServer } from '@simonbackx/simple-endpoints';
2
+ import { CpuService } from '@stamhoofd/logging/CpuService';
3
+ import { STExpect, TestUtils } from '@stamhoofd/test-utils';
4
+ import { HealthEndpoint } from './HealthEndpoint.js';
5
+
6
+ describe('Endpoint.Health', () => {
7
+ const endpoint = new HealthEndpoint();
8
+ const testServer = new TestServer();
9
+ const key = 'health-test-key';
10
+
11
+ beforeEach(() => {
12
+ TestUtils.setEnvironment('HEALTH_ACCESS_KEY', key);
13
+ });
14
+
15
+ afterEach(() => {
16
+ // Reset the CPU samples so a high-load test doesn't leak into the next one.
17
+ CpuService.samples.fill(0);
18
+ });
19
+
20
+ test('Returns 200 when healthy', async () => {
21
+ const request = Request.get({
22
+ path: '/health',
23
+ query: { key },
24
+ });
25
+
26
+ const response = await testServer.test(endpoint, request);
27
+ expect(response.status).toBe(200);
28
+ expect(response.body.status).toBe('ok');
29
+ expect(response.body.errors).toBeUndefined();
30
+ });
31
+
32
+ test('Returns 503 when CPU usage is too high', async () => {
33
+ CpuService.samples.fill(95);
34
+
35
+ const request = Request.get({
36
+ path: '/health',
37
+ query: { key },
38
+ });
39
+
40
+ const response = await testServer.test(endpoint, request);
41
+ expect(response.status).toBe(503);
42
+ expect(response.body.status).toBe('error');
43
+ expect(response.body.errors).toContain('CPU usage is too high');
44
+ });
45
+
46
+ test('Rejects requests with a wrong key', async () => {
47
+ const request = Request.get({
48
+ path: '/health',
49
+ query: { key: 'wrong-key' },
50
+ });
51
+
52
+ await expect(testServer.test(endpoint, request)).rejects.toThrow(
53
+ STExpect.simpleError({ code: 'unauthorized', statusCode: 401 }),
54
+ );
55
+ });
56
+
57
+ test('Rejects requests without a key', async () => {
58
+ const request = Request.get({
59
+ path: '/health',
60
+ });
61
+
62
+ await expect(testServer.test(endpoint, request)).rejects.toThrow(
63
+ STExpect.simpleError({ code: 'unauthorized', statusCode: 401 }),
64
+ );
65
+ });
66
+ });
@@ -0,0 +1,88 @@
1
+ import { ArrayDecoder, AutoEncoder, field, StringDecoder } from '@simonbackx/simple-encoding';
2
+ import type { DecodedRequest, Request } from '@simonbackx/simple-endpoints';
3
+ import { Endpoint, Response } from '@simonbackx/simple-endpoints';
4
+ import { SimpleError } from '@simonbackx/simple-errors';
5
+ import { CpuService } from '@stamhoofd/logging/CpuService';
6
+
7
+ type Params = Record<string, never>;
8
+ type Body = undefined;
9
+
10
+ class Query extends AutoEncoder {
11
+ @field({ decoder: StringDecoder, optional: true })
12
+ key?: string;
13
+ }
14
+
15
+ export class ResponseBody extends AutoEncoder {
16
+ @field({ decoder: StringDecoder })
17
+ status: 'ok' | 'error';
18
+
19
+ @field({ decoder: new ArrayDecoder(StringDecoder), optional: true })
20
+ errors?: string[];
21
+ }
22
+
23
+ /**
24
+ * Liveness/health endpoint for the renderer service. Guarded by an optional access key so it can be
25
+ * polled by load balancers and monitoring without exposing anything sensitive. The endpoint is only
26
+ * registered when a HEALTH_ACCESS_KEY is configured.
27
+ */
28
+
29
+ export class HealthEndpoint extends Endpoint<Params, Query, Body, ResponseBody> {
30
+ queryDecoder = Query;
31
+
32
+ protected doesMatch(request: Request): [true, Params] | [false] {
33
+ if (request.method !== 'GET') {
34
+ return [false];
35
+ }
36
+
37
+ if (!STAMHOOFD.HEALTH_ACCESS_KEY) {
38
+ return [false];
39
+ }
40
+
41
+ const params = Endpoint.parseParameters(request.url, '/health', {});
42
+
43
+ if (params) {
44
+ return [true, params as Params];
45
+ }
46
+ return [false];
47
+ }
48
+
49
+ async handle(request: DecodedRequest<Params, Query, Body>) {
50
+ if (!STAMHOOFD.HEALTH_ACCESS_KEY) {
51
+ throw new SimpleError({
52
+ code: 'unauthorized',
53
+ message: 'Unauthorized',
54
+ statusCode: 401,
55
+ });
56
+ }
57
+
58
+ if (STAMHOOFD.HEALTH_ACCESS_KEY && request.query.key !== STAMHOOFD.HEALTH_ACCESS_KEY) {
59
+ throw new SimpleError({
60
+ code: 'unauthorized',
61
+ message: 'Unauthorized',
62
+ statusCode: 401,
63
+ });
64
+ }
65
+
66
+ const errors: string[] = [];
67
+
68
+ // The renderer is CPU-bound (Puppeteer). Sustained high load means it can no longer render
69
+ // pages in time, so report it as unhealthy so it can be taken out of rotation.
70
+ if (CpuService.getAverage(60) > 80) {
71
+ errors.push('CPU usage is too high');
72
+ }
73
+
74
+ const health = ResponseBody.create({
75
+ status: errors.length > 0 ? 'error' : 'ok',
76
+ errors: errors.length > 0 ? errors : undefined,
77
+ });
78
+
79
+ const response = new Response(
80
+ health,
81
+ );
82
+
83
+ if (health.status === 'error') {
84
+ response.status = 503;
85
+ }
86
+ return response;
87
+ }
88
+ }
@@ -1,8 +1,9 @@
1
1
  import { Request, TestServer } from '@simonbackx/simple-endpoints';
2
2
  import { PrerenderEndpoint } from './PrerenderEndpoint.js';
3
3
  import nock from 'nock';
4
- import { STExpect } from '@stamhoofd/test-utils';
4
+ import { STExpect, TestUtils } from '@stamhoofd/test-utils';
5
5
  import fs from 'fs/promises';
6
+ import { TrustedIPWhitelist } from '../classes/TrustedIPWhitelist.js';
6
7
 
7
8
  async function fileExists(path: string): Promise<boolean> {
8
9
  try {
@@ -100,6 +101,68 @@ describe('Endpoint.Prerender', () => {
100
101
  }));
101
102
  });
102
103
 
104
+ describe('IP whitelist', () => {
105
+ afterEach(() => {
106
+ TrustedIPWhitelist.shared.setFromText('');
107
+ });
108
+
109
+ test('Blocks requests from non-whitelisted IPs with a 403', async () => {
110
+ // Enable whitelisting with a list that does not contain the test request's IP.
111
+ // No network/render happens: the request is rejected before any browser work.
112
+ TestUtils.setEnvironment('PRERENDER_IP_WHITELIST_URL', 'https://example.com/list.txt');
113
+ TrustedIPWhitelist.shared.setFromText('1.2.3.4\n10.0.0.0/8');
114
+ nock.disableNetConnect();
115
+
116
+ const request = Request.post({
117
+ path: '/prerender',
118
+ query: {
119
+ url: 'https://shop.stamhoofd.be/test/',
120
+ },
121
+ });
122
+
123
+ await expect(testServer.test(endpoint, request)).rejects.toThrow(
124
+ STExpect.simpleError({ code: 'ip_not_whitelisted', statusCode: 403 }),
125
+ );
126
+ });
127
+ });
128
+
129
+ describe('stripTrackingParams', () => {
130
+ test('Strips a single tracking parameter (fbclid)', () => {
131
+ expect(PrerenderEndpoint.stripTrackingParams('https://shop.stamhoofd.be/test/?fbclid=abc123'))
132
+ .toBe('https://shop.stamhoofd.be/test/');
133
+ });
134
+
135
+ test('Keeps non-tracking parameters and drops tracking ones', () => {
136
+ expect(PrerenderEndpoint.stripTrackingParams('https://shop.stamhoofd.be/test/?fbclid=abc&page=2&utm_source=news'))
137
+ .toBe('https://shop.stamhoofd.be/test/?page=2');
138
+ });
139
+
140
+ test('Strips utm_* prefixed parameters', () => {
141
+ expect(PrerenderEndpoint.stripTrackingParams('https://shop.stamhoofd.be/test/?utm_source=nl&utm_medium=email&utm_campaign=x'))
142
+ .toBe('https://shop.stamhoofd.be/test/');
143
+ });
144
+
145
+ test('Matches tracking parameter names case-insensitively', () => {
146
+ expect(PrerenderEndpoint.stripTrackingParams('https://shop.stamhoofd.be/test/?FBCLID=abc&UTM_Source=x'))
147
+ .toBe('https://shop.stamhoofd.be/test/');
148
+ });
149
+
150
+ test('Returns the original string unchanged when there is nothing to strip', () => {
151
+ const url = 'https://shop.stamhoofd.be/test/?page=2&sort=name';
152
+ expect(PrerenderEndpoint.stripTrackingParams(url)).toBe(url);
153
+ });
154
+
155
+ test('Leaves a URL without query parameters untouched', () => {
156
+ const url = 'https://shop.stamhoofd.be/test/';
157
+ expect(PrerenderEndpoint.stripTrackingParams(url)).toBe(url);
158
+ });
159
+
160
+ test('Does not treat a parameter merely containing a tracking name as tracking', () => {
161
+ const url = 'https://shop.stamhoofd.be/test/?myfbclid=x&customization=y';
162
+ expect(PrerenderEndpoint.stripTrackingParams(url)).toBe(url);
163
+ });
164
+ });
165
+
103
166
  describe('cleanHeaders', () => {
104
167
  test('Ignores the Content-Security-Policy header (the renderer sets its own via CORSMiddleware)', () => {
105
168
  // Caddy sets two CSP headers on documents; Puppeteer hands them back as one newline-joined
@@ -4,6 +4,7 @@ import { SimpleError } from '@simonbackx/simple-errors';
4
4
 
5
5
  import type { Decoder } from '@simonbackx/simple-encoding';
6
6
  import { AutoEncoder, field, URLDecoder } from '@simonbackx/simple-encoding';
7
+ import { TrustedIPWhitelist } from '../classes/TrustedIPWhitelist.js';
7
8
  import { TTLFileCache } from '../helpers/TTLFileCache.js';
8
9
  import { HtmlToPdfEndpoint } from './HtmlToPdfEndpoint.js';
9
10
 
@@ -43,7 +44,13 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
43
44
  }
44
45
 
45
46
  async handle(request: DecodedRequest<Params, Query, Body>) {
46
- const url = request.query.url.href;
47
+ // Only trusted IPs (legitimate crawlers/bots) may trigger a (potentially expensive)
48
+ // prerender. Throws a 403 for non-whitelisted IPs when whitelisting is enabled.
49
+ TrustedIPWhitelist.shared.assertAllowed(request.request.getIP());
50
+
51
+ // Strip click/campaign tracking parameters (e.g. ?fbclid) so we don't render and cache
52
+ // a separate copy of the same page for every unique tracking value.
53
+ const url = PrerenderEndpoint.stripTrackingParams(request.query.url.href);
47
54
 
48
55
  console.log('Prerendering ' + url);
49
56
 
@@ -79,6 +86,75 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
79
86
  'content-security-policy',
80
87
  ]);
81
88
 
89
+ /**
90
+ * Query parameters used purely for click/campaign tracking. They never influence the
91
+ * rendered page, so we drop them before requesting and caching the prerender. This keeps
92
+ * the cache from fragmenting into near-identical entries (one per ?fbclid, ?gclid, ...).
93
+ */
94
+ static readonly TRACKING_QUERY_PARAMS = new Set([
95
+ 'fbclid', // Facebook
96
+ 'gclid', // Google Ads
97
+ 'gclsrc', // Google Ads
98
+ 'dclid', // Google DoubleClick
99
+ 'wbraid', // Google Ads
100
+ 'gbraid', // Google Ads
101
+ 'msclkid', // Microsoft / Bing Ads
102
+ 'yclid', // Yandex
103
+ 'twclid', // Twitter / X
104
+ 'ttclid', // TikTok
105
+ 'igshid', // Instagram
106
+ 'mc_cid', // Mailchimp
107
+ 'mc_eid', // Mailchimp
108
+ '_hsenc', // HubSpot
109
+ '_hsmi', // HubSpot
110
+ 'vero_id', // Vero
111
+ 'vero_conv', // Vero
112
+ 'oly_anon_id', // Omeda
113
+ 'oly_enc_id', // Omeda
114
+ '_openstat', // Openstat
115
+ ]);
116
+
117
+ /**
118
+ * Any query parameter whose name starts with one of these prefixes is treated as tracking
119
+ * (e.g. utm_source, utm_medium, pk_campaign, mtm_kwd).
120
+ */
121
+ static readonly TRACKING_QUERY_PREFIXES = ['utm_', 'pk_', 'piwik_', 'mtm_', 'matomo_'];
122
+
123
+ static isTrackingParam(key: string): boolean {
124
+ const l = key.toLowerCase();
125
+ if (this.TRACKING_QUERY_PARAMS.has(l)) {
126
+ return true;
127
+ }
128
+ return this.TRACKING_QUERY_PREFIXES.some(prefix => l.startsWith(prefix));
129
+ }
130
+
131
+ /**
132
+ * Remove tracking query parameters from a URL. Returns the original string untouched when it
133
+ * isn't a valid absolute URL or when there is nothing to strip (so the common case keeps its
134
+ * exact formatting).
135
+ */
136
+ static stripTrackingParams(rawUrl: string): string {
137
+ let parsed: URL;
138
+ try {
139
+ parsed = new URL(rawUrl);
140
+ } catch {
141
+ return rawUrl;
142
+ }
143
+
144
+ let changed = false;
145
+ for (const key of [...parsed.searchParams.keys()]) {
146
+ if (this.isTrackingParam(key)) {
147
+ parsed.searchParams.delete(key);
148
+ changed = true;
149
+ }
150
+ }
151
+
152
+ if (!changed) {
153
+ return rawUrl;
154
+ }
155
+ return parsed.href;
156
+ }
157
+
82
158
  static cleanHeaders(headers: Record<string, string | undefined>): Record<string, string> {
83
159
  const cleanedHeaders: Record<string, string> = {};
84
160
  for (const key of Object.keys(headers)) {