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

feat: Check whether the value is legal Before setting the header #72

Open
wants to merge 4 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
9 changes: 7 additions & 2 deletions lib/middlewares/csp.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,12 @@ module.exports = options => {
}
}
const headerString = bufArray.join(';');
ctx.set(finalHeader, headerString);
ctx.set('x-csp-nonce', ctx.nonce);

if (!utils.checkInvalidHeaderChar(headerString)) {
ctx.set(finalHeader, headerString);
ctx.set('x-csp-nonce', ctx.nonce);
} else {
console.warn('Invalid character in header content :', finalHeader);
}
};
};
6 changes: 6 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,9 @@ function getContains(ip) {
}
return IP.cidrSubnet(ip).contains;
}

const HEADER_CHAR_REGEX = /[^\t\x20-\x7e\x80-\xff]/;

exports.checkInvalidHeaderChar = function(val) {
return HEADER_CHAR_REGEX.test(val);
};
13 changes: 13 additions & 0 deletions test/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,4 +251,17 @@ describe('test/utils.test.js', function() {
});
});
});

describe('utils.checkInvalidHeaderChar', function() {
it('Invalid character return true', function() {
utils.checkInvalidHeaderChar('aaaaa\naaaaaa').should.equal(true);
utils.checkInvalidHeaderChar('aaaa\raaaaa').should.equal(true);
});

it('character return false', function() {
utils.checkInvalidHeaderChar('aaaaa').should.equal(false);
utils.checkInvalidHeaderChar('aaaa aaaaa').should.equal(false);
utils.checkInvalidHeaderChar('aaaaaaaaa').should.equal(false);
});
});
});