Skip to content

Instantly share code, notes, and snippets.

@rspieker
Created August 24, 2015 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rspieker/8ab68c383c95fe3e306a to your computer and use it in GitHub Desktop.
Save rspieker/8ab68c383c95fe3e306a to your computer and use it in GitHub Desktop.
Hapi - allow for the CSP 2.0 'application/csp-report' content-type
'use strict';
var Hapi = require('hapi'),
server = new Hapi.Server();
server.connection({ port: 80 });
// Example #1, simply override the content-type header and trust the input
server.route({
path: '/csp/report/1',
method: 'POST',
config: {
payload: {
override: 'application/json'
}
},
handler: function(request, reply) {
// write the CSP-Report to the console
console.info('CSP-Report', request.payload);
reply(200);
}
});
// Example #2, check the content-type header and indicate the version in the output
server.route({
path: '/csp/report/2',
method: 'POST',
config: {
payload: {
parse: false
}
},
handler: function(request, reply) {
var type = request.headers['content-type'].match(/^application\/(csp-report|json)$/),
version = type ? (type[1] === 'csp-report' ? 2 : 1) : null,
data = type ? JSON.parse(String(request.payload)) : null;
if (!type) {
throw new Error('Unknown content-type: ' + request.headers['content-type']);
}
else if (!data) {
throw new Error('Could not parse payload as JSON: ' + request.payload);
}
// write the CSP-Report to the console along with the user-agent (which determined the CSP version) and version
console.info('CSP-Report', {
'user-agent': request.headers['user-agent'],
version: version,
data: data
});
reply(200);
}
});
server.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment