@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.
Files changed (60) 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 +13 -0
  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 +69 -56
  40. package/src/boot.ts +9 -9
  41. package/src/classes/TrustedIPWhitelist.ts +1 -1
  42. package/src/endpoints/HealthEndpoint.test.ts +18 -1
  43. package/src/endpoints/HealthEndpoint.ts +7 -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/tests/vitest.global.setup.ts +0 -20
  59. package/tests/vitest.setup.ts +0 -31
  60. 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,QAAQ,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAS/D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAKzC,KAAK,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AACpC,KAAK,IAAI,GAAG,SAAS,CAAC;AACtB,KAAK,KAAK,GAAG,SAAS,CAAC;AACvB,KAAK,YAAY,GAAG,UAAU,CAAC;AAE/B;;GAEG;AAEH,qBAAa,iBAAkB,SAAQ,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,CAAC;IAC9E,SAAS,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC;IAa/D;;;;;;OAMG;IACG,MAAM,CAAC,OAAO,EAAE,cAAc,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC;IAyHzD,MAAM,CAAC,QAAQ,EAAE,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC,EAAE,CAA4B;IAC3F,MAAM,CAAC,gBAAgB,SAAK;WAEf,UAAU,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;WAwBrE,YAAY,CAAC,OAAO,EAAE,OAAO;IAY1C;;OAEG;IACG,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,IAAI,CAAA;KAAE,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;CAiC9G"}
