@stamhoofd/backend-renderer 2.152.0 → 2.160.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.md +7 -7
- package/README.md +11 -1
- package/dist/boot.js +83 -0
- package/dist/boot.js.map +1 -0
- package/dist/classes/TrustedIPWhitelist.js +204 -0
- package/dist/classes/TrustedIPWhitelist.js.map +1 -0
- package/dist/endpoints/HealthEndpoint.js +76 -0
- package/dist/endpoints/HealthEndpoint.js.map +1 -0
- package/dist/endpoints/HtmlToPdfEndpoint.js +220 -0
- package/dist/endpoints/HtmlToPdfEndpoint.js.map +1 -0
- package/dist/endpoints/PdfCacheEndpoint.js +66 -0
- package/dist/endpoints/PdfCacheEndpoint.js.map +1 -0
- package/dist/endpoints/PrerenderEndpoint.js +276 -0
- package/dist/endpoints/PrerenderEndpoint.js.map +1 -0
- package/dist/helpers/FileCache.js +51 -0
- package/dist/helpers/FileCache.js.map +1 -0
- package/dist/helpers/TTLFileCache.js +83 -0
- package/dist/helpers/TTLFileCache.js.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist-types/boot.d.ts +3 -0
- package/dist-types/boot.d.ts.map +1 -0
- package/dist-types/classes/TrustedIPWhitelist.d.ts +72 -0
- package/dist-types/classes/TrustedIPWhitelist.d.ts.map +1 -0
- package/dist-types/endpoints/HealthEndpoint.d.ts +24 -0
- package/dist-types/endpoints/HealthEndpoint.d.ts.map +1 -0
- package/dist-types/endpoints/HtmlToPdfEndpoint.d.ts +37 -0
- package/dist-types/endpoints/HtmlToPdfEndpoint.d.ts.map +1 -0
- package/dist-types/endpoints/PdfCacheEndpoint.d.ts +28 -0
- package/dist-types/endpoints/PdfCacheEndpoint.d.ts.map +1 -0
- package/dist-types/endpoints/PrerenderEndpoint.d.ts +56 -0
- package/dist-types/endpoints/PrerenderEndpoint.d.ts.map +1 -0
- package/dist-types/helpers/FileCache.d.ts +11 -0
- package/dist-types/helpers/FileCache.d.ts.map +1 -0
- package/dist-types/helpers/TTLFileCache.d.ts +10 -0
- package/dist-types/helpers/TTLFileCache.d.ts.map +1 -0
- package/dist-types/index.d.ts +2 -0
- package/dist-types/index.d.ts.map +1 -0
- package/package.json +69 -56
- package/src/boot.ts +9 -9
- package/src/classes/TrustedIPWhitelist.ts +1 -1
- package/src/endpoints/HealthEndpoint.test.ts +18 -1
- package/src/endpoints/HealthEndpoint.ts +7 -4
- package/src/endpoints/HtmlToPdfEndpoint.test.ts +94 -0
- package/src/endpoints/HtmlToPdfEndpoint.ts +33 -15
- package/src/endpoints/PdfCacheEndpoint.test.ts +46 -0
- package/src/endpoints/PdfCacheEndpoint.ts +23 -5
- package/src/endpoints/PrerenderEndpoint.test.ts +19 -1
- package/src/endpoints/PrerenderEndpoint.ts +10 -9
- package/src/helpers/FileCache.test.ts +27 -0
- package/src/helpers/FileCache.ts +5 -24
- package/src/helpers/TTLFileCache.ts +7 -7
- package/src/index.ts +7 -6
- package/tsconfig.build.json +4 -9
- package/tsconfig.json +1 -1
- package/tsconfig.test.json +2 -4
- package/tsconfig.types.json +7 -0
- package/tests/vitest.global.setup.ts +0 -20
- package/tests/vitest.setup.ts +0 -31
- package/vitest.config.js +0 -20
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import type { DecodedRequest, Request} from '@
|
|
2
|
-
import { Endpoint, Response } from '@
|
|
3
|
-
import { SimpleError } from '@
|
|
1
|
+
import type { DecodedRequest, Request } from '@stamhoofd/node-endpoints';
|
|
2
|
+
import { Endpoint, Response } from '@stamhoofd/node-endpoints';
|
|
3
|
+
import { SimpleError } from '@stamhoofd/common-errors';
|
|
4
4
|
import { verifyInternalSignature } from '@stamhoofd/backend-env';
|
|
5
5
|
import { QueueHandler } from '@stamhoofd/queues';
|
|
6
6
|
import formidable from 'formidable';
|
|
7
7
|
import { firstValues } from 'formidable/src/helpers/firstValues.js';
|
|
8
8
|
import { promises as fs } from 'fs';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
9
11
|
import type { Browser } from 'puppeteer';
|
|
10
12
|
import puppeteer from 'puppeteer';
|
|
11
13
|
|
|
@@ -34,14 +36,23 @@ export class HtmlToPdfEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
34
36
|
return [false];
|
|
35
37
|
}
|
|
36
38
|
|
|
39
|
+
/**
|
|
40
|
+
* Reads multipart HTML into memory and removes the request's upload directory
|
|
41
|
+
* whether parsing succeeds or fails, before signature verification or rendering.
|
|
42
|
+
* Returns PDF bytes after rendering and caching the signed resource version.
|
|
43
|
+
* The html-to-pdf grant binds the HTML bytes, cache ID, version and expiry;
|
|
44
|
+
* expired grants or expiries beyond the next minute are rejected before rendering.
|
|
45
|
+
*/
|
|
37
46
|
async handle(request: DecodedRequest<Params, Query, Body>) {
|
|
47
|
+
const uploadDir = await fs.mkdtemp(join(tmpdir(), 'stamhoofd-renderer-'));
|
|
38
48
|
const form = formidable({
|
|
49
|
+
uploadDir,
|
|
39
50
|
maxTotalFileSize: 20 * 1024 * 1024,
|
|
40
51
|
keepExtensions: false,
|
|
41
52
|
maxFiles: 1,
|
|
42
53
|
});
|
|
43
54
|
|
|
44
|
-
const { html, cacheId, timestamp, signature } = await new Promise<{ html: string; cacheId: string; timestamp: Date; signature: string }>((resolve, reject) => {
|
|
55
|
+
const { html, cacheId, timestamp, signature, expires } = await new Promise<{ html: string; cacheId: string; timestamp: Date; signature: string; expires: string }>((resolve, reject) => {
|
|
45
56
|
if (!request.request.request) {
|
|
46
57
|
reject(new SimpleError({
|
|
47
58
|
code: 'invalid_request',
|
|
@@ -66,6 +77,12 @@ export class HtmlToPdfEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
66
77
|
return;
|
|
67
78
|
}
|
|
68
79
|
const fields = firstValues(form, fieldsMultiple);
|
|
80
|
+
const expires: unknown = fields.expires;
|
|
81
|
+
|
|
82
|
+
if (typeof expires !== 'string' || !/^\d+$/.test(expires)) {
|
|
83
|
+
reject(new SimpleError({ code: 'invalid_signature', message: 'Missing expiration', statusCode: 403 }));
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
69
86
|
|
|
70
87
|
if (!fields.signature || typeof fields.signature !== 'string') {
|
|
71
88
|
reject(new SimpleError({
|
|
@@ -95,8 +112,7 @@ export class HtmlToPdfEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
95
112
|
let html;
|
|
96
113
|
try {
|
|
97
114
|
html = await fs.readFile(files.html[0].filepath, 'utf8');
|
|
98
|
-
}
|
|
99
|
-
catch (e) {
|
|
115
|
+
} catch (e) {
|
|
100
116
|
reject(new SimpleError({
|
|
101
117
|
code: 'invalid_field',
|
|
102
118
|
message: 'Could not read html',
|
|
@@ -107,16 +123,21 @@ export class HtmlToPdfEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
107
123
|
|
|
108
124
|
resolve({
|
|
109
125
|
html,
|
|
126
|
+
expires,
|
|
110
127
|
signature: fields.signature,
|
|
111
128
|
cacheId: fields.cacheId,
|
|
112
129
|
timestamp: new Date(parseInt(fields.timestamp as string)),
|
|
113
130
|
});
|
|
114
131
|
return;
|
|
115
132
|
});
|
|
133
|
+
}).finally(async () => {
|
|
134
|
+
// A private directory also covers partial files omitted from failed parse results.
|
|
135
|
+
await fs.rm(uploadDir, { recursive: true, force: true });
|
|
116
136
|
});
|
|
117
137
|
|
|
118
138
|
// Verify signature first
|
|
119
|
-
if (
|
|
139
|
+
if (Number(expires) <= Date.now() || Number(expires) > Date.now() + 60000
|
|
140
|
+
|| !verifyInternalSignature(signature, 'html-to-pdf', cacheId, timestamp.getTime().toString(), expires, html)) {
|
|
120
141
|
throw new SimpleError({
|
|
121
142
|
code: 'invalid_signature',
|
|
122
143
|
message: 'Invalid signature',
|
|
@@ -126,8 +147,7 @@ export class HtmlToPdfEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
126
147
|
let pdf: Uint8Array | null = null;
|
|
127
148
|
try {
|
|
128
149
|
pdf = await this.htmlToPdf(html, { retryCount: 2, startDate: new Date() });
|
|
129
|
-
}
|
|
130
|
-
catch (e) {
|
|
150
|
+
} catch (e) {
|
|
131
151
|
console.error(e);
|
|
132
152
|
}
|
|
133
153
|
if (!pdf) {
|
|
@@ -138,6 +158,7 @@ export class HtmlToPdfEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
138
158
|
}
|
|
139
159
|
await FileCache.write(cacheId, timestamp, pdf);
|
|
140
160
|
const response = new Response(pdf);
|
|
161
|
+
response.headers['Cache-Control'] = 'no-store';
|
|
141
162
|
response.headers['Content-Type'] = 'application/pdf';
|
|
142
163
|
response.headers['Content-Length'] = pdf.byteLength.toString();
|
|
143
164
|
return response;
|
|
@@ -160,8 +181,7 @@ export class HtmlToPdfEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
160
181
|
if (browser.count > 50 || !browser.browser.connected) {
|
|
161
182
|
try {
|
|
162
183
|
await browser.browser.close();
|
|
163
|
-
}
|
|
164
|
-
catch (e) {
|
|
184
|
+
} catch (e) {
|
|
165
185
|
console.error(e);
|
|
166
186
|
}
|
|
167
187
|
this.browsers[this.nextBrowserIndex] = { browser: await puppeteer.launch({}), count: 0 };
|
|
@@ -174,8 +194,7 @@ export class HtmlToPdfEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
174
194
|
static async clearBrowser(browser: Browser) {
|
|
175
195
|
try {
|
|
176
196
|
await browser.close();
|
|
177
|
-
}
|
|
178
|
-
catch (e) {
|
|
197
|
+
} catch (e) {
|
|
179
198
|
console.error(e);
|
|
180
199
|
}
|
|
181
200
|
const i = this.browsers.findIndex(b => b?.browser === browser);
|
|
@@ -209,8 +228,7 @@ export class HtmlToPdfEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
209
228
|
|
|
210
229
|
console.log('Rendered document pdf');
|
|
211
230
|
return pdf;
|
|
212
|
-
}
|
|
213
|
-
catch (e) {
|
|
231
|
+
} catch (e) {
|
|
214
232
|
console.error('Failed to render document pdf', e);
|
|
215
233
|
return null;
|
|
216
234
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { Request, TestServer } from '@stamhoofd/node-endpoints';
|
|
2
|
+
import { signInternal } from '@stamhoofd/backend-env';
|
|
3
|
+
import { FileCache } from '../helpers/FileCache.js';
|
|
4
|
+
import { PdfCacheEndpoint } from './PdfCacheEndpoint.js';
|
|
5
|
+
|
|
6
|
+
/** Exercises request decoding and signature verification with cache I/O stubbed. */
|
|
7
|
+
describe('PDF cache authorization', () => {
|
|
8
|
+
const endpoint = new PdfCacheEndpoint();
|
|
9
|
+
const server = new TestServer();
|
|
10
|
+
const cacheId = 'document-123';
|
|
11
|
+
const timestamp = 2000;
|
|
12
|
+
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
vi.spyOn(FileCache, 'read').mockResolvedValue(Buffer.from('PDF'));
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
afterEach(() => vi.restoreAllMocks());
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A grant authorizes only its signed cache ID and exact version while unexpired.
|
|
21
|
+
* Mutating request fields after signing must fail without accessing cached bytes;
|
|
22
|
+
* missing fields must also be rejected by request decoding.
|
|
23
|
+
*/
|
|
24
|
+
test.each(['missing', 'expired', 'changed version', 'changed ID', 'invalid signature'])('rejects %s authorization before reading the cache', async (mode) => {
|
|
25
|
+
const expires = Date.now() + (mode === 'expired' ? -1000 : 60000);
|
|
26
|
+
const signature = signInternal('pdf-cache', cacheId, String(timestamp), String(expires));
|
|
27
|
+
const query = {
|
|
28
|
+
cacheId: mode === 'changed ID' ? 'invoice-123' : cacheId,
|
|
29
|
+
timestamp: mode === 'changed version' ? timestamp + 1 : timestamp,
|
|
30
|
+
...(mode === 'missing' ? {} : { expires, signature: mode === 'invalid signature' ? 'invalid' : signature }),
|
|
31
|
+
};
|
|
32
|
+
await expect(server.test(endpoint, Request.get({ path: '/pdf-cache', query }))).rejects.toThrow();
|
|
33
|
+
expect(FileCache.read).not.toHaveBeenCalled();
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
/** Valid grants work for both cache namespaces and pass the signed version to storage unchanged. */
|
|
37
|
+
test.each(['document-123', 'invoice-123'])('returns an authorized exact version of %s', async (cacheId) => {
|
|
38
|
+
const expires = Date.now() + 60000;
|
|
39
|
+
const signature = signInternal('pdf-cache', cacheId, String(timestamp), String(expires));
|
|
40
|
+
const response = await server.test(endpoint, Request.get({
|
|
41
|
+
path: '/pdf-cache', query: { cacheId, timestamp, expires, signature },
|
|
42
|
+
}));
|
|
43
|
+
expect(response.body).toEqual(Buffer.from('PDF'));
|
|
44
|
+
expect(FileCache.read).toHaveBeenCalledWith(cacheId, new Date(timestamp));
|
|
45
|
+
});
|
|
46
|
+
});
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import type { Decoder} from '@
|
|
2
|
-
import { AutoEncoder, DateDecoder, field, StringDecoder } from '@
|
|
3
|
-
import type { DecodedRequest, Request} from '@
|
|
4
|
-
import { Endpoint, Response } from '@
|
|
5
|
-
import { SimpleError } from '@
|
|
1
|
+
import type { Decoder } from '@stamhoofd/common-encoding';
|
|
2
|
+
import { AutoEncoder, DateDecoder, field, StringDecoder } from '@stamhoofd/common-encoding';
|
|
3
|
+
import type { DecodedRequest, Request } from '@stamhoofd/node-endpoints';
|
|
4
|
+
import { Endpoint, Response } from '@stamhoofd/node-endpoints';
|
|
5
|
+
import { SimpleError } from '@stamhoofd/common-errors';
|
|
6
|
+
import { verifyInternalSignature } from '@stamhoofd/backend-env';
|
|
6
7
|
|
|
7
8
|
import { FileCache } from '../helpers/FileCache.js';
|
|
8
9
|
|
|
@@ -13,6 +14,12 @@ class Query extends AutoEncoder {
|
|
|
13
14
|
|
|
14
15
|
@field({ decoder: DateDecoder })
|
|
15
16
|
timestamp: Date;
|
|
17
|
+
|
|
18
|
+
@field({ decoder: DateDecoder })
|
|
19
|
+
expires: Date;
|
|
20
|
+
|
|
21
|
+
@field({ decoder: StringDecoder })
|
|
22
|
+
signature: string;
|
|
16
23
|
}
|
|
17
24
|
type Body = undefined;
|
|
18
25
|
type ResponseBody = Buffer;
|
|
@@ -37,7 +44,17 @@ export class PdfCacheEndpoint extends Endpoint<Params, Query, Body, ResponseBody
|
|
|
37
44
|
return [false];
|
|
38
45
|
}
|
|
39
46
|
|
|
47
|
+
/**
|
|
48
|
+
* Returns cached PDF bytes only for the ID and exact version in a valid cache-read
|
|
49
|
+
* grant. Expiry must be in the next minute; verification precedes all cache I/O.
|
|
50
|
+
* A valid grant with no readable version produces cache_not_found.
|
|
51
|
+
*/
|
|
40
52
|
async handle(request: DecodedRequest<Params, Query, Body>) {
|
|
53
|
+
const { cacheId, timestamp, expires, signature } = request.query;
|
|
54
|
+
if (expires.getTime() <= Date.now() || expires.getTime() > Date.now() + 60000
|
|
55
|
+
|| !verifyInternalSignature(signature, 'pdf-cache', cacheId, String(timestamp.getTime()), String(expires.getTime()))) {
|
|
56
|
+
throw new SimpleError({ code: 'invalid_signature', message: 'Invalid signature', statusCode: 403 });
|
|
57
|
+
}
|
|
41
58
|
const pdf = await FileCache.read(request.query.cacheId, request.query.timestamp);
|
|
42
59
|
if (!pdf) {
|
|
43
60
|
throw new SimpleError({
|
|
@@ -47,6 +64,7 @@ export class PdfCacheEndpoint extends Endpoint<Params, Query, Body, ResponseBody
|
|
|
47
64
|
});
|
|
48
65
|
}
|
|
49
66
|
const response = new Response(pdf);
|
|
67
|
+
response.headers['Cache-Control'] = 'no-store';
|
|
50
68
|
response.headers['Content-Type'] = 'application/pdf';
|
|
51
69
|
response.headers['Content-Length'] = pdf.byteLength.toString();
|
|
52
70
|
return response;
|
|
@@ -1,10 +1,28 @@
|
|
|
1
|
-
import { Request, TestServer } from '@
|
|
1
|
+
import { Request, TestServer } from '@stamhoofd/node-endpoints';
|
|
2
2
|
import { PrerenderEndpoint } from './PrerenderEndpoint.js';
|
|
3
3
|
import nock from 'nock';
|
|
4
4
|
import { STExpect, TestUtils } from '@stamhoofd/test-utils';
|
|
5
5
|
import fs from 'fs/promises';
|
|
6
6
|
import { TrustedIPWhitelist } from '../classes/TrustedIPWhitelist.js';
|
|
7
7
|
|
|
8
|
+
describe('cleanHeaders dictionary isolation', () => {
|
|
9
|
+
test('preserves special response header names without mutating the result prototype', () => {
|
|
10
|
+
const input = JSON.parse('{"__proto__":"first","constructor":"second","prototype":"third"}');
|
|
11
|
+
const output = PrerenderEndpoint.cleanHeaders(input);
|
|
12
|
+
expect(Object.getPrototypeOf(output)).toBe(Object.prototype);
|
|
13
|
+
expect(Object.getOwnPropertyDescriptor(output, '__proto__')?.value).toBe('first');
|
|
14
|
+
expect(output).toEqual(input);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('rejects structured values instead of treating them as header prototype state', () => {
|
|
18
|
+
const input = JSON.parse('{"__proto__":{"location":"https://untrusted.example"}}');
|
|
19
|
+
const output = PrerenderEndpoint.cleanHeaders(input);
|
|
20
|
+
expect(Object.getPrototypeOf(output)).toBe(Object.prototype);
|
|
21
|
+
expect(output).toEqual({});
|
|
22
|
+
expect(output.location).toBeUndefined();
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
8
26
|
async function fileExists(path: string): Promise<boolean> {
|
|
9
27
|
try {
|
|
10
28
|
await fs.access(path, fs.constants.F_OK);
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import type { DecodedRequest, Request } from '@
|
|
2
|
-
import { Endpoint, Response } from '@
|
|
3
|
-
import { SimpleError } from '@
|
|
1
|
+
import type { DecodedRequest, Request } from '@stamhoofd/node-endpoints';
|
|
2
|
+
import { Endpoint, Response } from '@stamhoofd/node-endpoints';
|
|
3
|
+
import { SimpleError } from '@stamhoofd/common-errors';
|
|
4
4
|
|
|
5
|
-
import type { Decoder } from '@
|
|
6
|
-
import { AutoEncoder, field, URLDecoder } from '@
|
|
5
|
+
import type { Decoder } from '@stamhoofd/common-encoding';
|
|
6
|
+
import { AutoEncoder, field, URLDecoder } from '@stamhoofd/common-encoding';
|
|
7
7
|
import { TrustedIPWhitelist } from '../classes/TrustedIPWhitelist.js';
|
|
8
8
|
import { TTLFileCache } from '../helpers/TTLFileCache.js';
|
|
9
9
|
import { HtmlToPdfEndpoint } from './HtmlToPdfEndpoint.js';
|
|
@@ -155,11 +155,12 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
155
155
|
return parsed.href;
|
|
156
156
|
}
|
|
157
157
|
|
|
158
|
+
/** Normalizes literal header keys in a Map, returning the object required by the HTTP boundary. */
|
|
158
159
|
static cleanHeaders(headers: Record<string, string | undefined>): Record<string, string> {
|
|
159
|
-
const cleanedHeaders
|
|
160
|
+
const cleanedHeaders = new Map<string, string>();
|
|
160
161
|
for (const key of Object.keys(headers)) {
|
|
161
162
|
const rawValue = headers[key];
|
|
162
|
-
if (!rawValue) {
|
|
163
|
+
if (typeof rawValue !== 'string' || !rawValue) {
|
|
163
164
|
continue;
|
|
164
165
|
}
|
|
165
166
|
const l = key.toLowerCase();
|
|
@@ -169,9 +170,9 @@ export class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBod
|
|
|
169
170
|
if (/[\r\n]/.test(rawValue)) {
|
|
170
171
|
continue;
|
|
171
172
|
}
|
|
172
|
-
cleanedHeaders
|
|
173
|
+
cleanedHeaders.set(l, rawValue);
|
|
173
174
|
}
|
|
174
|
-
return cleanedHeaders;
|
|
175
|
+
return Object.fromEntries(cleanedHeaders);
|
|
175
176
|
}
|
|
176
177
|
|
|
177
178
|
static async getUrlHtml(url: string, options: { retryCount: number; startDate: Date }): Promise<Data | null> {
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { promises as fs } from 'node:fs';
|
|
3
|
+
import { FileCache } from './FileCache.js';
|
|
4
|
+
|
|
5
|
+
/** Exercises on-disk version selection without sharing cache entries with other tests. */
|
|
6
|
+
describe('FileCache exact versions', () => {
|
|
7
|
+
const cacheId = `document-${randomUUID()}`;
|
|
8
|
+
|
|
9
|
+
afterEach(async () => {
|
|
10
|
+
await fs.rm(`${STAMHOOFD.CACHE_PATH}/${cacheId}`, { recursive: true, force: true });
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
/** An existing later timestamp is a cache miss, not a substitute for the requested document. */
|
|
14
|
+
test('does not return a newer document for an older version', async () => {
|
|
15
|
+
await FileCache.write(cacheId, new Date(2000), Buffer.from('newer document'));
|
|
16
|
+
|
|
17
|
+
expect(await FileCache.read(cacheId, new Date(1000))).toBeNull();
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
/** Positive control: matching timestamps return the stored PDF bytes unchanged. */
|
|
21
|
+
test('returns the exact requested version', async () => {
|
|
22
|
+
const pdf = Buffer.from('requested document');
|
|
23
|
+
await FileCache.write(cacheId, new Date(2000), pdf);
|
|
24
|
+
|
|
25
|
+
expect(await FileCache.read(cacheId, new Date(2000))).toEqual(pdf);
|
|
26
|
+
});
|
|
27
|
+
});
|
package/src/helpers/FileCache.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { SimpleError } from '@
|
|
1
|
+
import { SimpleError } from '@stamhoofd/common-errors';
|
|
2
2
|
import { promises as fs } from 'fs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* This cache does not use a TTL.
|
|
5
|
+
* This cache does not use a TTL.
|
|
6
6
|
* Instead it uses the updatedAt timestamp of a resource when caching. So we keep the cache forever unless the resource itself has changed.
|
|
7
|
-
*
|
|
7
|
+
* Reads only return the exact requested updatedAt timestamp, never a later version.
|
|
8
8
|
*/
|
|
9
9
|
export class FileCache {
|
|
10
10
|
static async write(cacheId: string, timestamp: Date, data: Uint8Array | Buffer) {
|
|
@@ -32,6 +32,7 @@ export class FileCache {
|
|
|
32
32
|
await fs.writeFile(path, data);
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
/** Returns bytes for this exact resource version, or null when its file cannot be read. */
|
|
35
36
|
static async read(cacheId: string, timestamp: Date): Promise<Buffer | null> {
|
|
36
37
|
if (cacheId.includes('/')) {
|
|
37
38
|
throw new SimpleError({
|
|
@@ -46,27 +47,7 @@ export class FileCache {
|
|
|
46
47
|
try {
|
|
47
48
|
const data = await fs.readFile(path);
|
|
48
49
|
return data;
|
|
49
|
-
}
|
|
50
|
-
catch {
|
|
51
|
-
// ignore
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
try {
|
|
55
|
-
const files = await fs.readdir(folder);
|
|
56
|
-
for (const file of files) {
|
|
57
|
-
const fileTimestamp = parseInt(file.substring(0, file.length - 4));
|
|
58
|
-
if (fileTimestamp >= timestamp.getTime()) {
|
|
59
|
-
try {
|
|
60
|
-
const data = await fs.readFile(folder + '/' + file);
|
|
61
|
-
return data;
|
|
62
|
-
}
|
|
63
|
-
catch {
|
|
64
|
-
// ignore
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
catch {
|
|
50
|
+
} catch {
|
|
70
51
|
// ignore
|
|
71
52
|
}
|
|
72
53
|
|
|
@@ -7,15 +7,15 @@ export class TTLFileCache {
|
|
|
7
7
|
|
|
8
8
|
constructor(name: string, ttl: number) {
|
|
9
9
|
if (!STAMHOOFD.CACHE_PATH) {
|
|
10
|
-
throw new Error('Missing STAMHOOFD.CACHE_PATH')
|
|
10
|
+
throw new Error('Missing STAMHOOFD.CACHE_PATH');
|
|
11
11
|
}
|
|
12
|
-
this.cachePath = STAMHOOFD.CACHE_PATH + '/' + Formatter.slug(name)
|
|
12
|
+
this.cachePath = STAMHOOFD.CACHE_PATH + '/' + Formatter.slug(name);
|
|
13
13
|
|
|
14
14
|
// Clear on boot
|
|
15
|
-
this.clear().catch(console.error)
|
|
15
|
+
this.clear().catch(console.error);
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
keyToFilePath(key: string): string {
|
|
19
19
|
// Percent-encode every character that isn't safe in a filename.
|
|
20
20
|
// Using encoding rather than replacement ensures the mapping is
|
|
21
21
|
// injective: no two distinct keys ever produce the same filename.
|
|
@@ -28,7 +28,6 @@ export class TTLFileCache {
|
|
|
28
28
|
return path.join(this.cachePath, safeKey);
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
|
|
32
31
|
async cacheFile(key: string, contents: string): Promise<void> {
|
|
33
32
|
await fs.mkdir(this.cachePath, { recursive: true });
|
|
34
33
|
await fs.writeFile(this.keyToFilePath(key), contents, 'utf-8');
|
|
@@ -54,7 +53,7 @@ export class TTLFileCache {
|
|
|
54
53
|
|
|
55
54
|
async clear() {
|
|
56
55
|
try {
|
|
57
|
-
await fs.rm(this.cachePath, {recursive: true})
|
|
56
|
+
await fs.rm(this.cachePath, { recursive: true });
|
|
58
57
|
} catch (e) {
|
|
59
58
|
// ignore
|
|
60
59
|
}
|
|
@@ -80,12 +79,13 @@ export class TTLFileCache {
|
|
|
80
79
|
try {
|
|
81
80
|
const stat = await fs.stat(filePath);
|
|
82
81
|
if (stat.isFile() && stat.mtimeMs < cutoff) {
|
|
82
|
+
// eslint-disable-next-line node-security/no-toctou-vulnerability -- The stat only selects expired cache entries, not access permissions; unlink does not follow symlinks and concurrent deletion is caught below.
|
|
83
83
|
await fs.unlink(filePath);
|
|
84
84
|
}
|
|
85
85
|
} catch {
|
|
86
86
|
// File may have been deleted concurrently — ignore
|
|
87
87
|
}
|
|
88
|
-
})
|
|
88
|
+
}),
|
|
89
89
|
);
|
|
90
90
|
}
|
|
91
91
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import backendEnv from '@stamhoofd/backend-env';
|
|
2
|
+
import { BackendApp } from '@stamhoofd/types/BackendApp';
|
|
3
|
+
import { runApplication } from '@stamhoofd/node-observability';
|
|
2
4
|
|
|
3
5
|
process.title = 'stamhoofd-renderer';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
await import('./boot.js');
|
|
6
|
+
runApplication('renderer', async (lifecycle) => {
|
|
7
|
+
await backendEnv.load({ service: BackendApp.Renderer });
|
|
8
|
+
const { boot } = await import('./boot.js');
|
|
9
|
+
await boot(lifecycle);
|
|
9
10
|
}).catch((error) => {
|
|
10
|
-
console.error('Failed to start the
|
|
11
|
+
console.error('Failed to start the renderer:', error);
|
|
11
12
|
process.exit(1);
|
|
12
13
|
});
|
package/tsconfig.build.json
CHANGED
|
@@ -1,15 +1,10 @@
|
|
|
1
1
|
{
|
|
2
|
-
"extends": "../../../tsconfig.base.json",
|
|
2
|
+
"extends": ["../../../tsconfig.base.json", "../../../tsconfig.runtime.json"],
|
|
3
3
|
"compilerOptions": {
|
|
4
|
+
"tsBuildInfoFile": ".cache/build.tsbuildinfo",
|
|
4
5
|
"rootDir": "./src",
|
|
5
6
|
"outDir": "dist"
|
|
6
7
|
},
|
|
7
|
-
"include": [
|
|
8
|
-
|
|
9
|
-
"./stamhoofd.d.ts"
|
|
10
|
-
],
|
|
11
|
-
"exclude": [
|
|
12
|
-
"./src/**/*.spec.ts",
|
|
13
|
-
"./src/**/*.test.ts"
|
|
14
|
-
]
|
|
8
|
+
"include": ["./src", "./stamhoofd.d.ts"],
|
|
9
|
+
"exclude": ["./src/**/*.spec.ts", "./src/**/*.test.ts"]
|
|
15
10
|
}
|
package/tsconfig.json
CHANGED
package/tsconfig.test.json
CHANGED
|
@@ -5,13 +5,11 @@
|
|
|
5
5
|
"outDir": "dist",
|
|
6
6
|
"noEmit": true
|
|
7
7
|
},
|
|
8
|
-
"references": [
|
|
9
|
-
{ "path": "./tsconfig.build.json" }
|
|
10
|
-
],
|
|
8
|
+
"references": [{ "path": "./tsconfig.types.json" }],
|
|
11
9
|
"include": [
|
|
12
10
|
"./stamhoofd.d.ts",
|
|
13
11
|
"../../../jest-extended.d.ts",
|
|
14
|
-
"./src/**/*.spec.ts",
|
|
12
|
+
"./src/**/*.spec.ts",
|
|
15
13
|
"./src/**/*.test.ts",
|
|
16
14
|
"./tests"
|
|
17
15
|
]
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
// first import nock
|
|
2
|
-
import nock from 'nock';
|
|
3
|
-
|
|
4
|
-
// prevent nock import from being removed on save
|
|
5
|
-
console.log('Imported nock: ', !!nock);
|
|
6
|
-
|
|
7
|
-
import { TestUtils } from '@stamhoofd/test-utils';
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
// Set timezone!
|
|
11
|
-
process.env.TZ = 'UTC';
|
|
12
|
-
|
|
13
|
-
// Quick check
|
|
14
|
-
if (new Date().getTimezoneOffset() !== 0) {
|
|
15
|
-
throw new Error('Process should always run in UTC timezone');
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export async function setup() {
|
|
19
|
-
TestUtils.globalSetup();
|
|
20
|
-
};
|
package/tests/vitest.setup.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
// first import nock
|
|
2
|
-
|
|
3
|
-
import { Column } from '@simonbackx/simple-database';
|
|
4
|
-
import { Request } from '@simonbackx/simple-endpoints';
|
|
5
|
-
import { Version } from '@stamhoofd/structures';
|
|
6
|
-
import { TestUtils } from '@stamhoofd/test-utils';
|
|
7
|
-
|
|
8
|
-
Error.stackTraceLimit = 100;
|
|
9
|
-
|
|
10
|
-
// Set version of saved structures
|
|
11
|
-
Column.setJSONVersion(Version);
|
|
12
|
-
|
|
13
|
-
// Automatically set endpoint default version to latest one (only in tests!)
|
|
14
|
-
Request.defaultVersion = Version;
|
|
15
|
-
|
|
16
|
-
// Set timezone!
|
|
17
|
-
process.env.TZ = 'UTC';
|
|
18
|
-
|
|
19
|
-
// Quick check
|
|
20
|
-
if (new Date().getTimezoneOffset() !== 0) {
|
|
21
|
-
throw new Error('Process should always run in UTC timezone');
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
console.log = () => {};
|
|
25
|
-
|
|
26
|
-
beforeAll(async () => {
|
|
27
|
-
// Override default $t handlers
|
|
28
|
-
TestUtils.loadEnvironment();
|
|
29
|
-
});
|
|
30
|
-
TestUtils.setPermanentEnvironment('CACHE_PATH', import.meta.dirname + '/../.test-cache')
|
|
31
|
-
TestUtils.setup();
|
package/vitest.config.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { defineConfig } from 'vitest/config';
|
|
2
|
-
|
|
3
|
-
export default defineConfig({
|
|
4
|
-
test: {
|
|
5
|
-
include: ['**/*.test.ts'], // only match TypeScript sources, so compiled copies in dist are never picked up
|
|
6
|
-
globalSetup: './tests/vitest.global.setup.ts',
|
|
7
|
-
setupFiles: ['./tests/vitest.setup.ts'],
|
|
8
|
-
watch: false,
|
|
9
|
-
testTimeout: 30_000, // launching Chrome and prerendering a live page is slow on CI
|
|
10
|
-
globals: true,
|
|
11
|
-
root: import.meta.dirname,
|
|
12
|
-
isolate: true,
|
|
13
|
-
maxWorkers: 1, // For now we can't run parallel because all test files use the same database
|
|
14
|
-
coverage: {
|
|
15
|
-
provider: 'v8',
|
|
16
|
-
include: ['src/**'],
|
|
17
|
-
reporter: ['text', 'html', 'lcov'],
|
|
18
|
-
},
|
|
19
|
-
},
|
|
20
|
-
});
|