Skip to content

Commit 3542d7d

Browse files
committed
fix: Use Web Crypto compatible function for nonce generation
1 parent 7fa4e0b commit 3542d7d

File tree

2 files changed

+219
-246
lines changed

2 files changed

+219
-246
lines changed

src/steps/csp.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,19 @@ function shouldApplyNonce(metaCSPText, headersCSPText) {
5656

5757
/**
5858
* Create a nonce for CSP
59+
* Constraints:
60+
* - we can only use web crypto functions to be compatible with cloudflare.
61+
* - we need at least 128bits of entropy, according to the documentation.
5962
* @returns {string}
6063
*/
6164
function createNonce() {
62-
return cryptoImpl.randomBytes(18).toString('base64');
65+
// 1 UUIDv4 = 122 bits entropy + 4 hex characters/16 bits from second UUIDv4 = 138 bits entropy
66+
const randomHex = cryptoImpl.randomUUID().replaceAll('-', '')
67+
+ cryptoImpl.randomUUID().slice(0, 4);
68+
69+
// transform into byte array before encoding for compression
70+
const byteArray = new Uint8Array(randomHex.match(/.{2}/g).map((byte) => parseInt(byte, 16)));
71+
return btoa(String.fromCharCode(...byteArray));
6372
}
6473

6574
/**

0 commit comments

Comments
 (0)