Skip to main content
Deno 2 is finally here 🎉️
Learn more

csp-middleware

deno land deno doc GitHub release (latest by date) codecov GitHub

test NPM

HTTP Content Security Policy(CSP) middleware.

Compliant with Content Security Policy Level 3.

Middleware

For a definition of Universal HTTP middleware, see the http-middleware project.

Usage

Middleware adds the Content-Security-Policy header to the response.

import {
  csp,
  type CSPDirectives,
} from "https://deno.land/x/csp_middleware@$VERSION/mod.ts";
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";

declare const request: Request;
declare const handler: (request: Request) => Response;

const directives: CSPDirectives = { defaultSrc: ["'self'"] };
const middleware = csp(directives);
const response = await middleware(request, handler);

assertEquals(
  response.headers.get("content-security-policy"),
  "default-src 'self'",
);

yield:

Content-Security-Policy: default-src 'self'

CSP directives

CSPDirectives are structured Content-Security-Policy header field objects.

You can declare a CSP directive with a camelCase key and type-safe.

OWASP recommendation:

import {
  type CSPDirectives,
} from "https://deno.land/x/csp_middleware@$VERSION/mod.ts";

const directives: CSPDirectives = {
  defaultSrc: `'none'`,
  scriptSrc: [`'self'`],
  connectSrc: [`'self'`],
  imgSrc: [`'self'`],
  styleSrc: [`'self'`],
  frameAncestors: [`'self'`],
  formAction: [`'self'`],
};

yield:

Content-Security-Policy: default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self'; frame-ancestors 'self'; form-action 'self';

Throwing error

CSP directives are serialized.

If the CSP does not follow <serialized-policy-list>, it throws a TypeError.

import { csp } from "https://deno.land/x/csp_middleware@$VERSION/mod.ts";
import { assertThrows } from "https://deno.land/std/testing/asserts.ts";

assertThrows(() => csp({}));

Report only

With the reportOnly flag, switches Content-Security-Policy to Content-Security-Policy-Report-Only header.

import {
  csp,
  type CSPDirectives,
} from "https://deno.land/x/csp_middleware@$VERSION/mod.ts";
import { assert } from "https://deno.land/std/testing/asserts.ts";

declare const directives: CSPDirectives;
declare const request: Request;
declare const handler: (request: Request) => Response;

const middleware = csp(directives, { reportOnly: true });
const response = await middleware(request, handler);

assert(response.headers.has("content-security-policy-report-only"));

Effects

Middleware may make changes to the following elements of the HTTP message.

  • HTTP Headers
    • Content-Security-Policy

Conditions

Middleware is executed if all of the following conditions are met:

  • Content-Security-Policy header does not exists in response

License

Copyright © 2023-present httpland.

Released under the MIT license