@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.
- 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 +7 -6
- 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 +40 -26
- package/src/boot.ts +6 -8
- package/src/classes/TrustedIPWhitelist.ts +1 -1
- package/src/endpoints/HealthEndpoint.test.ts +1 -1
- package/src/endpoints/HealthEndpoint.ts +4 -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/.gitignore +0 -223
- package/tests/vitest.global.setup.ts +0 -20
- package/tests/vitest.setup.ts +0 -31
- package/vitest.config.js +0 -20
package/LICENSE.md
CHANGED
|
@@ -5,25 +5,25 @@ Copyright 2020 Codawood BV
|
|
|
5
5
|
Permission is hereby granted, free of charge, to any non-profit organization with fewer than 2,000 members (each, a “Licensee”), to use this software and associated documentation files (the “Software”), subject to the following conditions:
|
|
6
6
|
|
|
7
7
|
1. Eligibility:
|
|
8
|
-
This license applies only if neither the Licensee nor, if applicable, its parent or umbrella organization, is already subject to an existing license for this project. For the purposes of this license, a “parent or umbrella organization” means any organization with which the Licensee is affiliated, coordinated, or represented as part of a larger collective, including but not limited to national associations or federations.
|
|
8
|
+
This license applies only if neither the Licensee nor, if applicable, its parent or umbrella organization, is already subject to an existing license for this project. For the purposes of this license, a “parent or umbrella organization” means any organization with which the Licensee is affiliated, coordinated, or represented as part of a larger collective, including but not limited to national associations or federations.
|
|
9
9
|
|
|
10
10
|
2. Modifications:
|
|
11
|
-
Modifications to the Software are permitted only if they are published publicly under the MIT License, covering only the modifications; the original Software remains under this license and may not be sublicensed without a separate agreement. Any modification made by a Licensee (other than modifications by the original author, its representatives, or the copyright owner) shall be deemed to be distributed under the MIT License. Submission of modifications through publicly accessible channels, including but not limited to pull requests on code repositories such as GitHub, shall be considered an explicit acknowledgment and grant by the Licensee that such modifications are made available under the MIT License. Licensees may not sublicense, transfer, or assign the rights granted under this license except as expressly permitted herein.
|
|
11
|
+
Modifications to the Software are permitted only if they are published publicly under the MIT License, covering only the modifications; the original Software remains under this license and may not be sublicensed without a separate agreement. Any modification made by a Licensee (other than modifications by the original author, its representatives, or the copyright owner) shall be deemed to be distributed under the MIT License. Submission of modifications through publicly accessible channels, including but not limited to pull requests on code repositories such as GitHub, shall be considered an explicit acknowledgment and grant by the Licensee that such modifications are made available under the MIT License. Licensees may not sublicense, transfer, or assign the rights granted under this license except as expressly permitted herein.
|
|
12
12
|
|
|
13
13
|
3. Precedence of Existing Licenses:
|
|
14
|
-
If the Licensee, or its parent or umbrella organization, is already subject to an existing license for this project, that license shall take precedence, and no additional free license is granted. Nothing in this license shall be construed to override any pre-existing exclusive license agreement.
|
|
14
|
+
If the Licensee, or its parent or umbrella organization, is already subject to an existing license for this project, that license shall take precedence, and no additional free license is granted. Nothing in this license shall be construed to override any pre-existing exclusive license agreement.
|
|
15
15
|
|
|
16
16
|
4. Data Protection / GDPR Responsibility:
|
|
17
|
-
Licensees are solely responsible for ensuring that any processing of personal data using this software complies with applicable data protection laws, including the EU General Data Protection Regulation (GDPR).
|
|
17
|
+
Licensees are solely responsible for ensuring that any processing of personal data using this software complies with applicable data protection laws, including the EU General Data Protection Regulation (GDPR).
|
|
18
18
|
|
|
19
19
|
5. Termination and Revocation:
|
|
20
|
-
The copyright holders may revoke this license at any time, at their sole discretion.
|
|
20
|
+
The copyright holders may revoke this license at any time, at their sole discretion.
|
|
21
21
|
|
|
22
22
|
6. Governing Law:
|
|
23
|
-
This license shall be governed by and construed in accordance with the laws of Belgium, without regard to conflict of law principles.
|
|
23
|
+
This license shall be governed by and construed in accordance with the laws of Belgium, without regard to conflict of law principles.
|
|
24
24
|
|
|
25
25
|
7. Third-Party Licenses:
|
|
26
|
-
Certain files or components included in the Software may be governed by separate licenses, including open-source licenses, or contributed by third parties under different terms. Such files are not automatically covered by this license. Licensees are responsible for reviewing and complying with any additional license terms that apply to these files.
|
|
26
|
+
Certain files or components included in the Software may be governed by separate licenses, including open-source licenses, or contributed by third parties under different terms. Such files are not automatically covered by this license. Licensees are responsible for reviewing and complying with any additional license terms that apply to these files.
|
|
27
27
|
|
|
28
28
|
For the purposes of this license, a “non-profit organization” means an entity recognized as non-profit under applicable law in its jurisdiction, which does not distribute profits to its members or owners.
|
|
29
29
|
|
package/README.md
CHANGED
|
@@ -1 +1,11 @@
|
|
|
1
|
-
# Stamhoofd Renderer service
|
|
1
|
+
# Stamhoofd Renderer service
|
|
2
|
+
|
|
3
|
+
PDF cache reads require an API-issued signature over `pdf-cache`, the cache ID,
|
|
4
|
+
the exact version timestamp, and an expiry timestamp. HTML rendering signs
|
|
5
|
+
`html-to-pdf`, the cache ID, version timestamp, expiry, and HTML. Both grants last
|
|
6
|
+
at most 60 seconds; cached HTTP responses must not reuse them. The document client
|
|
7
|
+
always obtains a new grant through the API's current document permission check.
|
|
8
|
+
A grant already issued before permission revocation remains usable until expiry.
|
|
9
|
+
Deploy API, renderer, and document clients together: old unsigned cache requests
|
|
10
|
+
and non-expiring render signatures are rejected. Invoice generation uses the same
|
|
11
|
+
expiring render transport.
|
package/dist/boot.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { CORSPreflightEndpoint, Router, RouterServer } from '@stamhoofd/node-endpoints';
|
|
2
|
+
import { I18n } from '@stamhoofd/backend-i18n';
|
|
3
|
+
import { CORSMiddleware, LogMiddleware } from '@stamhoofd/backend-middleware';
|
|
4
|
+
import { loadLogger } from '@stamhoofd/logging';
|
|
5
|
+
import { CpuService } from '@stamhoofd/logging/CpuService';
|
|
6
|
+
import { MemoryService } from '@stamhoofd/logging/MemoryService';
|
|
7
|
+
import { TrustedIPWhitelist } from './classes/TrustedIPWhitelist.js';
|
|
8
|
+
process.on('unhandledRejection', (error) => {
|
|
9
|
+
console.error('unhandledRejection');
|
|
10
|
+
console.error(error.message, error.stack);
|
|
11
|
+
process.exit(1);
|
|
12
|
+
});
|
|
13
|
+
// Set timezone!
|
|
14
|
+
process.env.TZ = 'UTC';
|
|
15
|
+
Error.stackTraceLimit = 50;
|
|
16
|
+
// Quick check
|
|
17
|
+
if (new Date().getTimezoneOffset() !== 0) {
|
|
18
|
+
throw new Error('Process should always run in UTC timezone');
|
|
19
|
+
}
|
|
20
|
+
export const boot = async (lifecycle) => {
|
|
21
|
+
loadLogger();
|
|
22
|
+
console.debug('Started Renderer.');
|
|
23
|
+
await I18n.load();
|
|
24
|
+
// Load the trusted IP whitelist that guards the /prerender endpoint (no-op when not configured).
|
|
25
|
+
await TrustedIPWhitelist.shared.load();
|
|
26
|
+
TrustedIPWhitelist.shared.startAutoRefresh();
|
|
27
|
+
const router = new Router();
|
|
28
|
+
await router.loadEndpoints(import.meta.dirname + '/endpoints');
|
|
29
|
+
router.endpoints.push(new CORSPreflightEndpoint());
|
|
30
|
+
const routerServer = new RouterServer(router);
|
|
31
|
+
routerServer.verbose = false;
|
|
32
|
+
// Send the app version along
|
|
33
|
+
routerServer.addRequestMiddleware(LogMiddleware);
|
|
34
|
+
routerServer.addResponseMiddleware(LogMiddleware);
|
|
35
|
+
// Add CORS headers
|
|
36
|
+
routerServer.addResponseMiddleware(CORSMiddleware);
|
|
37
|
+
routerServer.listen(STAMHOOFD.PORT ?? 9090);
|
|
38
|
+
// Monitor CPU load and memory so the /health endpoint can report an overloaded renderer as unhealthy.
|
|
39
|
+
if (STAMHOOFD.environment !== 'development' && STAMHOOFD.environment !== 'test') {
|
|
40
|
+
CpuService.startMonitoring();
|
|
41
|
+
MemoryService.startMonitoring();
|
|
42
|
+
}
|
|
43
|
+
if (routerServer.server) {
|
|
44
|
+
// Default timeout is a bit too short
|
|
45
|
+
routerServer.server.timeout = 15000;
|
|
46
|
+
}
|
|
47
|
+
const shutdown = async () => {
|
|
48
|
+
console.log('Shutting down...');
|
|
49
|
+
// Disable keep alive
|
|
50
|
+
routerServer.defaultHeaders = Object.assign(routerServer.defaultHeaders, { Connection: 'close' });
|
|
51
|
+
if (routerServer.server) {
|
|
52
|
+
routerServer.server.headersTimeout = 5000;
|
|
53
|
+
routerServer.server.keepAliveTimeout = 1;
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
await routerServer.close();
|
|
57
|
+
console.log('HTTP server stopped');
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
console.error('Failed to stop HTTP server:');
|
|
61
|
+
console.error(err);
|
|
62
|
+
}
|
|
63
|
+
// Should not be needed, but added for security as sometimes a promise hangs somewhere
|
|
64
|
+
await lifecycle.close();
|
|
65
|
+
process.exit(0);
|
|
66
|
+
};
|
|
67
|
+
process.on('SIGTERM', () => {
|
|
68
|
+
console.info('SIGTERM signal received.');
|
|
69
|
+
shutdown().catch((e) => {
|
|
70
|
+
console.error(e);
|
|
71
|
+
process.exit(1);
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
process.on('SIGINT', () => {
|
|
75
|
+
console.info('SIGINT signal received.');
|
|
76
|
+
shutdown().catch((e) => {
|
|
77
|
+
console.error(e);
|
|
78
|
+
process.exit(1);
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
await lifecycle.ready(routerServer.server);
|
|
82
|
+
};
|
|
83
|
+
//# sourceMappingURL=boot.js.map
|
package/dist/boot.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"boot.js","sourceRoot":"","sources":["../src/boot.ts"],"names":[],"mappings":"A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
import { IPRangeSet } from '@stamhoofd/utility/IPRange.js';
|
|
3
|
+
import fs from 'fs/promises';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
/**
|
|
6
|
+
* Guards the /prerender endpoint against being overloaded by (spam) bots by only allowing
|
|
7
|
+
* requests from a whitelist of trusted IP addresses (legitimate crawlers, AI bots, monitoring, ...).
|
|
8
|
+
*
|
|
9
|
+
* The whitelist is fetched from a public, plain-text list and cached on disk. On boot and on every
|
|
10
|
+
* refresh we try the remote source first and fall back to the local cache when it's unavailable, so
|
|
11
|
+
* a transient outage never wipes the whitelist. If no list is available at all (neither remote nor
|
|
12
|
+
* cache), the set stays empty and every request is blocked (fail-closed) — a state our monitoring
|
|
13
|
+
* should alert on.
|
|
14
|
+
*
|
|
15
|
+
* The source URL defaults to {@link TrustedIPWhitelist.DEFAULT_URL} in real deployments (production
|
|
16
|
+
* and staging) and can be overridden with PRERENDER_IP_WHITELIST_URL. In local development and tests
|
|
17
|
+
* it's off by default and only enabled when PRERENDER_IP_WHITELIST_URL is explicitly set.
|
|
18
|
+
*/
|
|
19
|
+
export class TrustedIPWhitelist {
|
|
20
|
+
static shared = new TrustedIPWhitelist();
|
|
21
|
+
/**
|
|
22
|
+
* Default trusted-IP source: the "all safe IPs" list (crawlers, AI bots, infrastructure,
|
|
23
|
+
* monitoring and DNS resolvers) from https://github.com/sefinek/trusted-ips-whitelist.
|
|
24
|
+
*/
|
|
25
|
+
static DEFAULT_URL = 'https://raw.githubusercontent.com/sefinek/trusted-ips-whitelist/main/lists/all-safe-ips.txt';
|
|
26
|
+
/** The upstream list is regenerated roughly every 6 hours. */
|
|
27
|
+
static REFRESH_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
|
28
|
+
/** While we have no list at all (fail-closed, blocking everything), retry much more often. */
|
|
29
|
+
static EMPTY_RETRY_INTERVAL_MS = 5 * 60 * 1000;
|
|
30
|
+
static FETCH_TIMEOUT_MS = 30 * 1000;
|
|
31
|
+
static CACHE_FILE_NAME = 'trusted-ips-whitelist.txt';
|
|
32
|
+
set = new IPRangeSet();
|
|
33
|
+
refreshTimer = null;
|
|
34
|
+
autoRefreshActive = false;
|
|
35
|
+
get enabled() {
|
|
36
|
+
return !!this.url;
|
|
37
|
+
}
|
|
38
|
+
get url() {
|
|
39
|
+
if (STAMHOOFD.PRERENDER_IP_WHITELIST_URL) {
|
|
40
|
+
return STAMHOOFD.PRERENDER_IP_WHITELIST_URL;
|
|
41
|
+
}
|
|
42
|
+
// Enabled by default in real deployments; opt-in (via the env var) for local dev and tests.
|
|
43
|
+
if (STAMHOOFD.environment === 'production' || STAMHOOFD.environment === 'staging') {
|
|
44
|
+
return TrustedIPWhitelist.DEFAULT_URL;
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
/** Number of ranges currently loaded (for logging/monitoring/tests). */
|
|
49
|
+
get count() {
|
|
50
|
+
return this.set.size;
|
|
51
|
+
}
|
|
52
|
+
get cacheFilePath() {
|
|
53
|
+
return path.join(STAMHOOFD.CACHE_PATH, TrustedIPWhitelist.CACHE_FILE_NAME);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Parse raw list text into a set of ranges. Lines that are empty or start with '#' are
|
|
57
|
+
* ignored; unparseable lines are skipped (and logged).
|
|
58
|
+
*/
|
|
59
|
+
parse(text) {
|
|
60
|
+
const set = new IPRangeSet();
|
|
61
|
+
set.addText(text, (line, error) => {
|
|
62
|
+
console.error(`[trusted-ips] Failed to parse line: ${line}`, error);
|
|
63
|
+
});
|
|
64
|
+
return set;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Replace the in-memory ranges from raw list text. Returns the number of parsed entries.
|
|
68
|
+
*/
|
|
69
|
+
setFromText(text) {
|
|
70
|
+
this.set = this.parse(text);
|
|
71
|
+
return this.set.size;
|
|
72
|
+
}
|
|
73
|
+
async fetchRemote() {
|
|
74
|
+
const url = this.url;
|
|
75
|
+
if (!url) {
|
|
76
|
+
throw new Error('No PRERENDER_IP_WHITELIST_URL configured');
|
|
77
|
+
}
|
|
78
|
+
const controller = new AbortController();
|
|
79
|
+
const timeout = setTimeout(() => controller.abort(), TrustedIPWhitelist.FETCH_TIMEOUT_MS);
|
|
80
|
+
try {
|
|
81
|
+
const response = await fetch(url, { signal: controller.signal });
|
|
82
|
+
if (!response.ok) {
|
|
83
|
+
throw new Error(`Unexpected status ${response.status} while fetching ${url}`);
|
|
84
|
+
}
|
|
85
|
+
return await response.text();
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
clearTimeout(timeout);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
async readCache() {
|
|
92
|
+
try {
|
|
93
|
+
return await fs.readFile(this.cacheFilePath, 'utf-8');
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
async writeCache(text) {
|
|
100
|
+
try {
|
|
101
|
+
await fs.mkdir(STAMHOOFD.CACHE_PATH, { recursive: true });
|
|
102
|
+
await fs.writeFile(this.cacheFilePath, text, 'utf-8');
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
console.error('[trusted-ips] Failed to persist whitelist cache', error);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Fetch the whitelist from the remote source and persist it locally. Falls back to the
|
|
110
|
+
* locally cached copy when the remote fetch fails or returns an empty list, so a transient
|
|
111
|
+
* outage doesn't drop the whitelist. Never throws: a failure just leaves the previous set
|
|
112
|
+
* in place, or an empty set if nothing could be loaded.
|
|
113
|
+
*/
|
|
114
|
+
async load() {
|
|
115
|
+
if (!this.enabled) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
const text = await this.fetchRemote();
|
|
120
|
+
const set = this.parse(text);
|
|
121
|
+
if (set.size > 0) {
|
|
122
|
+
// Only install and persist a valid, non-empty list.
|
|
123
|
+
this.set = set;
|
|
124
|
+
await this.writeCache(text);
|
|
125
|
+
console.log(`[trusted-ips] Loaded ${set.size} trusted IP ranges from ${this.url}`);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
console.error('[trusted-ips] Remote whitelist was empty, falling back to local cache');
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
console.error('[trusted-ips] Failed to fetch remote whitelist, falling back to local cache', error);
|
|
132
|
+
}
|
|
133
|
+
// Fall back to the last known good copy on disk. We keep the current in-memory set until
|
|
134
|
+
// we have a valid replacement, so a failed refresh never blocks requests it was serving.
|
|
135
|
+
const cached = await this.readCache();
|
|
136
|
+
if (cached !== null) {
|
|
137
|
+
const set = this.parse(cached);
|
|
138
|
+
if (set.size > 0) {
|
|
139
|
+
this.set = set;
|
|
140
|
+
console.log(`[trusted-ips] Loaded ${set.size} trusted IP ranges from local cache`);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// No usable list at all: block every request (fail-closed). Monitoring should alert on this.
|
|
145
|
+
this.set = new IPRangeSet();
|
|
146
|
+
console.error('[trusted-ips] No trusted IP whitelist available (remote and cache both failed). Prerender requests will be blocked.');
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Delay until the next background refresh. While we have a usable list we only need to keep up
|
|
150
|
+
* with the upstream (regenerated ~every 6h); while we have nothing (fail-closed, blocking every
|
|
151
|
+
* request) we retry much more often so a brief upstream outage doesn't blackhole prerendering.
|
|
152
|
+
*/
|
|
153
|
+
nextRefreshDelay() {
|
|
154
|
+
return this.count > 0
|
|
155
|
+
? TrustedIPWhitelist.REFRESH_INTERVAL_MS
|
|
156
|
+
: TrustedIPWhitelist.EMPTY_RETRY_INTERVAL_MS;
|
|
157
|
+
}
|
|
158
|
+
/** Periodically refresh the whitelist in the background. Safe to call multiple times. */
|
|
159
|
+
startAutoRefresh() {
|
|
160
|
+
if (!this.enabled || this.autoRefreshActive) {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
this.autoRefreshActive = true;
|
|
164
|
+
this.scheduleNextRefresh();
|
|
165
|
+
}
|
|
166
|
+
scheduleNextRefresh() {
|
|
167
|
+
if (!this.autoRefreshActive) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
this.refreshTimer = setTimeout(() => {
|
|
171
|
+
// load() never rejects (it handles its own errors); reschedule once it settles.
|
|
172
|
+
void this.load().finally(() => this.scheduleNextRefresh());
|
|
173
|
+
}, this.nextRefreshDelay());
|
|
174
|
+
// Don't keep the event loop alive just for refreshing.
|
|
175
|
+
this.refreshTimer.unref?.();
|
|
176
|
+
}
|
|
177
|
+
stopAutoRefresh() {
|
|
178
|
+
this.autoRefreshActive = false;
|
|
179
|
+
if (this.refreshTimer) {
|
|
180
|
+
clearTimeout(this.refreshTimer);
|
|
181
|
+
this.refreshTimer = null;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
isWhitelisted(ip) {
|
|
185
|
+
return this.set.includes(ip);
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Throws a 403 when whitelisting is enabled and the IP is not allowed (including when the
|
|
189
|
+
* whitelist could not be loaded). When disabled this is a no-op.
|
|
190
|
+
*/
|
|
191
|
+
assertAllowed(ip) {
|
|
192
|
+
if (!this.enabled) {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (!this.isWhitelisted(ip)) {
|
|
196
|
+
throw new SimpleError({
|
|
197
|
+
statusCode: 403,
|
|
198
|
+
code: 'ip_not_whitelisted',
|
|
199
|
+
message: `IP ${ip} is not in the trusted IP whitelist`,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
//# sourceMappingURL=TrustedIPWhitelist.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TrustedIPWhitelist.js","sourceRoot":"","sources":["../../src/classes/TrustedIPWhitelist.ts"],"names":[],"mappings":"AAAA,OAAO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C,IAAI,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,mBAAmB,EAAE,CAAC,CAAC;QAC/D,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,CAAC,CAAC;QAE5B,uDAAuD;QACvD,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC;IAChC,CAAC;IAED,eAAe;QACX,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;QAC/B,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACpB,YAAY,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;YAChC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC7B,CAAC;IACL,CAAC;IAED,aAAa,CAAC,EAAU;QACpB,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IACjC,CAAC;IAED;;;OAGG;IACH,aAAa,CAAC,EAAU;QACpB,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAChB,OAAO;QACX,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,WAAW,CAAC;gBAClB,UAAU,EAAE,GAAG;gBACf,IAAI,EAAE,oBAAoB;gBAC1B,OAAO,EAAE,MAAM,EAAE,qCAAqC;aACzD,CAAC,CAAC;QACP,CAAC;IACL,CAAC"}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { __decorate } from "tslib";
|
|
2
|
+
import { ArrayDecoder, AutoEncoder, field, StringDecoder } from '@stamhoofd/common-encoding';
|
|
3
|
+
import { Endpoint, Response } from '@stamhoofd/node-endpoints';
|
|
4
|
+
import { SimpleError } from '@stamhoofd/common-errors';
|
|
5
|
+
import { CpuService } from '@stamhoofd/logging/CpuService';
|
|
6
|
+
import { MemoryService } from '@stamhoofd/logging/MemoryService';
|
|
7
|
+
class Query extends AutoEncoder {
|
|
8
|
+
key;
|
|
9
|
+
}
|
|
10
|
+
__decorate([
|
|
11
|
+
field({ decoder: StringDecoder, optional: true })
|
|
12
|
+
], Query.prototype, "key", void 0);
|
|
13
|
+
export class ResponseBody extends AutoEncoder {
|
|
14
|
+
status;
|
|
15
|
+
errors;
|
|
16
|
+
}
|
|
17
|
+
__decorate([
|
|
18
|
+
field({ decoder: StringDecoder })
|
|
19
|
+
], ResponseBody.prototype, "status", void 0);
|
|
20
|
+
__decorate([
|
|
21
|
+
field({ decoder: new ArrayDecoder(StringDecoder), optional: true })
|
|
22
|
+
], ResponseBody.prototype, "errors", void 0);
|
|
23
|
+
/**
|
|
24
|
+
* Liveness/health endpoint for the renderer service. Guarded by an optional access key so it can be
|
|
25
|
+
* polled by load balancers and monitoring without exposing anything sensitive. The endpoint is only
|
|
26
|
+
* registered when a HEALTH_ACCESS_KEY is configured.
|
|
27
|
+
*/
|
|
28
|
+
export class HealthEndpoint extends Endpoint {
|
|
29
|
+
queryDecoder = Query;
|
|
30
|
+
doesMatch(request) {
|
|
31
|
+
if (request.method !== 'GET') {
|
|
32
|
+
return [false];
|
|
33
|
+
}
|
|
34
|
+
if (!STAMHOOFD.HEALTH_ACCESS_KEY) {
|
|
35
|
+
return [false];
|
|
36
|
+
}
|
|
37
|
+
const params = Endpoint.parseParameters(request.url, '/health', {});
|
|
38
|
+
if (params) {
|
|
39
|
+
return [true, params];
|
|
40
|
+
}
|
|
41
|
+
return [false];
|
|
42
|
+
}
|
|
43
|
+
async handle(request) {
|
|
44
|
+
if (!STAMHOOFD.HEALTH_ACCESS_KEY) {
|
|
45
|
+
throw new SimpleError({
|
|
46
|
+
code: 'unauthorized',
|
|
47
|
+
message: 'Unauthorized',
|
|
48
|
+
statusCode: 401,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
if (STAMHOOFD.HEALTH_ACCESS_KEY && request.query.key !== STAMHOOFD.HEALTH_ACCESS_KEY) {
|
|
52
|
+
throw new SimpleError({
|
|
53
|
+
code: 'unauthorized',
|
|
54
|
+
message: 'Unauthorized',
|
|
55
|
+
statusCode: 401,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
const errors = [];
|
|
59
|
+
// The renderer is CPU-bound (Puppeteer). Sustained high load means it can no longer render
|
|
60
|
+
// pages in time, so report it as unhealthy so it can be taken out of rotation.
|
|
61
|
+
if (CpuService.getAverage(60) > 80) {
|
|
62
|
+
errors.push('CPU usage is too high');
|
|
63
|
+
}
|
|
64
|
+
errors.push(...MemoryService.getErrors());
|
|
65
|
+
const health = ResponseBody.create({
|
|
66
|
+
status: errors.length > 0 ? 'error' : 'ok',
|
|
67
|
+
errors: errors.length > 0 ? errors : undefined,
|
|
68
|
+
});
|
|
69
|
+
const response = new Response(health);
|
|
70
|
+
if (health.status === 'error') {
|
|
71
|
+
response.status = 503;
|
|
72
|
+
}
|
|
73
|
+
return response;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=HealthEndpoint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"HealthEndpoint.js","sourceRoot":"","sources":["../../src/endpoints/HealthEndpoint.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAE7F,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAC;AAKjE,MAAM,KAAM,SAAQ,WAAW;IAE3B,GAAG,CAAU;CAChB;AADG;IADC,KAAK,CAAC,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;kCACrC;AAGjB,MAAM,OAAO,YAAa,SAAQ,WAAW;IAEzC,MAAM,CAAiB;I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M,MAAM,GAAa,EAAE,CAAC;QAE5B,2FAA2F;QAC3F,+EAA+E;QAC/E,IAAI,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC;YACjC,MAAM,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QACzC,CAAC;QAED,MAAM,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC,SAAS,EAAE,CAAC,CAAC;QAE1C,MAAM,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC;YAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI;YAC1C,MAAM,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;SACjD,CAAC,CAAC;QAEH,MAAM,QAAQ,GAAG,IAAI,QAAQ,CACzB,MAAM,CACT,CAAC;QAEF,IAAI,MAAM,CAAC,MAAM,KAAK,OAAO,EAAE,CAAC;YAC5B,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC;QAC1B,CAAC;QACD,OAAO,QAAQ,CAAC;IACpB,CAAC;CACJ"}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { Endpoint, Response } from '@stamhoofd/node-endpoints';
|
|
2
|
+
import { SimpleError } from '@stamhoofd/common-errors';
|
|
3
|
+
import { verifyInternalSignature } from '@stamhoofd/backend-env';
|
|
4
|
+
import { QueueHandler } from '@stamhoofd/queues';
|
|
5
|
+
import formidable from 'formidable';
|
|
6
|
+
import { firstValues } from 'formidable/src/helpers/firstValues.js';
|
|
7
|
+
import { promises as fs } from 'fs';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import puppeteer from 'puppeteer';
|
|
11
|
+
import { FileCache } from '../helpers/FileCache.js';
|
|
12
|
+
/**
|
|
13
|
+
* 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
|
|
14
|
+
*/
|
|
15
|
+
export class HtmlToPdfEndpoint extends Endpoint {
|
|
16
|
+
doesMatch(request) {
|
|
17
|
+
if (request.method !== 'POST') {
|
|
18
|
+
return [false];
|
|
19
|
+
}
|
|
20
|
+
const params = Endpoint.parseParameters(request.url, '/html-to-pdf', {});
|
|
21
|
+
if (params) {
|
|
22
|
+
return [true, params];
|
|
23
|
+
}
|
|
24
|
+
return [false];
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Reads multipart HTML into memory and removes the request's upload directory
|
|
28
|
+
* whether parsing succeeds or fails, before signature verification or rendering.
|
|
29
|
+
* Returns PDF bytes after rendering and caching the signed resource version.
|
|
30
|
+
* The html-to-pdf grant binds the HTML bytes, cache ID, version and expiry;
|
|
31
|
+
* expired grants or expiries beyond the next minute are rejected before rendering.
|
|
32
|
+
*/
|
|
33
|
+
async handle(request) {
|
|
34
|
+
const uploadDir = await fs.mkdtemp(join(tmpdir(), 'stamhoofd-renderer-'));
|
|
35
|
+
const form = formidable({
|
|
36
|
+
uploadDir,
|
|
37
|
+
maxTotalFileSize: 20 * 1024 * 1024,
|
|
38
|
+
keepExtensions: false,
|
|
39
|
+
maxFiles: 1,
|
|
40
|
+
});
|
|
41
|
+
const { html, cacheId, timestamp, signature, expires } = await new Promise((resolve, reject) => {
|
|
42
|
+
if (!request.request.request) {
|
|
43
|
+
reject(new SimpleError({
|
|
44
|
+
code: 'invalid_request',
|
|
45
|
+
message: 'Invalid request',
|
|
46
|
+
statusCode: 500,
|
|
47
|
+
}));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
51
|
+
form.parse(request.request.request, async (err, fieldsMultiple, files) => {
|
|
52
|
+
if (err) {
|
|
53
|
+
reject(err);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (!files.html || files.html.length !== 1) {
|
|
57
|
+
reject(new SimpleError({
|
|
58
|
+
code: 'missing_field',
|
|
59
|
+
message: 'Field html is required',
|
|
60
|
+
field: 'html',
|
|
61
|
+
}));
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const fields = firstValues(form, fieldsMultiple);
|
|
65
|
+
const expires = fields.expires;
|
|
66
|
+
if (typeof expires !== 'string' || !/^\d+$/.test(expires)) {
|
|
67
|
+
reject(new SimpleError({ code: 'invalid_signature', message: 'Missing expiration', statusCode: 403 }));
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (!fields.signature || typeof fields.signature !== 'string') {
|
|
71
|
+
reject(new SimpleError({
|
|
72
|
+
code: 'missing_field',
|
|
73
|
+
message: 'Field signature is required',
|
|
74
|
+
field: 'signature',
|
|
75
|
+
}));
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (!fields.cacheId || typeof fields.cacheId !== 'string') {
|
|
79
|
+
reject(new SimpleError({
|
|
80
|
+
code: 'missing_field',
|
|
81
|
+
message: 'Field cacheId is required',
|
|
82
|
+
field: 'cacheId',
|
|
83
|
+
}));
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (!fields.timestamp || typeof fields.timestamp !== 'string') {
|
|
87
|
+
reject(new SimpleError({
|
|
88
|
+
code: 'missing_field',
|
|
89
|
+
message: 'Field timestamp is required',
|
|
90
|
+
field: 'timestamp',
|
|
91
|
+
}));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
let html;
|
|
95
|
+
try {
|
|
96
|
+
html = await fs.readFile(files.html[0].filepath, 'utf8');
|
|
97
|
+
}
|
|
98
|
+
catch (e) {
|
|
99
|
+
reject(new SimpleError({
|
|
100
|
+
code: 'invalid_field',
|
|
101
|
+
message: 'Could not read html',
|
|
102
|
+
field: 'html',
|
|
103
|
+
}));
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
resolve({
|
|
107
|
+
html,
|
|
108
|
+
expires,
|
|
109
|
+
signature: fields.signature,
|
|
110
|
+
cacheId: fields.cacheId,
|
|
111
|
+
timestamp: new Date(parseInt(fields.timestamp)),
|
|
112
|
+
});
|
|
113
|
+
return;
|
|
114
|
+
});
|
|
115
|
+
}).finally(async () => {
|
|
116
|
+
// A private directory also covers partial files omitted from failed parse results.
|
|
117
|
+
await fs.rm(uploadDir, { recursive: true, force: true });
|
|
118
|
+
});
|
|
119
|
+
// Verify signature first
|
|
120
|
+
if (Number(expires) <= Date.now() || Number(expires) > Date.now() + 60000
|
|
121
|
+
|| !verifyInternalSignature(signature, 'html-to-pdf', cacheId, timestamp.getTime().toString(), expires, html)) {
|
|
122
|
+
throw new SimpleError({
|
|
123
|
+
code: 'invalid_signature',
|
|
124
|
+
message: 'Invalid signature',
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
let pdf = null;
|
|
128
|
+
try {
|
|
129
|
+
pdf = await this.htmlToPdf(html, { retryCount: 2, startDate: new Date() });
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
console.error(e);
|
|
133
|
+
}
|
|
134
|
+
if (!pdf) {
|
|
135
|
+
throw new SimpleError({
|
|
136
|
+
code: 'internal_error',
|
|
137
|
+
message: 'Could not generate pdf',
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
await FileCache.write(cacheId, timestamp, pdf);
|
|
141
|
+
const response = new Response(pdf);
|
|
142
|
+
response.headers['Cache-Control'] = 'no-store';
|
|
143
|
+
response.headers['Content-Type'] = 'application/pdf';
|
|
144
|
+
response.headers['Content-Length'] = pdf.byteLength.toString();
|
|
145
|
+
return response;
|
|
146
|
+
}
|
|
147
|
+
static browsers = [null, null, null, null];
|
|
148
|
+
static nextBrowserIndex = 0;
|
|
149
|
+
static async useBrowser(callback) {
|
|
150
|
+
console.log('Requesting browser');
|
|
151
|
+
this.nextBrowserIndex++;
|
|
152
|
+
if (this.nextBrowserIndex >= this.browsers.length) {
|
|
153
|
+
this.nextBrowserIndex = 0;
|
|
154
|
+
}
|
|
155
|
+
return await QueueHandler.schedule('getBrowser' + this.nextBrowserIndex, async () => {
|
|
156
|
+
if (!this.browsers[this.nextBrowserIndex]) {
|
|
157
|
+
this.browsers[this.nextBrowserIndex] = { browser: await puppeteer.launch({}), count: 0 };
|
|
158
|
+
}
|
|
159
|
+
const browser = this.browsers[this.nextBrowserIndex];
|
|
160
|
+
if (browser.count > 50 || !browser.browser.connected) {
|
|
161
|
+
try {
|
|
162
|
+
await browser.browser.close();
|
|
163
|
+
}
|
|
164
|
+
catch (e) {
|
|
165
|
+
console.error(e);
|
|
166
|
+
}
|
|
167
|
+
this.browsers[this.nextBrowserIndex] = { browser: await puppeteer.launch({}), count: 0 };
|
|
168
|
+
}
|
|
169
|
+
return await callback(browser.browser);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
static async clearBrowser(browser) {
|
|
173
|
+
try {
|
|
174
|
+
await browser.close();
|
|
175
|
+
}
|
|
176
|
+
catch (e) {
|
|
177
|
+
console.error(e);
|
|
178
|
+
}
|
|
179
|
+
const i = this.browsers.findIndex(b => b?.browser === browser);
|
|
180
|
+
if (i >= 0) {
|
|
181
|
+
this.browsers[i] = null;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* This will move to a different external service
|
|
186
|
+
*/
|
|
187
|
+
async htmlToPdf(html, options) {
|
|
188
|
+
const response = await HtmlToPdfEndpoint.useBrowser(async (browser) => {
|
|
189
|
+
try {
|
|
190
|
+
// Create a new page
|
|
191
|
+
const page = await browser.newPage();
|
|
192
|
+
await page.setJavaScriptEnabled(false);
|
|
193
|
+
await page.emulateMediaType('screen');
|
|
194
|
+
await page.setContent(html, { waitUntil: 'load' });
|
|
195
|
+
// Downlaod the PDF
|
|
196
|
+
const pdf = await page.pdf({
|
|
197
|
+
// path: directory + this.id + '.pdf',
|
|
198
|
+
margin: { top: '50px', right: '50px', bottom: '50px', left: '50px' },
|
|
199
|
+
printBackground: true,
|
|
200
|
+
format: 'A4',
|
|
201
|
+
preferCSSPageSize: true,
|
|
202
|
+
displayHeaderFooter: false,
|
|
203
|
+
});
|
|
204
|
+
await page.close();
|
|
205
|
+
console.log('Rendered document pdf');
|
|
206
|
+
return pdf;
|
|
207
|
+
}
|
|
208
|
+
catch (e) {
|
|
209
|
+
console.error('Failed to render document pdf', e);
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
if (response === null && options.retryCount > 0 && new Date().getTime() - options.startDate.getTime() < 15000) {
|
|
214
|
+
// Retry
|
|
215
|
+
return await this.htmlToPdf(html, { ...options, retryCount: options.retryCount - 1 });
|
|
216
|
+
}
|
|
217
|
+
return response;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
//# sourceMappingURL=HtmlToPdfEndpoint.js.map
|