born05/craft-csp

Content Security Policy (or CSP) generator using nonces.

Installs: 7 559

Dependents: 0

Suggesters: 0

Security: 0

Stars: 9

Watchers: 8

Forks: 7

Open Issues: 1

Type:craft-plugin

2.1.1 2023-07-03 14:05 UTC

This package is auto-updated.

Last update: 2024-05-03 15:57:14 UTC


README

Content Security Policy (or CSP) generator using nonces.

Currently does not work in combination with {% js %}{% endjs %} block code twig tags.

Requirements

  • Craft 3.0.0

Installation

To install the plugin, search the plugin store for "Content Security Policy" or:

composer require born05/craft-csp

Setting up

Either config using config/content-security-policy.php or use nonces:

{# Regular html #}
<script src="url/of/script.js" nonce="{{ cspNonce('script-src') }}"></script>
<link href="url/of/style.css" rel="stylesheet" nonce="{{ cspNonce('style-src') }}" />

{# Twig tags #}
{% css inlineCSS with {nonce: cspNonce('style-src')} %}
{% js 'example.js' with {nonce: cspNonce('script-src')} %}

Example config/content-security-policy.php:

<?php

return [
    'enabled' => true,
    
    'reportOnly' => false,

    'baseUri' => [
        "'none'",
    ],
    'defaultSrc' => [],
    'scriptSrc' => [
        "'self'",
    ],
    'styleSrc' => [
        "'self'",
    ],
    'imgSrc' => [
        "'self'",
    ],
    'connectSrc' => [],
    'fontSrc' => [],
    'objectSrc' => [],
    'mediaSrc' => [],
    'frameSrc' => [],
    'sandbox' => [],
    'reportUri' => [],
    'childSrc' => [],
    'formAction' => [],
    'frameAncestors' => [],
    'pluginTypes' => [],
    'reportTo' => [],
    'workerSrc' => [],
    'manifestSrc' => [],
    'navigateTo' => [],
];

Troubleshooting

If using the SEOMatic plugin, nonces added by that plugin will interfer with this plugin's configuration. You can disable this feature at /admin/seomatic/plugin#tags and re-enable the scripts with the following code:

{% do seomatic.script.get("googleAnalytics").nonce(cspNonce('script-src')) %}

For config options see: Settings.php

License

Copyright © Born05

See license