cosepo

Types

pub type ContentSecurityPolicy {
  ContentSecurityPolicy(directives: List(Directive))
}

Constructors

  • ContentSecurityPolicy(directives: List(Directive))

Use .new_directive(name: String, value: String) to construct a Directive

pub opaque type Directive

Functions

pub fn merge(
  content_security_policy: ContentSecurityPolicy,
  directive: Directive,
) -> ContentSecurityPolicy

Merges a Directive with an existing ContentSecurityPolicy

Example

let existing_csp = parse("default-src 'self';")
let assert Ok(directive) = new_directive("default-src", ["https://example.com/"])
merge(existing_csp, directive)
// -> ContentSecurityPolicy([
//   Directive("default-src", ["'self'", "https://example.com"])
// ])
pub fn new_directive(
  name name: String,
  value value: List(String),
) -> Result(Directive, String)

Creates a new Directive, validating the directive name and values.

Example

new_directive("default-src", ["'self'"])
// -> Ok(Directive(name: "default-src", value: ["'self'"]))

new_directive("invalid-directive", [])
// -> Error("invalid-directive is not a valid directive name")
pub fn parse(
  serialized_csp: String,
) -> Result(ContentSecurityPolicy, String)

Parses a serialized content security policy string https://www.w3.org/TR/CSP3/#parse-serialized-policy

Example

parse("default-src 'self'")
// -> Ok(ContentSecurityPolicy(directives: [
//      Directive(name: "default-src", value: ["'self'"]),
//    ]))

parse("invalid-directive 'self'")
// -> Error("invalid-directive is not a valid directive name")
pub fn serialize(
  content_security_policy: ContentSecurityPolicy,
) -> String

Generates a serialized string, suitable for the Content-Security-Policy HTTP header.

Example

let assert Ok(content_security_policy) = parse("default-src 'self';")
content_security_policy |> serialize
// -> "default-src 'self';"
pub fn set(
  content_security_policy: ContentSecurityPolicy,
  directive: Directive,
) -> ContentSecurityPolicy

Modifies a ContentSecurityPolicy, overwriting a previous directive, if present

Example

let assert Ok(content_security_policy) = parse("default-src 'self'")
let assert Ok(directive) = new_directive("default-src", ["'none'"])
set(content_security_policy, directive) |> serialize
// -> "default-src 'none';"
Search Document