Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

conditionally set headers (if not already set) in redirect response #190

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,22 @@ 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)
}
}

/**
* 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)
}
}
12 changes: 11 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'")
}
})
})

Expand Down Expand Up @@ -508,13 +511,20 @@ describe('serveStatic()', function () {
.expect(301, />Redirecting to \/snow%20%E2%98%83\/</, done)
})

it('should respond with default Content-Security-Policy', function (done) {
it('should respond with default Content-Security-Policy when header is not set', function (done) {
request(server)
.get('/users')
.expect('Content-Security-Policy', "default-src 'none'")
.expect(301, done)
})

it('should respond with custom Content-Security-Policy when header is set', function (done) {
request(server)
.get('/pets')
.expect('Content-Security-Policy', "default-src 'self'")
.expect(301, done)
})

it('should not redirect incorrectly', function (done) {
request(server)
.get('/')
Expand Down