@stamhoofd/backend-renderer 2.137.1 → 2.137.2

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.1",
3
+ "version": "2.137.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "exports": {
@@ -27,14 +27,14 @@
27
27
  "@simonbackx/simple-endpoints": "1.21.1",
28
28
  "@simonbackx/simple-errors": "1.5.0",
29
29
  "@simonbackx/simple-logging": "1.0.1",
30
- "@stamhoofd/backend-env": "2.137.1",
31
- "@stamhoofd/backend-i18n": "2.137.1",
32
- "@stamhoofd/backend-middleware": "2.137.1",
33
- "@stamhoofd/logging": "2.137.1",
34
- "@stamhoofd/queues": "2.137.1",
35
- "@stamhoofd/structures": "2.137.1",
36
- "@stamhoofd/types": "2.137.1",
37
- "@stamhoofd/utility": "2.137.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",
38
38
  "formidable": "3.5.4",
39
39
  "luxon": "3.7.2",
40
40
  "mockdate": "3.0.5",
@@ -42,16 +42,16 @@
42
42
  "puppeteer": "25.3.0"
43
43
  },
44
44
  "devDependencies": {
45
- "@stamhoofd/test-utils": "2.137.1",
45
+ "@stamhoofd/test-utils": "2.137.2",
46
46
  "@types/formidable": "3.5.1",
47
- "@types/luxon": "3.7.1",
47
+ "@types/luxon": "3.7.2",
48
48
  "@types/node": "22.20.1",
49
- "nock": "14.0.15",
50
- "vitest": "4.1.8"
49
+ "nock": "14.0.16",
50
+ "vitest": "4.1.10"
51
51
  },
52
52
  "license": "UNLICENCED",
53
53
  "publishConfig": {
54
54
  "access": "public"
55
55
  },
56
- "gitHead": "951f73f30cf648612da5e4ff22d9db19f5a8f31e"
56
+ "gitHead": "e0a970fd52c4f5a57f1e5a41cf40940859277ddf"
57
57
  }
@@ -99,4 +99,49 @@ describe('Endpoint.Prerender', () => {
99
99
  location: 'https://shop.stamhoofd.be/test',
100
100
  }));
101
101
  });
102
+
103
+ describe('cleanHeaders', () => {
104
+ test('Ignores the Content-Security-Policy header (the renderer sets its own via CORSMiddleware)', () => {
105
+ // Caddy sets two CSP headers on documents; Puppeteer hands them back as one newline-joined
106
+ // value. We never forward it (CORSMiddleware overwrites it anyway), so the crash-prone
107
+ // header is dropped regardless of how Puppeteer joined it.
108
+ const cleaned = PrerenderEndpoint.cleanHeaders({
109
+ 'content-security-policy': `script-src 'nonce-abc' 'strict-dynamic'; object-src 'none'; base-uri 'none'\nscript-src 'self' 'nonce-abc'`,
110
+ });
111
+
112
+ expect(cleaned).not.toHaveProperty('content-security-policy');
113
+ });
114
+
115
+ test('Ignores any header whose value contains a CR/LF (would throw ERR_INVALID_CHAR)', () => {
116
+ const cleaned = PrerenderEndpoint.cleanHeaders({
117
+ 'x-newline': 'a\nb',
118
+ 'x-carriage-return': 'a\r\nb',
119
+ 'x-ok': 'clean',
120
+ });
121
+
122
+ expect(cleaned).not.toHaveProperty('x-newline');
123
+ expect(cleaned).not.toHaveProperty('x-carriage-return');
124
+ expect(cleaned['x-ok']).toBe('clean');
125
+ });
126
+
127
+ test('Lowercases keys and forwards other single-line headers unchanged', () => {
128
+ const cleaned = PrerenderEndpoint.cleanHeaders({
129
+ 'Cache-Control': 'no-cache',
130
+ });
131
+
132
+ expect(cleaned['cache-control']).toBe('no-cache');
133
+ });
134
+
135
+ test('Drops hop-by-hop, set-cookie and empty headers', () => {
136
+ const cleaned = PrerenderEndpoint.cleanHeaders({
137
+ 'connection': 'keep-alive',
138
+ 'transfer-encoding': 'chunked',
139
+ 'set-cookie': 'session=1',
140
+ 'content-length': '123',
141
+ 'x-empty': '',
142
+ });
143
+
144
+ expect(cleaned).toEqual({});
145
+ });
146
+ });
102
147
  });
