npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sortdinc/csrf-csrf

v3.0.4

Published

A utility package to help implement stateless CSRF protection using the Double Submit Cookie Pattern in express.

Downloads

75

Readme

npm install cookie-parser csrf-csrf
// ESM
import { doubleCsrf } from "csrf-csrf";

// CommonJS
const { doubleCsrf } = require("csrf-csrf");
const {
  invalidCsrfTokenError, // This is just for convenience if you plan on making your own middleware.
  generateToken, // Use this in your routes to provide a CSRF hash + token cookie and token.
  validateRequest, // Also a convenience if you plan on making your own middleware.
  doubleCsrfProtection, // This is the default CSRF protection middleware.
} = doubleCsrf(doubleCsrfOptions);
const myRoute = (req, res) => {
  const csrfToken = generateToken(req, res);
  // You could also pass the token into the context of a HTML response.
  res.json({ csrfToken });
};
const myProtectedRoute = (req, res) =>
  res.json({ unpopularOpinion: "Game of Thrones was amazing" });
request.csrfToken(); // same as generateToken(req, res);
// Make sure your session middleware is registered before these
express.use(session);
express.get("/csrf-token", myRoute);
express.use(doubleCsrfProtection);
// Any non GET routes registered after this will be considered "protected"
app.get("/secret-stuff", doubleCsrfProtection, myProtectedRoute);
(req, res, next) => {
  getCsrfTokenAsync(req)
    .then((token) => {
      req.asyncCsrfToken = token;
      next();
    })
    .catch((error) => next(error));
};
(req) => req.asyncCsrfToken;

When creating your doubleCsrf, you have a few options available for configuration, the only required option is getSecret, the rest have sensible defaults (shown below).

const doubleCsrfUtilities = doubleCsrf({
  getSecret: () => "Secret", // A function that optionally takes the request and returns a secret
  cookieName: "__Host-psifi.x-csrf-token", // The name of the cookie to be used, recommend using Host prefix.
  cookieOptions: {
    sameSite = "lax",  // Recommend you make this strict if posible
    path = "/",
    secure = true,
    ...remainingCookieOptions // See cookieOptions below
  },
  size: 64, // The size of the generated tokens in bits
  ignoredMethods: ["GET", "HEAD", "OPTIONS"], // A list of request methods that will not be protected.
  getTokenFromRequest: (req) => req.headers["x-csrf-token"], // A function that returns the token from the request
});
(request?: Request) => string | string[]
string;
{
  sameSite?: string;
  path?: string;
  secure?: boolean
  ...remainingCookieOptions // See below.
}
{
  sameSite: "lax",
  path: "/",
  secure: true
}
  maxAge?: number | undefined;
  signed?: boolean | undefined;
  expires?: Date | undefined;
  domain?: string | undefined;
  encode?: (val: string) => string
(req: Request) => string | null | undefined;
(req: Request) => req.headers["x-csrf-token"];
Array<RequestMethod>;
number;
(request: Request, response: Response, next: NextFunction) => void
(
  request: Request,
  response: Response,
  overwrite?: boolean, // Set to true to force a new token to be generated
  validateOnReuse?: boolean, // Set to false to generate a new token if token re-use is invalid
) => string;
generateToken(req, res, true); // This will force a new token to be generated, and a new cookie to be set, even if one already exists
generateToken(req, res, true); // As overwrite is true, an error will never be thrown.
generateToken(req, res, false); // As validateOnReuse is true (default), an error will be thrown if the cookie is invalid.
generateToken(req, res, false, false); // As validateOnReuse is false, an error will never be thrown, even if the cookie is invalid. Instead, a new cookie will be generated if it is found to be invalid.
req.csrfToken(); // same as generateToken(req, res) and generateToken(req, res, false);
req.csrfToken(true); // same as generateToken(req, res, true);
req.csrfToken(false, false); // same as generateToken(req, res, false, false);
(req: Request) => boolean;