Skip to content

fix: Use Web Crypto compatible function for nonce generation - v2 #818

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/steps/csp.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,19 @@ function shouldApplyNonce(metaCSPText, headersCSPText) {

/**
* Create a nonce for CSP
* Constraints:
* - we can only use web crypto functions to be compatible with cloudflare.
* - we need at least 128bits of entropy, according to the documentation.
* @returns {string}
*/
function createNonce() {
return cryptoImpl.randomBytes(18).toString('base64');
// 1 UUIDv4 = 122 bits entropy + 4 hex characters/16 bits from second UUIDv4 = 138 bits entropy
const randomHex = cryptoImpl.randomUUID().replaceAll('-', '')
+ cryptoImpl.randomUUID().slice(0, 4);

// transform into byte array before encoding for compression
const byteArray = new Uint8Array(randomHex.match(/.{2}/g).map((byte) => parseInt(byte, 16)));
return btoa(String.fromCharCode(...byteArray));
}

/**
Expand Down
Loading