CSRF crumb generation and validation for hapi
Lead Maintainer: Marcus Stong
Crumb is used to diminish CSRF attacks using a random unique token that is validated on the server side.
Crumb may be used whenever you want to prevent malicious code to execute system commands, that are performed by HTTP requests. For example, if users are able to publish code on your website, malicious code added by a user could force every other user who opens the page, to load and execute code from a third party website e.g. via an HTML image tag. With Crumb implemented into your hapi.js application, you are able to verify requests with unique tokens and prevent the execution of malicious requests.
Crumb has been refactored to securely work with CORS, as OWASP recommends using CSRF protection with CORS.
It is highly discouraged to have a production servers cors.origin
setting set to "[*]" or "true" with Crumb as it will leak the crumb token to potentially malicious sites
const Hapi = require('hapi');
const Crumb = require('crumb');
const server = new Hapi.Server();
server.connection({ port: 8000 });
server.register({
register: crumb,
// plugin options
options: {}
});
server.route({
path: '/login',
method: 'GET',
config: {
plugins: {
// route specific options
crumb: {}
},
handler(request, reply) {
// this requires to have a view engine configured
return reply.view('some-view');
}
}
});
For a complete example see the examples folder.
The following options are available when registering the plugin.
key
- the name of the cookie to store the csrf crumb into. Defaults tocrumb
.size
- the length of the crumb to generate. Defaults to43
, which is 256 bits, see cryptile for more information.autoGenerate
- whether to automatically generate a new crumb for requests. Defaults totrue
.addToViewContext
- whether to automatically add the crumb to view contexts as the given key. Defaults totrue
.cookieOptions
- storage options for the cookie containing the crumb, see the server.state documentation of hapi for more information. Default tocookieOptions.path=/
restful
- RESTful mode that validates crumb tokens from "X-CSRF-Token" request header for POST, PUT, PATCH and DELETE server routes. Disables payload/query crumb validation. Defaults tofalse
.skip
- a function with the signature offunction (request, reply) {}
, which when provided, is called for every request. If the provided function returns true, validation and generation of crumb is skipped. Defaults tofalse
.
Additionally, some configuration can be passed on a per-route basis.
key
- the key used in the view contexts and payloads for the crumb. Defaults toplugin.key
.source
- can be eitherpayload
orquery
specifying how the crumb will be sent in requests. Defaults topayload
.restful
- an override for the server's 'restful' setting. Defaults toplugin.restful
.