Content Security Policy header generation

Files
README.md

csp #

Content-Security-Policy headers for OCaml web servers.

A Content Security Policy tells the browser which origins a page may load scripts, styles, images and frames from, so that injected markup cannot pull in a script from elsewhere or run inline code. The policy travels as one Content-Security-Policy header whose syntax is easy to get wrong by hand. csp builds that header from typed directives, following CSP Level 2 and CSP Level 3. It has one preset, a strict same-origin policy with no inline script, the origins of common CDNs as constants, and eleven directive constructors for anything else.

Install #

$ opam install csp

If opam cannot find the package, add the overlay repository first:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install csp

Usage #

(* The preset policy *)
let name, value = Csp.header ()
(* "Content-Security-Policy", "default-src 'none'; script-src 'self'; ..." *)

(* Custom directives *)
let name, value = Csp.custom_header [
  Csp.Default_src [ "'self'" ];
  Csp.Script_src [ "'self'"; Csp.cdn_jsdelivr ];
  Csp.Style_src [ "'self'"; Csp.cdn_google_fonts ];
  Csp.Img_src [ "'self'"; "data:" ];
]

API #

  • Csp.header () is the header name and the preset value, and Csp.header_value () the value alone. Csp.strict_policy is that value and Csp.strict_directives the directives it is formatted from. The preset withholds 'unsafe-inline', so a page that needs inline script says so in its own directive list.
  • Csp.custom_header builds the header from any directive list, and Csp.format_directive and Csp.format_policy format directives as strings.
  • Csp.cdn_jsdelivr, cdn_unpkg, cdn_cdnjs, cdn_google_fonts, cdn_google_static, cdn_google_apis, cdn_cloudflare, cdn_bootstrap and cdn_fontawesome are CDN origins, and Csp.popular_cdns lists them all.

License #

ISC. See LICENSE.md.