JSPM

  • Created
  • Published
  • Downloads 548184
  • Score
    100M100P100Q174406F
  • License MIT

Content Security Policy middleware

Package Exports

  • helmet-csp

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (helmet-csp) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Content Security Policy middleware

Content Security Policy helps prevent unwanted content being injected into your webpages. This can mitigate cross-site scripting (XSS) vulnerabilities, malicious frames, unwanted trackers, and much more.

If you want to learn how CSP works, check out the fantastic HTML5 Rocks guide, the Content Security Policy Reference, and the Content Security Policy specification.

This middleware helps set Content Security Policies.

Basic usage:

const contentSecurityPolicy = require("helmet-csp");

app.use(
  contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'", "default.example"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      objectSrc: ["'none'"],
      upgradeInsecureRequests: [],
    },
    reportOnly: false,
  })
);

To get the defaults, use contentSecurityPolicy.getDefaultDirectives().

You can set any directives you wish. defaultSrc is required. Directives can be kebab-cased (like script-src) or camel-cased (like scriptSrc). They are equivalent, but duplicates are not allowed.

The reportOnly option, if set to true, sets the Content-Security-Policy-Report-Only header instead.

This middleware does minimal validation. You should use a more sophisticated CSP validator, like Google's CSP Evaluator, to make sure your CSP looks good.

Recipe: generating nonces

You can dynamically generate nonces to allow inline <script> tags to be safely evaluated. Here's a simple example:

const crypto = require("crypto");

app.use((req, res, next) => {
  res.locals.nonce = crypto.randomBytes(16).toString("hex");
  next();
});

app.use((req, res, next) => {
  csp({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", `'nonce-${res.locals.nonce}'`],
    },
  })(req, res, next);
});

app.use((req, res) => {
  res.end(`<script nonce="${res.locals.nonce}">alert(1 + 1);</script>`);
});

See also