← all rules

ast/math-random-for-security-token

Insecure randomness: Math.random() used to generate a security token

criticalASTweak-cryptoCWE-338js · ts

What it detects

Math.random() is a pseudo-random number generator with predictable state — V8 uses xorshift128+, and a handful of observed outputs lets an attacker reproduce the entire stream. Using it for a token / session / csrf / nonce / salt / api-key / reset-token / otp / uuid means the value is forgeable. Use crypto.randomBytes(N).toString('hex') in Node, or crypto.getRandomValues(new Uint8Array(N)) in the browser / edge runtime. For uuids specifically use crypto.randomUUID().

How it runs

Each file scanned is parsed with the TypeScript Compiler API (via ts-morph). This rule walks the AST looking for the call shape and user-input flow it describes. Skipped on files larger than 200 KB or that fail to parse.

Found a false positive or want this rule tuned? File an issue. You can also suppress per-repo via a .repoguardignore line.