Something went wrong. Try again.
Content Security Policy header generation
Something went wrong. Try again.
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, andCsp.header_value ()the value alone.Csp.strict_policyis that value andCsp.strict_directivesthe 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_headerbuilds the header from any directive list, andCsp.format_directiveandCsp.format_policyformat directives as strings.Csp.cdn_jsdelivr,cdn_unpkg,cdn_cdnjs,cdn_google_fonts,cdn_google_static,cdn_google_apis,cdn_cloudflare,cdn_bootstrapandcdn_fontawesomeare CDN origins, andCsp.popular_cdnslists them all.
License #
ISC. See LICENSE.md.
- OCaml 100%