@stamhoofd/backend-renderer 2.153.0 → 2.161.1

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.
Files changed (61) hide show
  1. package/LICENSE.md +7 -7
  2. package/README.md +11 -1
  3. package/dist/boot.js +83 -0
  4. package/dist/boot.js.map +1 -0
  5. package/dist/classes/TrustedIPWhitelist.js +204 -0
  6. package/dist/classes/TrustedIPWhitelist.js.map +1 -0
  7. package/dist/endpoints/HealthEndpoint.js +76 -0
  8. package/dist/endpoints/HealthEndpoint.js.map +1 -0
  9. package/dist/endpoints/HtmlToPdfEndpoint.js +220 -0
  10. package/dist/endpoints/HtmlToPdfEndpoint.js.map +1 -0
  11. package/dist/endpoints/PdfCacheEndpoint.js +66 -0
  12. package/dist/endpoints/PdfCacheEndpoint.js.map +1 -0
  13. package/dist/endpoints/PrerenderEndpoint.js +276 -0
  14. package/dist/endpoints/PrerenderEndpoint.js.map +1 -0
  15. package/dist/helpers/FileCache.js +51 -0
  16. package/dist/helpers/FileCache.js.map +1 -0
  17. package/dist/helpers/TTLFileCache.js +83 -0
  18. package/dist/helpers/TTLFileCache.js.map +1 -0
  19. package/dist/index.js +7 -6
  20. package/dist/index.js.map +1 -0
  21. package/dist-types/boot.d.ts +3 -0
  22. package/dist-types/boot.d.ts.map +1 -0
  23. package/dist-types/classes/TrustedIPWhitelist.d.ts +72 -0
  24. package/dist-types/classes/TrustedIPWhitelist.d.ts.map +1 -0
  25. package/dist-types/endpoints/HealthEndpoint.d.ts +24 -0
  26. package/dist-types/endpoints/HealthEndpoint.d.ts.map +1 -0
  27. package/dist-types/endpoints/HtmlToPdfEndpoint.d.ts +37 -0
  28. package/dist-types/endpoints/HtmlToPdfEndpoint.d.ts.map +1 -0
  29. package/dist-types/endpoints/PdfCacheEndpoint.d.ts +28 -0
  30. package/dist-types/endpoints/PdfCacheEndpoint.d.ts.map +1 -0
  31. package/dist-types/endpoints/PrerenderEndpoint.d.ts +56 -0
  32. package/dist-types/endpoints/PrerenderEndpoint.d.ts.map +1 -0
  33. package/dist-types/helpers/FileCache.d.ts +11 -0
  34. package/dist-types/helpers/FileCache.d.ts.map +1 -0
  35. package/dist-types/helpers/TTLFileCache.d.ts +10 -0
  36. package/dist-types/helpers/TTLFileCache.d.ts.map +1 -0
  37. package/dist-types/index.d.ts +2 -0
  38. package/dist-types/index.d.ts.map +1 -0
  39. package/package.json +40 -26
  40. package/src/boot.ts +6 -8
  41. package/src/classes/TrustedIPWhitelist.ts +1 -1
  42. package/src/endpoints/HealthEndpoint.test.ts +1 -1
  43. package/src/endpoints/HealthEndpoint.ts +4 -4
  44. package/src/endpoints/HtmlToPdfEndpoint.test.ts +94 -0
  45. package/src/endpoints/HtmlToPdfEndpoint.ts +33 -15
  46. package/src/endpoints/PdfCacheEndpoint.test.ts +46 -0
  47. package/src/endpoints/PdfCacheEndpoint.ts +23 -5
  48. package/src/endpoints/PrerenderEndpoint.test.ts +19 -1
  49. package/src/endpoints/PrerenderEndpoint.ts +10 -9
  50. package/src/helpers/FileCache.test.ts +27 -0
  51. package/src/helpers/FileCache.ts +5 -24
  52. package/src/helpers/TTLFileCache.ts +7 -7
  53. package/src/index.ts +7 -6
  54. package/tsconfig.build.json +4 -9
  55. package/tsconfig.json +1 -1
  56. package/tsconfig.test.json +2 -4
  57. package/tsconfig.types.json +7 -0
  58. package/.gitignore +0 -223
  59. package/tests/vitest.global.setup.ts +0 -20
  60. package/tests/vitest.setup.ts +0 -31
  61. package/vitest.config.js +0 -20
@@ -0,0 +1,24 @@
1
+ import { AutoEncoder } from '@stamhoofd/common-encoding';
2
+ import type { DecodedRequest, Request } from '@stamhoofd/node-endpoints';
3
+ import { Endpoint, Response } from '@stamhoofd/node-endpoints';
4
+ type Params = Record<string, never>;
5
+ type Body = undefined;
6
+ declare class Query extends AutoEncoder {
7
+ key?: string;
8
+ }
9
+ export declare class ResponseBody extends AutoEncoder {
10
+ status: 'ok' | 'error';
11
+ errors?: string[];
12
+ }
13
+ /**
14
+ * Liveness/health endpoint for the renderer service. Guarded by an optional access key so it can be
15
+ * polled by load balancers and monitoring without exposing anything sensitive. The endpoint is only
16
+ * registered when a HEALTH_ACCESS_KEY is configured.
17
+ */
18
+ export declare class HealthEndpoint extends Endpoint<Params, Query, Body, ResponseBody> {
19
+ queryDecoder: typeof Query;
20
+ protected doesMatch(request: Request): [true, Params] | [false];
21
+ handle(request: DecodedRequest<Params, Query, Body>): Promise<Response<ResponseBody>>;
22
+ }
23
+ export {};
24
+ //# sourceMappingURL=HealthEndpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HealthEndpoint.d.ts","sourceRoot":"","sources":["../../src/endpoints/HealthEndpoint.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,WAAW,EAAwB,MAAM,4BAA4B,CAAC;AAC7F,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAK/D,KAAK,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AACpC,KAAK,IAAI,GAAG,SAAS,CAAC;AAEtB,cAAM,KAAM,SAAQ,WAAW;IAE3B,GAAG,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,qBAAa,YAAa,SAAQ,WAAW;IAEzC,MAAM,EAAE,IAAI,GAAG,OAAO,CAAC;IAGvB,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAED;;;;GAIG;AAEH,qBAAa,cAAe,SAAQ,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,CAAC;IAC3E,YAAY,eAAS;IAErB,SAAS,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC;IAiBzD,MAAM,CAAC,OAAO,EAAE,cAAc,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC;CAyC5D"}
@@ -0,0 +1,37 @@
1
+ import type { DecodedRequest, Request } from '@stamhoofd/node-endpoints';
2
+ import { Endpoint, Response } from '@stamhoofd/node-endpoints';
3
+ import type { Browser } from 'puppeteer';
4
+ type Params = Record<string, never>;
5
+ type Body = undefined;
6
+ type Query = undefined;
7
+ type ResponseBody = Uint8Array;
8
+ /**
9
+ * One endpoint to create, patch and delete groups. Usefull because on organization setup, we need to create multiple groups at once. Also, sometimes we need to link values and update multiple groups at once
10
+ */
11
+ export declare class HtmlToPdfEndpoint extends Endpoint<Params, Query, Body, ResponseBody> {
12
+ protected doesMatch(request: Request): [true, Params] | [false];
13
+ /**
14
+ * Reads multipart HTML into memory and removes the request's upload directory
15
+ * whether parsing succeeds or fails, before signature verification or rendering.
16
+ * Returns PDF bytes after rendering and caching the signed resource version.
17
+ * The html-to-pdf grant binds the HTML bytes, cache ID, version and expiry;
18
+ * expired grants or expiries beyond the next minute are rejected before rendering.
19
+ */
20
+ handle(request: DecodedRequest<Params, Query, Body>): Promise<Response<Uint8Array<ArrayBufferLike>>>;
21
+ static browsers: ({
22
+ browser: Browser;
23
+ count: number;
24
+ } | null)[];
25
+ static nextBrowserIndex: number;
26
+ static useBrowser<T>(callback: (browser: Browser) => Promise<T>): Promise<T>;
27
+ static clearBrowser(browser: Browser): Promise<void>;
28
+ /**
29
+ * This will move to a different external service
30
+ */
31
+ htmlToPdf(html: string, options: {
32
+ retryCount: number;
33
+ startDate: Date;
34
+ }): Promise<Uint8Array | null>;
35
+ }
36
+ export {};
37
+ //# sourceMappingURL=HtmlToPdfEndpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HtmlToPdfEndpoint.d.ts","sourceRoot":"","sources":["../../src/endpoints/HtmlToPdfEndpoint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,QA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d/node-endpoints';
4
+ import { Endpoint, Response } from '@stamhoofd/node-endpoints';
5
+ type Params = Record<string, never>;
6
+ declare class Query extends AutoEncoder {
7
+ cacheId: string;
8
+ timestamp: Date;
9
+ expires: Date;
10
+ signature: string;
11
+ }
12
+ type Body = undefined;
13
+ type ResponseBody = Buffer;
14
+ /**
15
+ * One endpoint to create, patch and delete groups. Usefull because on organization setup, we need to create multiple groups at once. Also, sometimes we need to link values and update multiple groups at once
16
+ */
17
+ export declare class PdfCacheEndpoint extends Endpoint<Params, Query, Body, ResponseBody> {
18
+ queryDecoder: Decoder<Query>;
19
+ protected doesMatch(request: Request): [true, Params] | [false];
20
+ /**
21
+ * Returns cached PDF bytes only for the ID and exact version in a valid cache-read
22
+ * grant. Expiry must be in the next minute; verification precedes all cache I/O.
23
+ * A valid grant with no readable version produces cache_not_found.
24
+ */
25
+ handle(request: DecodedRequest<Params, Query, Body>): Promise<Response<Buffer<ArrayBufferLike>>>;
26
+ }
27
+ export {};
28
+ //# sourceMappingURL=PdfCacheEndpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PdfCacheEndpoint.d.ts","sourceRoot":"","sources":["../../src/endpoints/PdfCacheEndpoint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAqC,MAAM,4BAA4B,CAAC;AAC5F,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAM/D,KAAK,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AACpC,cAAM,KAAM,SAAQ,WAAW;IAE3B,OAAO,EAAE,MAAM,CAAC;IAGhB,SAAS,EAAE,IAAI,CAAC;IAGhB,OAAO,EAAE,IAAI,CAAC;IAGd,SAAS,EAAE,MAAM,CAAC;CACrB;AACD,KAAK,IAAI,GAAG,SAAS,CAAC;AACtB,KAAK,YAAY,GAAG,MAAM,CAAC;AAE3B;;GAEG;AAEH,qBAAa,gBAAiB,SAAQ,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,CAAC;IAC7E,YAAY,EAAY,OAAO,CAAC,KAAK,CAAC,CAAC;IAEvC,SAAS,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC;IAa/D;;;;OAIG;IACG,MAAM,CAAC,OAAO,EAAE,cAAc,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC;CAoB5D"}
@@ -0,0 +1,56 @@
1
+ import type { DecodedRequest, Request } from '@stamhoofd/node-endpoints';
2
+ import { Endpoint, Response } from '@stamhoofd/node-endpoints';
3
+ import type { Decoder } from '@stamhoofd/common-encoding';
4
+ import { AutoEncoder } from '@stamhoofd/common-encoding';
5
+ import { TTLFileCache } from '../helpers/TTLFileCache.js';
6
+ type Params = Record<string, never>;
7
+ type Body = undefined;
8
+ declare class Query extends AutoEncoder {
9
+ url: URL;
10
+ }
11
+ type Data = {
12
+ html: string;
13
+ headers: Record<string, string>;
14
+ statusCode: number;
15
+ };
16
+ type ResponseBody = string;
17
+ /**
18
+ * One endpoint to create, patch and delete groups. Usefull because on organization setup, we need to create multiple groups at once. Also, sometimes we need to link values and update multiple groups at once
19
+ */
20
+ export declare class PrerenderEndpoint extends Endpoint<Params, Query, Body, ResponseBody> {
21
+ queryDecoder: Decoder<Query>;
22
+ protected doesMatch(request: Request): [true, Params] | [false];
23
+ handle(request: DecodedRequest<Params, Query, Body>): Promise<Response<string>>;
24
+ static readonly CACHE_TTL_MS: number;
25
+ static fileCache: TTLFileCache;
26
+ /**
27
+ * Response headers we never copy from the prerendered page onto our own response
28
+ */
29
+ static readonly SKIPPED_HEADERS: Set<string>;
30
+ /**
31
+ * Query parameters used purely for click/campaign tracking. They never influence the
32
+ * rendered page, so we drop them before requesting and caching the prerender. This keeps
33
+ * the cache from fragmenting into near-identical entries (one per ?fbclid, ?gclid, ...).
34
+ */
35
+ static readonly TRACKING_QUERY_PARAMS: Set<string>;
36
+ /**
37
+ * Any query parameter whose name starts with one of these prefixes is treated as tracking
38
+ * (e.g. utm_source, utm_medium, pk_campaign, mtm_kwd).
39
+ */
40
+ static readonly TRACKING_QUERY_PREFIXES: string[];
41
+ static isTrackingParam(key: string): boolean;
42
+ /**
43
+ * Remove tracking query parameters from a URL. Returns the original string untouched when it
44
+ * isn't a valid absolute URL or when there is nothing to strip (so the common case keeps its
45
+ * exact formatting).
46
+ */
47
+ static stripTrackingParams(rawUrl: string): string;
48
+ /** Normalizes literal header keys in a Map, returning the object required by the HTTP boundary. */
49
+ static cleanHeaders(headers: Record<string, string | undefined>): Record<string, string>;
50
+ static getUrlHtml(url: string, options: {
51
+ retryCount: number;
52
+ startDate: Date;
53
+ }): Promise<Data | null>;
54
+ }
55
+ export {};
56
+ //# sourceMappingURL=PrerenderEndpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PrerenderEndpoint.d.ts","sourceRoot":"","sources":["../../src/endpoints/PrerenderEndpoint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAG/D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAqB,MAAM,4BAA4B,CAAC;AAE5E,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAG1D,KAAK,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AACpC,KAAK,IAAI,GAAG,SAAS,CAAC;AACtB,cAAM,KAAM,SAAQ,WAAW;IAE3B,GAAG,EAA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O,CAAC,IAAI,GAAG,IAAI,CAAC;CA4I/G"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * This cache does not use a TTL.
3
+ * Instead it uses the updatedAt timestamp of a resource when caching. So we keep the cache forever unless the resource itself has changed.
4
+ * Reads only return the exact requested updatedAt timestamp, never a later version.
5
+ */
6
+ export declare class FileCache {
7
+ static write(cacheId: string, timestamp: Date, data: Uint8Array | Buffer): Promise<void>;
8
+ /** Returns bytes for this exact resource version, or null when its file cannot be read. */
9
+ static read(cacheId: string, timestamp: Date): Promise<Buffer | null>;
10
+ }
11
+ //# sourceMappingURL=FileCache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FileCache.d.ts","sourceRoot":"","sources":["../../src/helpers/FileCache.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,qBAAa,SAAS;WACL,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,UAAU,GAAG,MAAM;IAyB9E,2FAA2F;WAC9E,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CAoB9E"}
@@ -0,0 +1,10 @@
1
+ export declare class TTLFileCache {
2
+ private cachePath;
3
+ constructor(name: string, ttl: number);
4
+ keyToFilePath(key: string): string;
5
+ cacheFile(key: string, contents: string): Promise<void>;
6
+ checkCache(key: string, ttlMs?: number): Promise<string | null>;
7
+ clear(): Promise<void>;
8
+ purgeCache(ttlMs: number): Promise<void>;
9
+ }
10
+ //# sourceMappingURL=TTLFileCache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TTLFileCache.d.ts","sourceRoot":"","sources":["../../src/helpers/TTLFileCache.ts"],"names":[],"mappings":"AAIA,qBAAa,YAAY;IACrB,OAAO,CAAC,SAAS,CAAS;gBAEd,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM;IAUrC,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAa5B,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAkB/D,KAAK;IAQL,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CA6BjD"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,40 +1,55 @@
1
1
  {
2
2
  "name": "@stamhoofd/backend-renderer",
3
- "version": "2.153.0",
3
+ "version": "2.161.1",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/stamhoofd/stamhoofd.git",
7
+ "directory": "backend/app/renderer"
8
+ },
4
9
  "type": "module",
5
10
  "main": "./dist/index.js",
6
11
  "exports": {
7
12
  ".": {
13
+ "types": "./dist-types/index.d.ts",
8
14
  "require": "./dist/index.js"
9
15
  }
10
16
  },
17
+ "types": "./dist-types/index.d.ts",
18
+ "files": [
19
+ "dist",
20
+ "dist-types",
21
+ "src",
22
+ "*.ts",
23
+ "tsconfig*.json"
24
+ ],
11
25
  "dependencies": {
12
- "@simonbackx/simple-database": "1.40.1",
13
- "@simonbackx/simple-encoding": "2.26.11",
14
- "@simonbackx/simple-endpoints": "1.22.0",
15
- "@simonbackx/simple-errors": "1.5.0",
16
- "@simonbackx/simple-logging": "1.0.1",
17
- "@stamhoofd/backend-env": "2.153.0",
18
- "@stamhoofd/backend-i18n": "2.153.0",
19
- "@stamhoofd/backend-middleware": "2.153.0",
20
- "@stamhoofd/logging": "2.153.0",
21
- "@stamhoofd/queues": "2.153.0",
22
- "@stamhoofd/structures": "2.153.0",
23
- "@stamhoofd/types": "2.153.0",
24
- "@stamhoofd/utility": "2.153.0",
26
+ "@stamhoofd/common-encoding": "2.161.1",
27
+ "@stamhoofd/common-errors": "2.161.1",
28
+ "@stamhoofd/node-database": "2.161.1",
29
+ "@stamhoofd/node-endpoints": "2.161.1",
30
+ "@stamhoofd/node-logging": "2.161.1",
31
+ "@stamhoofd/node-observability": "2.161.1",
32
+ "@stamhoofd/backend-env": "2.161.1",
33
+ "@stamhoofd/backend-i18n": "2.161.1",
34
+ "@stamhoofd/backend-middleware": "2.161.1",
35
+ "@stamhoofd/logging": "2.161.1",
36
+ "@stamhoofd/queues": "2.161.1",
37
+ "@stamhoofd/structures": "2.161.1",
38
+ "@stamhoofd/types": "2.161.1",
39
+ "@stamhoofd/utility": "2.161.1",
25
40
  "formidable": "3.5.4",
26
41
  "luxon": "3.7.2",
27
42
  "mockdate": "3.0.5",
28
- "mysql2": "3.24.4",
29
- "puppeteer": "25.12.0"
43
+ "mysql2": "3.24.6",
44
+ "puppeteer": "25.18.1"
30
45
  },
31
46
  "devDependencies": {
32
- "@stamhoofd/test-utils": "2.153.0",
47
+ "@stamhoofd/test-utils": "2.161.1",
33
48
  "@types/formidable": "3.5.1",
34
- "@types/luxon": "3.7.5",
49
+ "@types/luxon": "3.7.6",
35
50
  "@types/node": "22.20.4",
36
51
  "nock": "14.0.17",
37
- "vitest": "4.1.11"
52
+ "vitest": "4.1.12"
38
53
  },
39
54
  "license": "UNLICENCED",
40
55
  "publishConfig": {
@@ -42,15 +57,14 @@
42
57
  },
43
58
  "scripts": {
44
59
  "build": "tsc --build tsconfig.build.json",
60
+ "build:types": "tsc --project tsconfig.types.json",
45
61
  "build:full": "pnpm run clear && pnpm run build",
46
- "clear": "rm -rf ./dist && rm -f *.tsbuildinfo",
47
- "dev": "wait-on ../../shared/middleware/dist/index.js && concurrently -r 'pnpm run build --watch --preserveWatchOutput' \"wait-on ./dist/index.js && nodemon --quiet --inspect=5858 --watch dist --watch '../../../shared/*/dist/' --watch '../../shared/*/dist/' --ext .ts,.json,.sql,.js --watch .env.json --delay 1000ms --exec 'node --enable-source-maps ./dist/index.js' --signal SIGTERM\"",
48
- "dev:build": "pnpm run build",
49
- "dev:full": "pnpm run dev",
50
- "lint": "eslint",
62
+ "clear": "rm -rf ./dist && rm -f *.tsbuildinfo .cache/*.tsbuildinfo",
63
+ "lint": "eslint --quiet",
51
64
  "start": "pnpm run build && node --enable-source-maps ./dist/index.js",
52
- "typecheck": "tsc --build tsconfig.test.json",
65
+ "typecheck": "tsc --project tsconfig.test.json --noEmit --composite false --incremental --tsBuildInfoFile .cache/typecheck.tsbuildinfo",
53
66
  "test": "vitest",
54
- "test:coverage": "vitest --coverage"
67
+ "test:coverage": "vitest --coverage",
68
+ "postinstall": "node -e \"if (process.env.PUPPETEER_SKIP_DOWNLOAD !== 'true') require('node:child_process').execSync('puppeteer browsers install chrome', { stdio: 'inherit' })\""
55
69
  }
