Content Security Policy with nonces

A Content Security Policy is the second line of defense: even if foreign code gets into a page, the browser only runs the scripts the server allowed.

JSX escapes all values, but a single html() with untrusted content, a library bug or a compromised script can still inject code. A guard creates a random nonce for every request, puts it into this and sends a policy which only allows scripts carrying this nonce. The layout adds nonce={this.nonce} to its script tags. Injected markup can't know the nonce, as it changes with every reload, so the browser refuses to run it.

Policy onPolicy off

The policy of this page

Content-Security-Policy: default-src 'self';
  script-src 'nonce-0Dg65eGHqjqIxiPlHzcb6g==' 'strict-dynamic';
  img-src 'self' data:;
  object-src 'none';
  base-uri 'self';
  form-action 'self';
  frame-ancestors 'none'

Try it

Script with nonce

An inline script rendered with nonce={this.nonce}, like the layout's scripts.

Didn't run
Script without nonce

The same inline script, but without the nonce, like an injected one.

Blocked
Injected event handler

Simulates a bug: untrusted markup with an onerror handler, inserted via html().

Blocked

Blocked by the browser

The browser reports every violation as a securitypolicyviolation event (and in the console). With a report-to directive, it can also send them to your server.