@@ -0,0 +1,28 @@
1
+ import type { Decoder } from '@stamhoofd/common-encoding';
2
+ import { AutoEncoder } from '@stamhoofd/common-encoding';
3
+ import type { DecodedRequest, Request } from '@stamhoofd/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,EAAE,GAAG,CAAC;CACZ;AAED,KAAK,IAAI,GAAG;IACR,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,UAAU,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,KAAK,YAAY,GAAG,MAAM,CAAC;AAE3B;;GAEG;AAEH,qBAAa,iBAAkB,SAAQ,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,CAAC;IAC9E,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;IAazD,MAAM,CAAC,OAAO,EAAE,cAAc,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC;IA+BzD,MAAM,CAAC,QAAQ,CAAC,YAAY,SAAuB;IACnD,MAAM,CAAC,SAAS,eAAoD;IAEpE;;OAEG;IACH,MAAM,CAAC,QAAQ,CAAC,eAAe,cAI5B;IAEH;;;;OAIG;IACH,MAAM,CAAC,QAAQ,CAAC,qBAAqB,cAqBlC;IAEH;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAAC,uBAAuB,WAAgD;IAEvF,MAAM,CAAC,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAQ5C;;;;OAIG;IACH,MAAM,CAAC,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;IAsBlD,mGAAmG;IACnG,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;WAmB3E,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,IAAI,CAAA;KAAE,GAAG,OAAO,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,57 +1,70 @@
1
1
  {
2
- "name": "@stamhoofd/backend-renderer",
3
- "version": "2.152.0",
4
- "type": "module",
5
- "main": "./dist/index.js",
6
- "exports": {
7
- ".": {
8
- "require": "./dist/index.js"
9
- }
10
- },
11
- "scripts": {
12
- "build": "tsc --build tsconfig.build.json",
13
- "build:full": "yarn -s clear && yarn -s build",
14
- "clear": "rm -rf ./dist && rm -f *.tsbuildinfo",
15
- "dev": "wait-on ../../shared/middleware/dist/index.js && concurrently -r 'yarn -s 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\"",
16
- "dev:build": "yarn -s build",
17
- "dev:full": "yarn -s dev",
18
- "lint": "eslint",
19
- "start": "yarn -s build && node --enable-source-maps ./dist/index.js",
20
- "typecheck": "tsc --build tsconfig.test.json",
21
- "test": "vitest",
22
- "test:coverage": "vitest --coverage"
23
- },
24
- "dependencies": {
25
- "@simonbackx/simple-database": "1.40.0",
26
- "@simonbackx/simple-encoding": "2.26.11",
27
- "@simonbackx/simple-endpoints": "1.22.0",
28
- "@simonbackx/simple-errors": "1.5.0",
29
- "@simonbackx/simple-logging": "1.0.1",
30
- "@stamhoofd/backend-env": "2.152.0",
31
- "@stamhoofd/backend-i18n": "2.152.0",
32
- "@stamhoofd/backend-middleware": "2.152.0",
33
- "@stamhoofd/logging": "2.152.0",
34
- "@stamhoofd/queues": "2.152.0",
35
- "@stamhoofd/structures": "2.152.0",
36
- "@stamhoofd/types": "2.152.0",
37
- "@stamhoofd/utility": "2.152.0",
38
- "formidable": "3.5.4",
39
- "luxon": "3.7.2",
40
- "mockdate": "3.0.5",
41
- "mysql2": "3.23.1",
42
- "puppeteer": "25.3.0"
43
- },
44
- "devDependencies": {
45
- "@stamhoofd/test-utils": "2.152.0",
46
- "@types/formidable": "3.5.1",
47
- "@types/luxon": "3.7.2",
48
- "@types/node": "22.20.1",
49
- "nock": "14.0.16",
50
- "vitest": "4.1.10"
51
- },
52
- "license": "UNLICENCED",
53
- "publishConfig": {
54
- "access": "public"
55
- },
56
- "gitHead": "66475bb3d64a936320e419ecf8f7d7ad98ff71e8"
57
- }
2
+ "name": "@stamhoofd/backend-renderer",
3
+ "version": "2.160.0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/stamhoofd/stamhoofd.git",
7
+ "directory": "backend/app/renderer"
8
+ },
9
+ "type": "module",
10
+ "main": "./dist/index.js",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist-types/index.d.ts",
14
+ "require": "./dist/index.js"
15
+ }
16
+ },
17
+ "types": "./dist-types/index.d.ts",
18
+ "files": [
19
+ "dist",
20
+ "dist-types",
21
+ "src",
22
+ "*.ts",
23
+ "tsconfig*.json"
24
+ ],
25
+ "dependencies": {
26
+ "@stamhoofd/common-encoding": "2.160.0",
27
+ "@stamhoofd/common-errors": "2.160.0",
28
+ "@stamhoofd/node-database": "2.160.0",
29
+ "@stamhoofd/node-endpoints": "2.160.0",
30
+ "@stamhoofd/node-logging": "2.160.0",
31
+ "@stamhoofd/node-observability": "2.160.0",
32
+ "@stamhoofd/backend-env": "2.160.0",
33
+ "@stamhoofd/backend-i18n": "2.160.0",
34
+ "@stamhoofd/backend-middleware": "2.160.0",
35
+ "@stamhoofd/logging": "2.160.0",
36
+ "@stamhoofd/queues": "2.160.0",
37
+ "@stamhoofd/structures": "2.160.0",
38
+ "@stamhoofd/types": "2.160.0",
39
+ "@stamhoofd/utility": "2.160.0",
40
+ "formidable": "3.5.4",
41
+ "luxon": "3.7.2",
42
+ "mockdate": "3.0.5",
43
+ "mysql2": "3.24.6",
44
+ "puppeteer": "25.18.1"
45
+ },
46
+ "devDependencies": {
47
+ "@stamhoofd/test-utils": "2.160.0",
48
+ "@types/formidable": "3.5.1",
49
+ "@types/luxon": "3.7.6",
50
+ "@types/node": "22.20.4",
51
+ "nock": "14.0.17",
52
+ "vitest": "4.1.12"
53
+ },
54
+ "license": "UNLICENCED",
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "scripts": {
59
+ "build": "tsc --build tsconfig.build.json",
60
+ "build:types": "tsc --project tsconfig.types.json",
61
+ "build:full": "pnpm run clear && pnpm run build",
62
+ "clear": "rm -rf ./dist && rm -f *.tsbuildinfo .cache/*.tsbuildinfo",
63
+ "lint": "eslint --quiet",
64
+ "start": "pnpm run build && node --enable-source-maps ./dist/index.js",
65
+ "typecheck": "tsc --project tsconfig.test.json --noEmit --composite false --incremental --tsBuildInfoFile .cache/typecheck.tsbuildinfo",
66
+ "test": "vitest",
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' })\""
69
+ }
70
+ }
package/src/boot.ts CHANGED
@@ -1,8 +1,10 @@
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';
5
6
  import { CpuService } from '@stamhoofd/logging/CpuService';
7
+ import { MemoryService } from '@stamhoofd/logging/MemoryService';
6
8
  import { TrustedIPWhitelist } from './classes/TrustedIPWhitelist.js';
7
9
 
8
10
  process.on('unhandledRejection', (error: Error) => {
@@ -20,9 +22,9 @@ if (new Date().getTimezoneOffset() !== 0) {
20
22
  throw new Error('Process should always run in UTC timezone');
21
23
  }
22
24
 
23
- const start = async () => {
24
- console.log('Started Renderer.');
25
+ export const boot = async (lifecycle: ApplicationLifecycle) => {
25
26
  loadLogger();
27
+ console.debug('Started Renderer.');
26
28
  await I18n.load();
27
29
 
28
30
  // Load the trusted IP whitelist that guards the /prerender endpoint (no-op when not configured).
@@ -45,9 +47,10 @@ const start = async () => {
45
47
 
46
48
  routerServer.listen(STAMHOOFD.PORT ?? 9090);
47
49
 
48
- // Monitor CPU load so the /health endpoint can report an overloaded renderer as unhealthy.
50
+ // Monitor CPU load and memory so the /health endpoint can report an overloaded renderer as unhealthy.
49
51
  if (STAMHOOFD.environment !== 'development' && STAMHOOFD.environment !== 'test') {
50
52
  CpuService.startMonitoring();
53
+ MemoryService.startMonitoring();
51
54
  }
52
55
 
53
56
  if (routerServer.server) {
@@ -73,6 +76,7 @@ const start = async () => {
73
76
  }
74
77
 
75
78
  // Should not be needed, but added for security as sometimes a promise hangs somewhere
79
+ await lifecycle.close();
76
80
  process.exit(0);
77
81
  };
78
82
 
@@ -91,9 +95,5 @@ const start = async () => {
91
95
  process.exit(1);
92
96
  });
93
97
  });
98
+ await lifecycle.ready(routerServer.server);
94
99
  };
95
-
96
- start().catch((error) => {
97
- console.error('unhandledRejection', error);
98
- process.exit(1);
99
- });
@@ -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,5 +1,6 @@
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
+ import { MemoryService } from '@stamhoofd/logging/MemoryService';
3
4
  import { STExpect, TestUtils } from '@stamhoofd/test-utils';
4
5
  import { HealthEndpoint } from './HealthEndpoint.js';
5
6
 
@@ -15,6 +16,7 @@ describe('Endpoint.Health', () => {
15
16
  afterEach(() => {
16
17
  // Reset the CPU samples so a high-load test doesn't leak into the next one.
17
18
  CpuService.samples.fill(0);
19
+ MemoryService.clearForTesting();
18
20
  });
19
21
 
20
22
  test('Returns 200 when healthy', async () => {
@@ -43,6 +45,21 @@ describe('Endpoint.Health', () => {
43
45
  expect(response.body.errors).toContain('CPU usage is too high');
44
46
  });
45
47
 
48
+ test('Returns 503 when the heap has been almost full for a minute', async () => {
49
+ const mib = 1024 * 1024;
50
+ MemoryService.record({ heapUsed: 480 * mib, heapLimit: 512 * mib, rss: 900 * mib, external: 100 * mib, systemTotal: 8192 * mib, systemAvailable: 4096 * mib });
51
+
52
+ const request = Request.get({
53
+ path: '/health',
54
+ query: { key },
55
+ });
56
+
57
+ const response = await testServer.test(endpoint, request);
58
+ expect(response.status).toBe(503);
59
+ expect(response.body.status).toBe('error');
60
+ expect(response.body.errors).toEqual(['Heap memory usage is too high: 480 MiB of 512 MiB (94% average)']);
61
+ });
62
+
46
63
  test('Rejects requests with a wrong key', async () => {
47
64
  const request = Request.get({
48
65
  path: '/health',
@@ -1,8 +1,9 @@
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
+ import { MemoryService } from '@stamhoofd/logging/MemoryService';
6
7
 
7
8
  type Params = Record<string, never>;
8
9
  type Body = undefined;
@@ -71,6 +72,8 @@ export class HealthEndpoint extends Endpoint<Params, Query, Body, ResponseBody>
71
72
  errors.push('CPU usage is too high');
72
73
  }
73
74
 
75
+ errors.push(...MemoryService.getErrors());
76
+
74
77
  const health = ResponseBody.create({
75
78
  status: errors.length > 0 ? 'error' : 'ok',
76
79
  errors: errors.length > 0 ? errors : undefined,
@@ -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
+ });