56
70
  }
package/src/boot.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { CORSPreflightEndpoint, Router, RouterServer } from '@simonbackx/simple-endpoints';
1
+ import { CORSPreflightEndpoint, Router, RouterServer } from '@stamhoofd/node-endpoints';
2
+ import type { ApplicationLifecycle } from '@stamhoofd/node-observability';
2
3
  import { I18n } from '@stamhoofd/backend-i18n';
3
4
  import { CORSMiddleware, LogMiddleware } from '@stamhoofd/backend-middleware';
4
5
  import { loadLogger } from '@stamhoofd/logging';
@@ -21,9 +22,9 @@ if (new Date().getTimezoneOffset() !== 0) {
21
22
  throw new Error('Process should always run in UTC timezone');
22
23
  }
23
24
 
24
- const start = async () => {
25
- console.log('Started Renderer.');
25
+ export const boot = async (lifecycle: ApplicationLifecycle) => {
26
26
  loadLogger();
27
+ console.debug('Started Renderer.');
27
28
  await I18n.load();
28
29
 
29
30
  // Load the trusted IP whitelist that guards the /prerender endpoint (no-op when not configured).
@@ -75,6 +76,7 @@ const start = async () => {
75
76
  }
76
77
 
77
78
  // Should not be needed, but added for security as sometimes a promise hangs somewhere
79
+ await lifecycle.close();
78
80
  process.exit(0);
79
81
  };
80
82
 
@@ -93,9 +95,5 @@ const start = async () => {
93
95
  process.exit(1);
94
96
  });
