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

1.1.1 • Public • Published

xsurf

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

A performant, zero-dependency Node.js utility for generating and validating CSRF tokens, written entirely in Typescript.

Token creation and verification logic is based on this specification.

Installation

Via npm:

npm i xsurf

Via yarn:

yarn add xsurf

Middlewares and plugins

Want to integrate CSRF protection middleware into your framework of choice? These middlewares use xsurf:

Usage API

createToken(length?: number)

Synchronously creates a CSRF token of the specified length (32 bytes by default) to be stored in a cookie and copied to the request header on the client.

const token = createToken();
request.setCookie('x-csrf-token', token);
// Create token with 64 bytes of random data
const token = createToken(64);

createTokenAsync(length?: number): Promise<string>

Asynchronous version of createToken(). Should only be used in niche scenarios because the underlying async crypto.randomBytes() call tends to sacrifice crypto ops/sec in favor of js ops/sec, leading to generally poorer performance.

async function handle() {
  const token = await createToken();
  // Do something with token
}

createChecksum(token: string, secret: string): string

Generate a checksum of the CSRF token using an HMAC SHA256 digest of the token and secret. This value should be stored in an httpOnly cookie and be used to verify incoming requests.

const secret = process.env.CSRF_SECRET;
const token = request.cookies['x-csrf-token'];
// Make checksum and store in a cookie
const checksum = createChecksum(token, secret);
request.setCookie('x-csrf-checksum', checksum);

verifyChecksum(token: string, checksum: string, secret: string): boolean

Verify the validity the provided token against the true checksum using a time-safe comparison. The provided token should originate from the HTTP request header while the checksum should be read from the httpOnly cookie.

const secret = process.env.CSRF_SECRET;
const headerToken = request.headers['x-csrf-token'];
// Validate the request header token by comparing its
// checksum to the true checksum stored in a cookie
const checksum = request.cookies['x-csrf-checksum'];
const valid = verifyChecksum(headerToken, checksum, secret);

License

MIT License

Package Sidebar

Install

npm i xsurf

Weekly Downloads

11

Version

1.1.1

License

MIT

Unpacked Size

12.3 kB

Total Files

9

Last publish

Collaborators

  • danielhzhang