@@ -10,15 +10,15 @@ import { HtmlToPdfEndpoint } from './HtmlToPdfEndpoint.js';
10
10
  type Params = Record<string, never>;
11
11
  type Body = undefined;
12
12
  class Query extends AutoEncoder {
13
- @field({decoder: new URLDecoder()})
14
- url: URL
13
+ @field({ decoder: new URLDecoder() })
14
+ url: URL;
15
15
  }
16
16
 
17
17
  type Data = {
18
18
  html: string;
19
19
  headers: Record<string, string>;
20
- statusCode: number
21
- }
20
+ statusCode: number;
21
+ };
22
22
 
23
23
  type ResponseBody = string;
24
24
 
@@ -27,7 +27,7 @@ type ResponseBody = string;
27
27
  */
28
28
 
29
29
  export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBody> {
30
- queryDecoder = Query as Decoder<Query>
30
+ queryDecoder = Query as Decoder<Query>;
31
31
 
32
32
  protected doesMatch(request: Request): [true, Params] | [false] {
33
33
  if (request.method !== 'POST') {
@@ -43,15 +43,14 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
43
43
  }
44
44
 
45
45
  async handle(request: DecodedRequest<Params, Query, Body>) {
46
- const url = request.query.url.href
46
+ const url = request.query.url.href;
47
47
 
48
- console.log('Prerendering ' + url)
48
+ console.log('Prerendering ' + url);
49
49
 
50
50
  let data: Data | null = null;
51
51
  try {
52
52
  data = await PrerenderEndpoint.getUrlHtml(url, { retryCount: 2, startDate: new Date() });
53
- }
54
- catch (e) {
53
+ } catch (e) {
55
54
  console.error(e);
56
55
  }
57
56
  if (!data) {
@@ -62,25 +61,53 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
62
61
  });
63
62
  }
64
63
  const response = new Response(data.html);
65
- data.headers['content-type'] = 'text/html'
66
- response.headers = data.headers
67
- response.status = data.statusCode
64
+ data.headers['content-type'] = 'text/html';
65
+ response.headers = data.headers;
66
+ response.status = data.statusCode;
68
67
  return response;
69
68
  }
70
-
69
+
71
70
  static readonly CACHE_TTL_MS = 60 * 1000 * 60 * 12; // 12 hours
72
- static fileCache = new TTLFileCache('prerender', this.CACHE_TTL_MS)
71
+ static fileCache = new TTLFileCache('prerender', this.CACHE_TTL_MS);
72
+
73
+ /**
74
+ * Response headers we never copy from the prerendered page onto our own response
75
+ */
76
+ static readonly SKIPPED_HEADERS = new Set([
77
+ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer',
78
+ 'transfer-encoding', 'upgrade', 'via', 'content-length', 'content-encoding', 'set-cookie', 'server',
79
+ 'content-security-policy',
80
+ ]);
81
+
82
+ static cleanHeaders(headers: Record<string, string | undefined>): Record<string, string> {
83
+ const cleanedHeaders: Record<string, string> = {};
84
+ for (const key of Object.keys(headers)) {
85
+ const rawValue = headers[key];
86
+ if (!rawValue) {
87
+ continue;
88
+ }
89
+ const l = key.toLowerCase();
90
+ if (this.SKIPPED_HEADERS.has(l)) {
91
+ continue;
92
+ }
93
+ if (/[\r\n]/.test(rawValue)) {
94
+ continue;
95
+ }
96
+ cleanedHeaders[l] = rawValue;
97
+ }
98
+ return cleanedHeaders;
99
+ }
73
100
 