95
97
  });
98
+ await lifecycle.ready(routerServer.server);
96
99
  };
97
-
98
- start().catch((error) => {
99
- console.error('unhandledRejection', error);
100
- process.exit(1);
101
- });
@@ -1,4 +1,4 @@
1
- import { SimpleError } from '@simonbackx/simple-errors';
1
+ import { SimpleError } from '@stamhoofd/common-errors';
2
2
  import { IPRangeSet } from '@stamhoofd/utility/IPRange.js';
3
3
  import fs from 'fs/promises';
4
4
  import path from 'path';
@@ -1,4 +1,4 @@
1
- import { Request, TestServer } from '@simonbackx/simple-endpoints';
1
+ import { Request, TestServer } from '@stamhoofd/node-endpoints';
2
2
  import { CpuService } from '@stamhoofd/logging/CpuService';
3
3
  import { MemoryService } from '@stamhoofd/logging/MemoryService';
4
4
  import { STExpect, TestUtils } from '@stamhoofd/test-utils';
@@ -1,7 +1,7 @@
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';
1
+ import { ArrayDecoder, AutoEncoder, field, StringDecoder } from '@stamhoofd/common-encoding';
2
+ import type { DecodedRequest, Request } from '@stamhoofd/node-endpoints';
3
+ import { Endpoint, Response } from '@stamhoofd/node-endpoints';
4
+ import { SimpleError } from '@stamhoofd/common-errors';
5
5
  import { CpuService } from '@stamhoofd/logging/CpuService';
6
6
  import { MemoryService } from '@stamhoofd/logging/MemoryService';
7
7
 
