From 1862aa6bb3cb4ae3b66e1f5d176d770126e22037 Mon Sep 17 00:00:00 2001 From: LoneRifle Date: Thu, 15 Aug 2024 11:10:42 +0800 Subject: [PATCH] chore: silence spurious error --- .../src/app/loaders/express/helmet.ts | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 replacements/src/app/loaders/express/helmet.ts diff --git a/replacements/src/app/loaders/express/helmet.ts b/replacements/src/app/loaders/express/helmet.ts new file mode 100644 index 0000000..42283b7 --- /dev/null +++ b/replacements/src/app/loaders/express/helmet.ts @@ -0,0 +1,65 @@ +import crypto from 'crypto' +import { RequestHandler } from 'express' +import helmet from 'helmet' + +import config from '../../config/config' + +import { CSP_CORE_DIRECTIVES } from './constants' + +const helmetMiddlewares = () => { + // Only add the "Strict-Transport-Security" header if request is https. + const hstsMiddleware: RequestHandler = (req, res, next) => { + if (req.secure) { + helmet.hsts({ maxAge: 400 * 24 * 60 * 60 })(req, res, next) // 400 days + } else next() + } + + const generateNonceMiddleware: RequestHandler = (req, res, next) => { + res.locals.nonce = + res.locals.nonce || crypto.randomBytes(32).toString('hex') + + next() + } + const xssFilterMiddleware = helmet.xssFilter() + + const noSniffMiddleware = helmet.noSniff() + + const ieNoOpenMiddlware = helmet.ieNoOpen() + + const dnsPrefetchControlMiddleware = helmet.dnsPrefetchControl() + + const hidePoweredByMiddleware = helmet.hidePoweredBy() + + const referrerPolicyMiddleware = helmet.referrerPolicy({ + policy: 'strict-origin-when-cross-origin', + }) + + const cspCoreDirectives = CSP_CORE_DIRECTIVES + + const cspOptionalDirectives = config.isDev + ? // Remove upgradeInsecureRequest CSP header if config.isDev + // See https://github.com/helmetjs/helmet for use of null to disable default + { upgradeInsecureRequests: null } + : null + + const contentSecurityPolicyMiddleware = helmet.contentSecurityPolicy({ + useDefaults: true, + directives: { + ...cspCoreDirectives, + ...cspOptionalDirectives, + }, + }) + return [ + generateNonceMiddleware, + xssFilterMiddleware, + noSniffMiddleware, + ieNoOpenMiddlware, + dnsPrefetchControlMiddleware, + hidePoweredByMiddleware, + hstsMiddleware, + referrerPolicyMiddleware, + contentSecurityPolicyMiddleware, + ] +} + +export default helmetMiddlewares