Skip to content
Create a secure stateless cookie session for Fastify
JavaScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
test Add malformed cookie detection May 26, 2019
.gitignore
.travis.yml Updated deps. Added Node 12 to travis May 27, 2019
LICENSE Initial commit Dec 3, 2017
README.md bug in checking salt length is fixed Mar 24, 2019
example-key Added static key generation and usage Dec 5, 2017
example.js Updated dependencies Sep 2, 2018
genkey.js Bumped dependencies and fixed genkey Jun 29, 2018
index.js
package.json

README.md

fastify-secure-session

Create a secure stateless cookie session for Fastify, based on libsodium's Secret Key Box Encryption and fastify-cookie.

Using a pregenerated key

First generate a key with:

./node_modules/.bin/secure-session-gen-key > secret-key

Then, register the plugin as follows:

'use strict'

const fastify = require('fastify')({ logger: false })
const fs = require('fs')
const path = require('path')

fastify.register(require('./'), {
  // adapt this to point to the directory where secret-key is located
  key: fs.readFileSync(path.join(__dirname, 'secret-key')),
  cookie: {
    // options from setCookie, see https://github.com/fastify/fastify-cookie
  }
})

fastify.post('/', (request, reply) => {
  request.session.set('data', request.body)
  reply.send('hello world')
})

fastify.get('/', (request, reply) => {
  const data = request.session.get('data')
  if (!data) {
    reply.code(404).send()
    return
  }
  reply.send(data)
})

fastify.post('/logout', (request, reply) => {
  request.session.delete()
  reply.send('logged out')
})

Using a secret

It's possible to generate a high-entropy key from a (low-entropy) secret passphrase. This approach is the simplest to use, but it adds a significant startup delay as strong cryptography is applied.

const fastify = require('fastify')({ logger: false })

fastify.register(require('./'), {
  secret: 'averylogphrasebiggerthanthirtytwochars',
  salt: 'mq9hDxBVDbspDR6n',
  cookie: {
    // options from setCookie, see https://github.com/fastify/fastify-cookie
  }
})

fastify.post('/', (request, reply) => {
  request.session.set('data', request.body)
  reply.send('session set')
})

fastify.get('/', (request, reply) => {
  const data = request.session.get('data')
  if (!data) {
    reply.code(404).send()
    return
  }
  reply.send(data)
})

fastify.listen(3000)

TODO

  • add an option to just sign, and do not encrypt

License

MIT

You can’t perform that action at this time.