@@ -0,0 +1,94 @@
1
+ import { Request } from '@stamhoofd/node-endpoints';
2
+ import { signInternal } from '@stamhoofd/backend-env';
3
+ import { promises as fs } from 'node:fs';
4
+ import type { IncomingMessage } from 'node:http';
5
+ import { Readable } from 'node:stream';
6
+ import { HtmlToPdfEndpoint } from './HtmlToPdfEndpoint.js';
7
+ import { FileCache } from '../helpers/FileCache.js';
8
+
9
+ // Observe real Formidable file paths, including partial uploads on parse errors.
10
+ const uploads = vi.hoisted(() => [] as string[]);
11
+ vi.mock('formidable', async (importOriginal) => {
12
+ const original = await importOriginal<typeof import('formidable')>();
13
+ return {
14
+ ...original,
15
+ default: (...args: Parameters<typeof original.formidable>) => {
16
+ const form = original.formidable(...args);
17
+ form.on('fileBegin', (_name, file) => uploads.push(file.filepath));
18
+ return form;
19
+ },
20
+ };
21
+ });
22
+
23
+ /** Uses real multipart parsing and disk uploads, but no browser or persistent PDF cache. */
24
+ describe('HTML PDF multipart cleanup', () => {
25
+ const endpoint = new HtmlToPdfEndpoint();
26
+ const html = '<html>Document</html>';
27
+ const cacheId = 'document-cleanup-test';
28
+ const timestamp = '2000';
29
+
30
+ beforeEach(() => {
31
+ uploads.length = 0;
32
+ vi.spyOn(endpoint, 'htmlToPdf').mockResolvedValue(Buffer.from('PDF'));
33
+ vi.spyOn(FileCache, 'write').mockResolvedValue();
34
+ });
35
+
36
+ afterEach(async () => {
37
+ // Keep failed assertions from leaving test uploads on disk; cleanup is asserted first.
38
+ await Promise.all(uploads.map(path => fs.rm(path, { force: true })));
39
+ vi.restoreAllMocks();
40
+ });
41
+
42
+ /**
43
+ * Builds a raw upload stream for the selected outcome. The HTML file precedes
44
+ * the fields so even invalid authorization creates a file to clean up;
45
+ * omitting the closing boundary exercises partial-upload cleanup.
46
+ */
47
+ function request(mode: string) {
48
+ const boundary = 'StamhoofdRendererTest';
49
+ const expires = String(Date.now() + (mode === 'expired authorization' ? -1000 : 60000));
50
+ const fields: Record<string, string> = {
51
+ cacheId,
52
+ timestamp,
53
+ expires,
54
+ signature: signInternal('html-to-pdf', cacheId, timestamp, expires, html),
55
+ };
56
+ if (mode === 'missing signature') delete fields.signature;
57
+ if (mode === 'invalid signature') fields.signature = 'invalid';
58
+ let body = `--${boundary}\r\nContent-Disposition: form-data; name="html"; filename="document.html"\r\nContent-Type: text/html\r\n\r\n${html}\r\n`;
59
+ for (const [name, value] of Object.entries(fields)) {
60
+ body += `--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`;
61
+ }
62
+ body += mode === 'malformed multipart' ? '' : `--${boundary}--\r\n`;
63
+ const stream = Readable.from([Buffer.from(body)]) as unknown as IncomingMessage;
64
+ stream.headers = {
65
+ 'content-type': `multipart/form-data; boundary=${boundary}`,
66
+ 'content-length': Buffer.byteLength(body).toString(),
67
+ };
68
+ const request = Request.post({ path: '/html-to-pdf' });
69
+ request.request = stream;
70
+ return request;
71
+ }
72
+
73
+ /**
74
+ * Both successful responses and rejected requests must remove every observed
75
+ * upload before handle settles. Requiring an observed path prevents an empty
76
+ * upload list from satisfying the ENOENT checks without exercising cleanup.
77
+ * An expired grant must also reject the request without retaining its upload.
78
+ */
79
+ test.each(['success', 'missing signature', 'invalid signature', 'malformed multipart', 'render failure', 'expired authorization'])('removes uploaded files after %s', async (mode) => {
80
+ if (mode === 'render failure') vi.mocked(endpoint.htmlToPdf).mockResolvedValue(null);
81
+ const decoded = await endpoint.decode(request(mode));
82
+ expect(decoded).not.toBeNull();
83
+ const result = endpoint.handle(decoded!);
84
+ if (mode === 'success') {
85
+ expect((await result).status).toBe(200);
86
+ } else {
87
+ await expect(result).rejects.toThrow();
88
+ }
89
+ expect(uploads.length).toBeGreaterThan(0);
90
+ for (const path of uploads) {
91
+ await expect(fs.stat(path)).rejects.toMatchObject({ code: 'ENOENT' });
92
+ }
93
+ });
94
+ });
@@ -1,11 +1,13 @@
1
- import type { DecodedRequest, Request} from '@simonbackx/simple-endpoints';
2
- import { Endpoint, Response } from '@simonbackx/simple-endpoints';
3
- import { SimpleError } from '@simonbackx/simple-errors';
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 (!verifyInternalSignature(signature, cacheId, timestamp.getTime().toString(), html)) {
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
  }