no-math-random-crypto
Disallow Math.random() for cryptographic purposes (tokens, keys, secrets, salts, IVs)
Next step
no-math-random-crypto ships in eslint-plugin-node-security, with 31 of its 47 rules in the recommended preset.
npm install -D eslint-plugin-node-securityimport { configs } from 'eslint-plugin-node-security';
export default [configs.recommended];
Detects Math.random() used in a cryptographic context in Node.js code. Math.random() is a non-cryptographic PRNG: its output is predictable and must never seed tokens, keys, passwords, salts, IVs, nonces, or session identifiers. This rule is part of eslint-plugin-node-security and provides LLM-optimized error messages with fix suggestions.
🚨 Security rule | 💡 Provides suggestions | ⚠️ Set to error in recommended
Migrated from the deprecated standalone
cryptoplugin intoeslint-plugin-node-security, which now ships every cryptography rule that plugin had — including this one.
Rule Details
The rule flags Math.random() only when the value flows into a cryptographic context, so benign randomness (shuffles, jitter, sampling, UI) does not trigger it. A context is treated as cryptographic when the result is:
- assigned to a variable or property whose name matches
token,key,secret,password,salt,iv,nonce,seed,session,csrf,otp,pin,auth,verify, etc.; or - returned from a function whose name suggests credential/token generation.
The value is followed through every local it is relayed into (const raw = Math.random()…; const padded = raw.padEnd(…); const apiKey = padded;), however many there are. Math.random is recognised in every static spelling — Math['random'], Math[`random`], globalThis.Math.random, const { random } = Math and const { ['random']: r } = Math.
❌ Incorrect
function generateSessionToken() {
return Math.random().toString(36).substring(2); // CWE-338: predictable token
}
const apiKey = Math.random().toString(36);✅ Correct
import { randomBytes, randomUUID } from 'node:crypto';
function generateSessionToken() {
return randomBytes(32).toString('hex');
}
const requestId = randomUUID();
// Non-crypto randomness is fine — not flagged
const j = Math.floor(Math.random() * deck.length);Security values named by their slot
A value is also a security value when the call it is passed to names the slot with a string literal:
headers.set('X-SRF-TOKEN', Math.random()...), res.setHeader('X-CSRF-Token', ...), res.cookie('session', ...),
localStorage.setItem('authToken', ...), url.searchParams.set('nonce', ...), and { 'X-CSRF-Token': ... }.
state is too ordinary a name to decide on its own, so an OAuth state is recognised by where the value goes: after
state= in a URL, as the value of a state query parameter, or in an object that also carries client_id,
redirect_uri, response_type, scope or code_challenge. setState(state) and { state } passed to a renderer are
not reported.
Not reported: a .sort(() => Math.random() - 0.5) shuffle, jitter, colours, and keys qualified as dom, element,
item, list, component, render, color or data.
Where the draw goes
A draw is a decision, not a value, when every use of it picks an element that already exists (credentials[Math.floor(Math.random() * credentials.length)], stored or returned whole), sets a setTimeout / setInterval delay, or is compared (Math.random() < 0.1). Its binding's name does not matter. A pick from an alphabet (a string, or an array of single characters), a pick appended to a growing value (token += CHARS[draw], a push, a callback body) and a draw that is also stored or stringified keep reporting.
Options
| Option | Type | Default | Description |
|---|---|---|---|
allowInTests | boolean | true | Allow Math.random() in test files. Default: true |
secretWords | string[] | ["token","tokens","key","keys","secret","secrets","password","passwd","salt","iv","nonce","seed","hash","cipher","auth","session","csrf","otp","pin","code","codes","verify","signature","credential","jwt","encryption","apikey","passphrase","mnemonic"] | Words that name a security value in this codebase. Replaces the default list. |
correlationIdWords | string[] | ["request","req","correlation","trace","span","transaction","txn","message","msg","event","job","run","task","batch","element","node","row","record","instance","component","widget","dom","operation","call","invocation","frame","render"] | Words that mark a trailing id as a correlation id rather than a credential. Replaces the default list. |
{
"node-security/no-math-random-crypto": ["error", { "allowInTests": false }]
}allowInTests(defaulttrue) — allowsMath.random()in*.test.*/*.spec.*files; setfalseto check test files too.
When Not To Use
If your codebase never uses Math.random() for anything security-sensitive and you want zero overhead, you can disable it — but the context-aware heuristic is designed to stay silent on non-crypto randomness, so leaving it on error is recommended.
Further Reading
Use this rule
npm install -D eslint-plugin-node-securityimport nodeSecurity from 'eslint-plugin-node-security';export default [ { plugins: { 'node-security': nodeSecurity }, rules: { 'node-security/no-math-random-crypto': 'error' }, },];npm install -D oxlint-plugin-node-security{ "jsPlugins": ["oxlint-plugin-node-security"], "rules": { "node-security/no-math-random-crypto": "error" }}import { defineConfig } from 'vite-plus';export default defineConfig({ lint: { jsPlugins: ['oxlint-plugin-node-security'], rules: { 'node-security/no-math-random-crypto': 'error', }, },});oxlint-plugin-node-security re-exports eslint-plugin-node-security/oxlint: the same rules under the same IDs, and no ESLint install. Why oxlint.
Did this rule catch something? Star the repo to get new CWE coverage as we ship it — or follow the AI-code-security benchmarks behind these rules.