From 04a8163db6b2ac3e1afd68cf11a0301274a95d5e Mon Sep 17 00:00:00 2001 From: ljeda Date: Sun, 12 Jan 2025 02:02:46 +0100 Subject: [PATCH 1/2] conditionally set headers (if not already set) in redirect response --- index.js | 16 +++++++++++----- test/test.js | 12 +++++++++++- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index 1bee463..5a86b42 100644 --- a/index.js +++ b/index.js @@ -198,11 +198,17 @@ function createRedirectDirectoryListener () { // send redirect response res.statusCode = 301 - res.setHeader('Content-Type', 'text/html; charset=UTF-8') - res.setHeader('Content-Length', Buffer.byteLength(doc)) - res.setHeader('Content-Security-Policy', "default-src 'none'") - res.setHeader('X-Content-Type-Options', 'nosniff') - res.setHeader('Location', loc) + setHeaderIfNotSet(res, 'Content-Type', 'text/html; charset=UTF-8') + setHeaderIfNotSet(res, 'Content-Length', Buffer.byteLength(doc)) + setHeaderIfNotSet(res, 'Content-Security-Policy', "default-src 'none'") + setHeaderIfNotSet(res, 'X-Content-Type-Options', 'nosniff') + setHeaderIfNotSet(res, 'Location', loc) res.end(doc) } } + +function setHeaderIfNotSet (res, name, value) { + if (!res.hasHeader(name)) { + res.setHeader(name, value) + } +} diff --git a/test/test.js b/test/test.js index 6984bcd..4a3ac85 100644 --- a/test/test.js +++ b/test/test.js @@ -469,6 +469,9 @@ describe('serveStatic()', function () { before(function () { server = createServer(fixtures, null, function (req, res) { req.url = req.url.replace(/\/snow(\/|$)/, '/snow \u2603$1') + if (req.url.match(/\/pets/)) { + res.setHeader('Content-Security-Policy', "default-src 'self'") + } }) }) @@ -508,13 +511,20 @@ describe('serveStatic()', function () { .expect(301, />Redirecting to \/snow%20%E2%98%83\/ Date: Sun, 12 Jan 2025 02:09:59 +0100 Subject: [PATCH 2/2] add new function description --- index.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/index.js b/index.js index 5a86b42..a7d0083 100644 --- a/index.js +++ b/index.js @@ -207,6 +207,11 @@ function createRedirectDirectoryListener () { } } +/** + * Set default value for the header only if it is not already set in the response + * @private + */ + function setHeaderIfNotSet (res, name, value) { if (!res.hasHeader(name)) { res.setHeader(name, value)