Skip to content

CSP compliance #686

@derekkramer

Description

@derekkramer

Problem

The __insertCSS method for pure CSS file imports isn't compliant with most
content security policies. This makes projects bundled with Bunchee only viable
with a style-src setting of 'unsafe-inline' or 'unsafe-hashes', or if
they remove their content security policy entirely.

Proposed Solution

The Bunchee CLI could be enhanced with an optional --nonce-header argument
passed to inlineCss and templated into the raw __insertCSS function. If
set, the code would be enhanced to pull the nonce value from the header and
inject it as an attribute to the inline'd <style> tag.

Example

If a user has configured a x-nonce header:

x-nonce "d1QZa9hkpPFwAMy3DPeizWDrdiJxKFwAv9YejVkccA4"

And specifies a header of x-nonce in their CLI build command:

bunchee --runtime node --nonce-header x-nonce -o ./dist/bundle.js

The existing inlineCss function would be modified to recieve the variable
and add calls to the cssImport.global payload:

let nonce = headers.get("x-nonce");
// ...
style.nonce = nonce

This would make Bunchee bundles more viable by allowing users to keep a content
security policy iwth a style-src setting of "nonce-<nonce_value>".
This feature would be superficial and purely additive and implementation of
the CSP nonce would be responsibility of the user.

I am open to tackling this feature and opening a pull request after receiving
approval to proceed in this request.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions