Skip to content

Instantly share code, notes, and snippets.

@milksense
Last active August 28, 2022 16:47
Show Gist options
  • Save milksense/2ceb52f674666d08d19af34d4c881fc4 to your computer and use it in GitHub Desktop.
Save milksense/2ceb52f674666d08d19af34d4c881fc4 to your computer and use it in GitHub Desktop.
Simple CSP nonce generator
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