Skip to content

fix: Use Web Crypto compatible function for nonce generation - v1 #817

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

Merged
merged 1 commit into from
Feb 13, 2025
Merged
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
4 changes: 3 additions & 1 deletion src/steps/csp.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ function shouldApplyNonce(metaCSPText, headersCSPText) {
* @returns {string}
*/
function createNonce() {
return cryptoImpl.randomBytes(18).toString('base64');
const array = new Uint8Array(18);
cryptoImpl.getRandomValues(array);
return btoa(String.fromCharCode(...array));
Comment on lines +62 to +64
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this better than the uuid approach in v2

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tripodsan I agree, but it has the esmock problem in the tests... that's the only reason I implemented v2.
The problem is that getRandomValues cannot be overriden in the module as simple as randomUUID, or other functions.

Other functions are simple module exports, while getRandomValues is done with:

ObjectDefineProperties(module.exports, {
  getRandomValues: {
    __proto__: null,
    configurable: false,
    enumerable: true,
    get: () => getRandomValues,
    set: undefined,
  },
});

Which means that when I try to do cryptoImpl.getRandomValues = () => mock, I get:

TypeError: Cannot set property getRandomValues of #<Object> which has only a getter

So I couldn't find another way except for using esmock, which makes the test setup quite complex.

}

/**
Expand Down
Loading