Last active
August 28, 2022 16:47
-
-
Save milksense/2ceb52f674666d08d19af34d4c881fc4 to your computer and use it in GitHub Desktop.
Simple CSP nonce generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { randomBytes } from 'crypto'; | |
/** | |
* Generates a valid base64 nonce value of at least 128-bits. | |
* | |
* @param {number} size The random bytes to generate clamped between 16 and 64. | |
* Defaults to 16 (128-bit). | |
* | |
* @see https://csp.withgoogle.com/docs/faq.html#generating-nonces | |
* | |
* @returns {string} The base64 nonce value. | |
*/ | |
export default (size: number = 16): string => { | |
const clamped: number = Math.max(16, Math.min(size, 64)); | |
const rounded: number = Math.round(clamped); | |
return randomBytes(rounded).toString('base64'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment