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 🙏

© 2026 – Pkg Stats / Ryan Hefner

salad-csrf

v1.0.0

Published

CSRF protection middleware for Express with preauth/auth scopes.

Readme

salad-csrf

Lightweight CSRF protection middleware for Express with pre-auth and auth scopes.

Install

npm install salad-csrf

Set a secret in your environment:

CSRF_SECRET="your-strong-secret"

Usage (ESM)

import express from "express";
import cookieParser from "cookie-parser";
import {
  init,
  csrfTokenHandler,
  preAuthScopeResolver,
  authScopeResolver,
  requireCsrf,
} from "salad-csrf";

const app = express();
app.use(cookieParser());

init({
  ttl: 60 * 15,
  cookieName: "csrf",
  sessionContext: {
    getSessionId: (req) => req.user?.id,
  },
  isProd: process.env.NODE_ENV === "production",
});

app.get("/csrf", csrfTokenHandler(preAuthScopeResolver));
app.post("/preauth-action", requireCsrf("preauth"), (req, res) => {
  res.json({ ok: true });
});

app.get("/auth-csrf", csrfTokenHandler(authScopeResolver()));
app.post("/auth-action", requireCsrf("auth"), (req, res) => {
  res.json({ ok: true });
});

Usage (CommonJS)

const express = require("express");
const cookieParser = require("cookie-parser");
const {
  init,
  csrfTokenHandler,
  preAuthScopeResolver,
  authScopeResolver,
  requireCsrf,
} = require("salad-csrf");

const app = express();
app.use(cookieParser());

init({
  ttl: 60 * 15,
  cookieName: "csrf",
  sessionContext: {
    getSessionId: (req) => req.user?.id,
  },
  isProd: process.env.NODE_ENV === "production",
});

app.get("/csrf", csrfTokenHandler(preAuthScopeResolver));
app.post("/preauth-action", requireCsrf("preauth"), (req, res) => {
  res.json({ ok: true });
});

app.get("/auth-csrf", csrfTokenHandler(authScopeResolver()));
app.post("/auth-action", requireCsrf("auth"), (req, res) => {
  res.json({ ok: true });
});

How it works

  • A CSRF binding cookie is set (HTTP-only, SameSite=Lax).
  • A CSRF token is issued with:
    • hash: SHA-256 of the binding cookie
    • scope: preauth or auth
    • exp: expiry (seconds since epoch)
    • sid: hashed session ID for auth scope
  • On protected requests, the token in x-csrf-token is validated against the cookie and (for auth) the session ID.

API

init({ ttl, cookieName, sessionContext, isProd })

Required:

  • ttl (number, seconds)

Optional:

  • cookieName (string, defaults to csrf_default)
  • sessionContext (object with getSessionId(req) for auth scope)
  • isProd (boolean)

Behavior:

  • When isProd is true, any validation or runtime errors returned to the client are masked as PERMISSION DENIED.
  • When isProd is false, exact error messages are returned to help debugging.

csrfTokenHandler(scopeResolver)

Returns an Express handler that:

  • Ensures the CSRF binding cookie exists.
  • Issues a token based on the provided scope resolver.
  • Responds with { csrfToken }.

preAuthScopeResolver

Resolver for pre-auth scope:

csrfTokenHandler(preAuthScopeResolver)

authScopeResolver()

Resolver for auth scope:

csrfTokenHandler(authScopeResolver())

Requires sessionContext.getSessionId(req) to return a session identifier.

requireCsrf(scope)

Express middleware that validates CSRF tokens on unsafe methods (POST, PUT, PATCH, DELETE). Safe methods (GET, HEAD, OPTIONS) bypass CSRF validation.

Example:

app.post("/protected", requireCsrf("preauth"), handler);

Client usage

  1. Fetch a CSRF token:
curl -c cookie.txt http://localhost:3000/csrf
  1. Send it back on unsafe requests:
curl -b cookie.txt -H "x-csrf-token: <token>" -X POST http://localhost:3000/preauth-action

Tests

npm test

Build

npm run build

Notes

  • You must set CSRF_SECRET in the environment before issuing or validating tokens.
  • Ensure cookie-parser is registered before these handlers so req.cookies is available.
  • Consider HTTPS in production so secure cookies are sent.