Blame Raw
Cohee · 51ad27fb · · 45 lines (2.0 KB)
1 contributor
1import path from 'node:path';
2import { color, getConfigValue, safeReadFileSync } from '../util.js';
3import { isHostAllowed, hostValidationMiddleware } from 'host-validation-middleware';
4
5const knownHosts = new Set();
6const maxKnownHosts = 1000;
7
8const hostWhitelistEnabled = !!getConfigValue('hostWhitelist.enabled', false);
9const hostWhitelist = Object.freeze(getConfigValue('hostWhitelist.hosts', []));
10const hostWhitelistScan = !!getConfigValue('hostWhitelist.scan', false, 'boolean');
11
12const validationMiddleware = hostValidationMiddleware({
13 allowedHosts: hostWhitelist,
14 generateErrorMessage: () => safeReadFileSync(path.join(globalThis.DATA_ROOT, '_errors', 'host-not-allowed.html'))?.toString() ?? '',
15 errorResponseContentType: 'text/html',
16});
17
18/**
19 * Middleware to validate remote hosts.
20 * Useful to protect against DNS rebinding attacks.
21 * @param {import('express').Request} req Request
22 * @param {import('express').Response} res Response
23 * @param {import('express').NextFunction} next Next middleware
24 */
25export default function hostWhitelistMiddleware(req, res, next) {
26 const hostValue = req.headers.host;
27 if (hostWhitelistScan && !isHostAllowed(hostValue, hostWhitelist) && !knownHosts.has(hostValue) && knownHosts.size < maxKnownHosts) {
28 const isFirstWarning = knownHosts.size === 0;
29 console.warn(color.red('Request from untrusted host:'), hostValue);
30 console.warn(`If you trust this host, you can add it to ${color.yellow('hostWhitelist.hosts')} in config.yaml`);
31 if (!hostWhitelistEnabled && isFirstWarning) {
32 console.warn(`To protect against host spoofing, consider setting ${color.yellow('hostWhitelist.enabled')} to true`);
33 }
34 if (isFirstWarning) {
35 console.warn(`To disable this warning, set ${color.yellow('hostWhitelist.scan')} to false`);
36 }
37 knownHosts.add(hostValue);
38 }
39
40 if (!hostWhitelistEnabled) {
41 return next();
42 }
43
44 return validationMiddleware(req, res, next);
45}