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

tiny-csrf

v1.1.4

Published

Tiny CSRF library for use with ExpressJS

Downloads

3,130

Readme

tiny-csrf

Downloads

This is a tiny csrf library meant to replace what csurf used to do before it was deleted. It is almost a drop-in replacement.

Notice that if you require very specific security needs you may want to look elsewhere. This library supports encrypting cookies on the client side to prevent malicious attackers from looking in but this may not be sufficient in some cases. For instance, It does not protect against things such as double submit cookies. Those setups require more know-how and involvement. This library aims to be simple to setup. If you have very strong security needs (e.g. large scale production application, sensitive information, single page application that makes many backend requests), then consult the OWASP Security Link here and implement more stringent security.

Installation

npm i tiny-csrf

To Use in your app:

const csurf = require("tiny-csrf");
const express = require("express");
const session = require("express-session");

let app = express();

app.use(express.urlencoded({ extended: false })); 
app.use(cookieParser("cookie-parser-secret"));
app.use(session({ secret: "keyboard cat" }));
// order matters: above three must come first
app.use(csurf("123456789iamasecret987654321look"));

// ...declare all your other routes and middleware

The secret must be 32 bytes (e.g. 32 characters, 256 bits) in length and uses the built-in crypto.createCipheriv library built into Node . The secret length is enforced by the AES-256-CBC algorithm.

Defaults to only requiring CSRF protection on POST, PUT, and PATCH requests and excludes no URLs. The csrf will be checked for in the body of a request via _csrf.

Examples

const csurf = require("tiny-csrf");
const express = require("express");
const session = require("express-session");
const cookieParser = require("cookie-parser");

let app = express();

app.use(express.urlencoded({ extended: false })); 
app.use(cookieParser("cookie-parser-secret"));
app.use(session({ secret: "keyboard cat" }));
// order matters: above three must come first
app.use(
  csurf(
    "123456789iamasecret987654321look", // secret -- must be 32 bits or chars in length
    ["POST"], // the request methods we want CSRF protection for
    ["/detail", /\/detail\.*/i], // any URLs we want to exclude, either as strings or regexp
    [process.env.SITE_URL + "/service-worker.js"]  // any requests from here will not see the token and will not generate a new one
  )
);

app.get("/", (req, res) => {
  const csrfToken = req.csrfToken();
  return res.status(200).send(
    `
<form method="POST" action="/">
  <input name="_csrf" value="${csrfToken}" type="hidden"/>
  <input name="thing" type="text"/>
  <button type="submit"/>Submit</button>
</form>
`.trim()
  );
});

const { randomUUID } = require("crypto");
app.get("/wont-pass", (req, res) => {
  const uuid = randomUUID();
  return res.status(200).send(
    `
<form method="POST" action="/">
  <input name="_csrf" value="${uuid}" type="hidden"/>
  <button type="submit"/>Submit</button>
</form>
`.trim()
  );
});

app.post("/", (req, res) => {
  res.status(200).send("Your cookie passed!");
});

app.listen(3000, () => console.log("running"));

Code Coverage

All contributions must contain adequeate testing.

$ npm run test:coverage

> [email protected] test:coverage
> nyc --reporter=lcov --reporter=text-summary mocha test.js --exit



  Cookie Encryption Tests
    ✔ will encrypt and decrypt a cookie

  Default Options Tests
    ✔ throw internal error if our secret is not long enough
    ✔ throws internal error if we have no cookies
    ✔ generates token for non-POST request
    ✔ allows if the CSRF token is correct
    ✔ does not allow if the CSRF token is incorrect
    ✔ does not allow if the CSRF token is missing in body
    ✔ does not allow if the CSRF token was never generated

  Tests w/Specified Included Request Methods
    ✔ allows if the CSRF token is correct
    ✔ does not allow if the CSRF token is incorrect
    ✔ allows if the method is specified as not included

  Tests w/Specified Excluded URLs
    ✔ allows if the URL is marked as excluded
    ✔ allows if the URL is marked as excluded as a regexp
    ✔ generates a new token if no token is supplied
    ✔ does not allow if the CSRF token is incorrect and the URL is not marked as excluded

  Excluded Referrer Tests (Service Workers)
    ✔ throws error if instantiated without a list as the fourth argument
    ✔ returns null if a service worker accesses an excluded URL
    ✔ returns null if we are a service worker
    ✔ allows for reuse of the CSRF token if there is a service worker request before the real one
    ✔ allows for reuse of the CSRF token if there is a service worker request after the real one

  other tests
    ✔ works #1
    ✔ works #2


  22 passing (75ms)


=============================== Coverage summary ===============================
Statements   : 100% ( 59/59 )
Branches     : 100% ( 30/30 )
Functions    : 100% ( 8/8 )
Lines        : 100% ( 54/54 )
================================================================================

License

MIT