vibe-audit.lab

guides · 2026-11-14

Math.random() Is Not a Token Generator: Weak Randomness in Reset Links and Session IDs

Published 2026-11-14 · Reviewed 2026-11-14 · By the Ingenious AI team

The short answer

Math.random() and Python's random module are statistical generators, not cryptographic ones: their future outputs are predictable from observed ones. Any token, reset link, invite code or session ID built from them is a guessing game the attacker wins. Use your platform's CSPRNG — crypto.randomUUID / getRandomValues, Python's secrets module — for anything whose value is a secret.

Check your own app free: paste your code or enter your site URL on the Vibe-Code Audit homepage — the free scan checks for exposed secrets, injection flaws, XSS patterns, missing headers and exposed .env/.git paths, with a copy-paste fix for every finding. No credit card.

Predictability is a property, not a bug

Math.random (V8's xorshift128+) has a small, recoverable state: researchers have shown that a handful of consecutive outputs suffice to reconstruct it and predict everything after — and 'before' is not safe either. Python's random (Mersenne Twister) surrenders its state after 624 observed outputs, and tokens leak outputs generously: every invite link you email, every reset URL in a log, every 'random' filename is a sample. AI models choose these functions because tutorials do and because the names sound right — 'random' is right there in the name. Vibe-Code Audit maintains separate weak-randomness detectors for JavaScript and Python, matching tokens/secrets/passwords/nonces near Math.random and the random module, because the vulnerable construct is specifically 'weak generator near a security value'.

Length does not rescue the generator: a 64-character token from a broken PRNG has far less real entropy than its length suggests, because the whole sequence derives from a small recoverable state. Attackers do not brute-force the token space; they solve the generator.

Where generated code hides weak tokens

Password-reset links, email-verification codes, API keys minted in-app, session identifiers in hand-rolled auth, invite and referral codes, file names for 'unguessable' uploads, and CSRF tokens. Numeric short codes deserve separate treatment: a 6-digit code is only a million possibilities even from a perfect generator, so it needs attempt limits (see the rate-limits guide) in addition to a CSPRNG. Also check the quieter spots: Math.random used for request IDs that later become cache keys or lookup handles, and 'temporary passwords' generated for new users — a temporary password is a credential, full stop.

The replacements, by language

JavaScript/Node: crypto.randomUUID() for identifiers, crypto.randomBytes(n) (or getRandomValues in browsers) encoded base64url/hex for tokens; never hand-roll from Math.random. Python: the secrets module — secrets.token_urlsafe(32), secrets.token_hex, secrets.choice for codes — which exists precisely so nobody has to make this decision again; uuid4 in Python is CSPRNG-backed on modern platforms, but secrets is the clearer signal in review. Set token sizes by purpose: 128 bits minimum for reset/session tokens (32 hex chars, ~43 base64url chars), so that even a perfect guessing attack is computationally absurd, and pair with expiry — a strong token that lives forever is a permanent key.

Sweep mechanically: grep for Math.random and random. across the codebase, then classify each hit — visual jitter and game mechanics may keep the weak generator; anything named token, secret, key, code, session, reset or nonce may not.

Rotate what weak randomness already minted

Long-lived artefacts minted weakly — API keys, persistent invite codes, remember-me tokens — should be re-issued from a CSPRNG if the generator was predictable during their lifetime and samples were observable. Short-lived tokens (reset links with an hour's expiry) mostly solve themselves by expiring; force-expire the outstanding ones at deploy of the fix for cleanliness. Then add the regression rule to your repo: a lint or scan check that fails when Math.random appears near security vocabulary — the same pattern the scanner encodes — so the next generated auth flow cannot quietly reintroduce it.

Worked example: ResetRight, an account-recovery flow audit

ResetRight is the fictional name the team at Fernway Fitness gave their recovery audit after a scan flagged 'Weak randomness for secrets (Math.random)' in their reset-token generator: tokens were 24 characters assembled from Math.random output. A developer demonstrated state recovery in staging using five tokens the system had emailed to test accounts, then predicted the sixth token correctly on the second try. The generator was replaced with crypto.randomBytes(32) base64url in one line, outstanding reset tokens were force-expired (all 17 of them), and API keys for the 3 connected integrations were re-minted from the CSPRNG as a precaution. The scan check joined CI, and a later AI-generated invite feature that reached for Math.random failed the build before review.

The five-step fix checklist

  1. Grep for Math.random, the random module and rand() everywhere near token, secret, code, session or nonce vocabulary.
  2. Replace every security use with the platform CSPRNG: crypto.randomBytes/randomUUID or Python's secrets module.
  3. Size tokens at 128 bits or more and give them expiries; pair short numeric codes with strict attempt limits.
  4. Force-expire outstanding weak tokens at fix time and re-mint long-lived artefacts (API keys, invite codes) from the CSPRNG.
  5. Add a scan or lint rule that fails the build when weak randomness appears near security vocabulary, and re-scan.

What is Weak randomness for secrets?

generating security tokens with a non-cryptographic pseudo-random generator (Math.random, the random module, rand()). These generators are designed for simulations: fast and well-distributed, but deterministic — given enough outputs, their internal state, and therefore all future tokens, can be computed.

Sources

Frequently asked questions

My token is long. Doesn't length make it safe?

Length helps only when the bits are truly unpredictable. A long token from a recoverable-state generator is a long encoding of a small secret — attackers solve the generator's state instead of guessing the token.

Is Math.random fine for anything?

Yes — animations, sampling, games, A/B assignment, anything where predictability costs nothing. The ban applies to values that function as secrets or unguessable handles.

Are UUIDs safe as tokens?

UUIDv4 from a platform crypto source carries 122 random bits and is fine as an unguessable identifier. The risk is hand-assembled 'UUID-like' strings from Math.random — use crypto.randomUUID, which is the real thing.

What about verification codes users type?

Six digits is a million combinations regardless of generator: generate with a CSPRNG and cap attempts per code (5 is a good default) with expiry in minutes. Both halves are required.

Related guides

Browse the full library on the guides index, run the checks in the launch audit, or compare plans on pricing.


Informational explainer, not a security guarantee. Scan your code free before every deploy.

← all guides

← Back