74
- static async getUrlHtml(url: string, options: { retryCount: number; startDate: Date }): Promise<Data | null> {
101
+ static async getUrlHtml(url: string, options: { retryCount: number; startDate: Date }): Promise<Data | null> {
75
102
  const existing = await this.fileCache.checkCache(url, this.CACHE_TTL_MS);
76
103
  if (existing) {
77
104
  try {
78
105
  const d = JSON.parse(existing);
79
106
 
80
- if (typeof d === 'object' && d !== null && 'html' in d && 'statusCode' in d && 'headers' in d) {
107
+ if (typeof d === 'object' && d !== null && 'html' in d && 'statusCode' in d && 'headers' in d) {
81
108
  return d;
82
109
  } else {
83
- console.error('Invalid cached data point for ' + url)
110
+ console.error('Invalid cached data point for ' + url);
84
111
  }
85
112
  } catch (e) {
86
113
  console.error(e);
@@ -92,7 +119,7 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
92
119
  const page = await browser.newPage();
93
120
 
94
121
  await page.setUserAgent({
95
- userAgent: 'prerender'
122
+ userAgent: 'prerender',
96
123
  });
97
124
 
98
125
  await page.setJavaScriptEnabled(true);
@@ -144,10 +171,10 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
144
171
  return el ? el.getAttribute('content')?.replace(/^Location:\s*/i, '') : null;
145
172
  });
146
173
  if (dmetaLocation) {
147
- metaLocation = dmetaLocation
174
+ metaLocation = dmetaLocation;
148
175
  } else {
149
176
  // something went wrong...
150
- console.error('Missing Location header')
177
+ console.error('Missing Location header');
151
178
  effectiveStatus = 500;
152
179
  }
153
180
  }
@@ -156,11 +183,11 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
156
183
  // Strip <script> tags and <link rel="preload|modulepreload"> from the DOM
157
184
  await page.evaluate(() => {
158
185
  // Remove all script tags
159
- document.querySelectorAll('script').forEach((el) => el.remove());
186
+ document.querySelectorAll('script').forEach(el => el.remove());
160
187
 
161
188
  // Remove preload / modulepreload link tags (removePreloads plugin)
162
189
  document.querySelectorAll('link[rel="preload"][as="script"], link[rel="prefetch"][as="script"], link[rel="prefetch"][as="style"], link[rel="modulepreload"][as="script"]')
163
- .forEach((el) => el.remove());
190
+ .forEach(el => el.remove());
164
191
  });
165
192
 
166
193
  // Ibject <base href="url here" />
@@ -168,9 +195,8 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
168
195
  if (STAMHOOFD.environment === 'test') {
169
196
  await page.evaluate(() => {
170
197
  const child = document.createElement('base');
171
- child.href = location.href;
172
- document.head.prepend(child)
173
-
198
+ child.href = location.href;
199
+ document.head.prepend(child);
174
200
  });
175
201
  }
176
202
 
@@ -181,18 +207,8 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
181
207
  return null;
182
208
  }
183
209
 
184
- // lowercase all headers
185
- const cleanedHeaders: Record<string, string> = {};
186
- for (const key of Object.keys(headers)) {
187
- if (!headers[key]) {
188
- continue;
189
- }
190
- const l = key.toLowerCase();
191
- if (['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'via', 'content-length', 'content-encoding', 'set-cookie', 'server'].includes(l)) {
192
- continue;
193
- }
194
- cleanedHeaders[l] = headers[key]
195
- }
210
+ // lowercase, filter and sanitize the upstream headers before forwarding them
211
+ const cleanedHeaders = PrerenderEndpoint.cleanHeaders(headers);
196
212
 
197
213
  if (metaLocation) {
198
214
  cleanedHeaders.location = metaLocation;
@@ -200,9 +216,9 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
200
216
  delete cleanedHeaders.connection;
201
217
 
202
218
  return {
203
- html: '<!doctype html>' + html,
204
- statusCode: effectiveStatus,
205
- headers: cleanedHeaders
219
+ html: '<!doctype html>' + html,
220
+ statusCode: effectiveStatus,
221
+ headers: cleanedHeaders,
206
222
  };
207
223
  } catch (e) {
208
224
  console.error('Failed to render url', e);
@@ -217,11 +233,9 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
217
233
 
218
234
  // Store in cache
219
235
  if (response !== null) {
220
- await this.fileCache.cacheFile(url, JSON.stringify(response))
236
+ await this.fileCache.cacheFile(url, JSON.stringify(response));
221
237
  return response;
222
-
223
238
  }
224
239
  return null;
225
-
226
240
  }
227
241
  }