fastify-xsurf

A Fastify plugin that adds CSRF protection to HTTP routes

Usage no npm install needed!

<script type="module">
  import fastifyXsurf from 'https://cdn.skypack.dev/fastify-xsurf';
</script>

README

fastify-xsurf

NPM Version Node.js Version NPM Downloads Node.js CI

A plugin for Fastify that adds CSRF protection to HTTP routes.

This plugin uses xsurf for generating CSRF tokens and their respective checksums. The anti-CSRF protection scheme follows this specification.

Installation

Via npm:

npm i fastify-xsurf

Via yarn:

yarn add fastify-xsurf

Usage API

This plugin does not decorate fastify's request or reply with new methods.

To validate CSRF tokens for all routes, simply register the plugin once after fastify-cookie. Only the routes using the HTTP methods specified in options.ignoredMethods will be excluded from validation.

With CommonJS require syntax:

fastify.register(require('fastify-cookie'));
fastify.register(require('fastify-xsurf'), {
  /*...options */
});

With ES module import syntax:

import cookiePlugin from 'fastify-cookie';
import csrfPlugin from 'fastify-xsurf';

fastify.register(cookiePlugin);
fastify.register(csrfPlugin, {
  /* ...options */
});

To validate CSRF tokens on only specific routes, set validateOnRequest: false on the options object:

fastify.register(csrfPlugin, {
  validateOnRequest: false,
});

A validate function will then be exposed at the property fastify.validateCsrf, which can be called on individual onRequest hooks:

fastify.route({
  method: 'POST',
  path: '/',
  onRequest: async (req, reply) => {
    fastify.validateCsrf(req, reply);
    /* ...other onRequest hook handlers */
  }
  handler: async (req, reply) => {
    // ...route handler
  }
})

On the browser client, ensure that the most recent value of the csrfToken cookie is used and copied to of the following headers (case sensitive) for each protected request: x-csrf-token, csrf-token, xsrf-token, or x-xsrf-token.

// Get token from cookies
const token = /(?:^|;\s*)csrfToken=([^;]+)/.exec(document.cookie)?.[1];
fetch(url, {
  method: 'POST',
  headers: {
    'x-csrf-token': token, // copy token to header
  },
});

Options (object)

Typescript users: options type is exported as CsrfPluginOptions.

options.secret (string)

Shared secret used to create the token checksum.

options.validateOnRequest (boolean)

Validate CSRF tokens on all requests to the server. If set to false, a validate function is exposed at the property fastify.validateCsrf, which can be called on an individual route's onRequest hook.

  • Optional
  • Default: true

options.ignoreMethods (string[])

Methods to ignore checking for a CSRF token.

  • Optional
  • Default: ['GET', 'HEAD', 'OPTIONS']

options.tokenKey (string)

Cookie key to store the CSRF token.

  • Optional
  • Default: 'csrfToken'

options.checksumKey (string)

Cookie key to store the token checksum. Defaults to 'csrfChecksum'

  • Optional
  • Default: 'csrfChecksum'

options.errorMessage (string)

Error message that will be sent in response to the client with invalid tokens.

  • Optional
  • Default: 'Invalid CSRF token provided.'

options.cookie (object)

Cookie options from fastify-cookie. Will override defaults on both the token and checksum cookies.

// csrfToken cookie
{
  path: '/',
  sameSite: 'strict',
}

// csrfChecksum cookie
{
  path: '/',
  sameSize: 'strict',
  httpOnly: true,
}

License

MIT License