Skip to content

CSP compatibility

Currently Hyvä CSP is unreleased

This is a documentation preview.
Please watch the #update-notifications channel in Slack to be notified when it is available.

For Hyvä developers, CSP compatibility means dealing with not being allowed to use JavaScript expressions in Alpine bindings, and not being able to inject inline scripts into the page at runtime.

No unsafe-eval

If the unsafe-eval content security policy is not allowed, no JavaScript code can be dynamically created and executed.

  • The eval() function can not be used
  • No new <script> elements with script content can be injected into the page
  • No new Functions can be created dynamically

Regular Alpine.js uses dynamically created function instances to evaluate attribute expressions, so it depends on unsafe-eval, which means it does not work with strict CSP without unsafe-eval.

How does Hyvä work without unsafe-eval?

Alpine CSP on the other hand uses no JS expressions. Only Alpine bindings referring to component properties are allowed. More information can be found in the Hyvä Alpine CSP documentation. Hyvä offers an Alpine CSP-compatible version of the theme, where all attribute bindings are converted to functions on the Alpine components.

No unsafe-inline

Only authorized <script> tags are executed to protect visitors against injected scripts.
Scripts are authorized either by including a sha256 of the script content in the CSP HTTP header, or by specifying a nonce attribute on the script that matches the nonce in the CSP HTTP header.

Inline event handlers are also forbidden without unsafe-inline, for example <a href="..." onclick='this.target="_blank"'>.

How does Hyvä work without unsafe-inline?

Hyvä uses nonces on uncached pages, and SHAs on cached pages. Injecting the nonce attribute or the sha is done by adding a single line right below the closing tag of every inline script:

</script>
<?php $hyvaCsp->registerInlineScript() ?>

The $hyvaCsp instance is available in every Hyvä theme as a template variable, just like $block and $viewModels.

Important!

The $hyvaCsp->registerInlineScript() has to be called directly after the closing script tag!
There must be no other HTML in between.

If there are multiple inline scripts in a page, $hyvaCsp->registerInlineScript() has to be called after each one.