encrypt-cookie
TypeScript icon, indicating that this package has built-in type declarations

1.1.5 • Public • Published

encrypt-cookie

npm npm code style: prettier TypeScript

Easy to use cookie encryption middleware for express and socket.io

Installation

npm install --save encrypt-cookie
yarn add encrypt-cookie

Features

  • Strong encryption AES 256 GCM
  • Derive unique encryption key for each cookie from master
  • Node.js middleware
  • Socket.io middleware

Node Express middleware

The express middleware automatically encrypts and decrypts the cookies.

import express from 'express';
import cookieParser from 'cookie-parser';
import { encryptCookieNodeMiddleware } from 'encrypt-cookie';
 
const expressApp = express();
expressApp.use(cookieParser(signatureSecret));
expressApp.use(encryptCookieNodeMiddleware(encryptionSecret));
 
// Set new cookie as usual
response.cookie(cookieName, cookieValue, cookieOptions);

Socket.io middleware

The middleware for socket.io just parses and decrypts the cookies. Since there exist no HTTP response you can not set any headers to submit new cookie values to the browser. The socket handshake includes the cookie values that exist when the handshake is created. To include newer cookies, you need to reset the socket connection. (Any workaround?)

import socketIO from 'socket.io';
import { decryptCookieSocketMiddleware } from 'encrypt-cookie';
 
this.httpServer = http.createServer(this.expressApp);
this.socketServer = socketIO(this.httpServer); // often defined as `io`
this.socketServer.use(decryptCookieSocketMiddleware(signatureSecret, encryptionSecret));
 
 

Set cookie with socket.io

The new cookie value only remains in the current handshake. It will not be submitted to the browsers cookie cache. The value will be deleted when the handshake is recreated.

cookieOptions will be mostly ignored, because the socked does not include any meta information about the cookies. Currently the only noticed value for cookieOptions is {sign: true} to sign the cookie.

import { setSocketCookie } from 'encrypt-cookie';
 
const cookieOptions = {sign: true};
setSocketCookie(socketSocketIO.Socket, signaturePasswordstring, cookieNamestring, cookieValueany, cookieOptionsexpress.CookieOptions)void

Encryption/Decryption methods

You can access the encryption methods to use it anywhere

import { decryptAesGcm, encryptAesGcm } from 'encrypt-cookie';
 
type Password = string | Buffer | NodeJS.TypedArray | DataView;
 
decryptAesGcm(cipherTextstring, passwordPassword)string | undefined
encryptAesGcm(plainTextstring | object, passwordPassword)string | undefined
 

Package Sidebar

Install

npm i encrypt-cookie

Weekly Downloads

28

Version

1.1.5

License

MIT

Unpacked Size

29.2 kB

Total Files

21

Last publish

Collaborators

  • btxtiger