Naar de inhoud
Sand Software Solutions

NaN, Infinity and 2^31: the bugs that quietly switch your checks off

Gepubliceerd · 4 min leestijd

We recently reviewed 48 small TypeScript/JavaScript utility packages (JWT helpers, retries, rate limiting, health checks, caching, timers) before publishing them. A disclosure first: the packages were written and reviewed with AI assistance (Claude), and what you read below is what the tests and the review found, not a claim that humans caught everything. The review found the same class of bug again and again, in unrelated packages. It's not exotic, and you probably have it in your own code.

The class: a number that isn't a sensible number turns a safety check into a no-op, without any error. Below, each case is reproduced with code you can run (Node 20+, no dependencies).

import { scryptSync, randomBytes } from "node:crypto";

// 1. An expiry check written the obvious way, and what NaN does to it.
function isExpired(exp, now, toleranceSec) {
  return now > exp + toleranceSec;
}
const exp = 1_000;               // the token expired long ago...
const now = 5_000;
console.log("tolerance 0       :", isExpired(exp, now, 0));
console.log("tolerance NaN     :", isExpired(exp, now, NaN), "  <- NaN > anything is false, so 'not expired'");
console.log("tolerance '99999' :", isExpired(exp, now, "99999"), "  <- 1000 + '99999' is the string '100099999'");

// 2. A guard that looks right and lets NaN through.
const naive = (x) => { if (x < 0) throw new RangeError("must be >= 0"); return x; };
console.log("naive(NaN)        :", naive(NaN), "  <- NaN < 0 is false, so it is accepted");
const strict = (x) => { if (!Number.isFinite(x) || x < 0) throw new RangeError("must be a finite number >= 0"); return x; };
try { strict(NaN); } catch (e) { console.log("strict(NaN)       :", e.message); }

// 3. Timers above 2^31-1 ms fire almost immediately.
process.on("warning", (w) => console.log("warning           :", w.name));
const t0 = Date.now();
await new Promise((resolve) => setTimeout(resolve, 2 ** 31)); // ~24.8 days, intended
console.log("setTimeout(2**31) :", `resolved after ${Date.now() - t0} ms`);
const t1 = Date.now();
await new Promise((resolve) => setTimeout(resolve, Infinity));
console.log("setTimeout(Infinity):", `resolved after ${Date.now() - t1} ms`);
const t2 = Date.now();
await new Promise((resolve) => setTimeout(resolve, NaN));
console.log("setTimeout(NaN)   :", `resolved after ${Date.now() - t2} ms`);

// 4. JSON.stringify as a cache key merges different arguments.
const key = (...args) => JSON.stringify(args);
console.log("cache keys equal  :", key(undefined) === key(null), key(NaN) === key(null), key(Infinity) === key(null));

// 5. A stored password hash that chooses its own cost. We measure, we do not guess.
const cost = { N: 2 ** 21, r: 8, p: 1, maxmem: 3 * 1024 ** 3 };
const mem0 = process.memoryUsage().rss;
const start = Date.now();
scryptSync("pw", randomBytes(16), 32, cost);
console.log(`scrypt N=2^21,r=8,p=1: ${((Date.now() - start) / 1000).toFixed(1)} s, needs about ${(128 * cost.N * cost.r) / 1024 ** 3} GiB by formula (128*N*r)`);
console.log("Node's default scrypt limit refuses this:");
try { scryptSync("pw", randomBytes(16), 32, { N: 2 ** 21, r: 8, p: 1 }); } catch (e) { console.log("  ", e.code); }

Output from a real run (Node 24):

tolerance 0       : true
tolerance NaN     : false   <- NaN > anything is false, so 'not expired'
tolerance '99999' : false   <- 1000 + '99999' is the string '100099999'
naive(NaN)        : NaN   <- NaN < 0 is false, so it is accepted
strict(NaN)       : must be a finite number >= 0
setTimeout(2**31) : resolved after 1 ms
setTimeout(Infinity): resolved after 0 ms
setTimeout(NaN)   : resolved after 1 ms
cache keys equal  : true true true
scrypt N=2^21,r=8,p=1: 3.7 s, needs about 2 GiB by formula (128*N*r)
Node's default scrypt limit refuses this:
   ERR_CRYPTO_INVALID_SCRYPT_PARAMS

1. Comparisons with NaN are always false

Every comparison with NaN is false, including NaN < 0, NaN > 0 and NaN === NaN. So:

  • if (x < 0) throw ... accepts NaN. The guard looks right and isn't.
  • An expiry check like now > exp + tolerance becomes "never expired" when tolerance or now is NaN. In our review, a JWT verifier with clockToleranceSec: NaN accepted a token that expired an hour earlier. A string tolerance did the same: 1000 + "99999" concatenates instead of adding.

Where does NaN come from? Number(undefined), parseInt(""), a missing environment variable run through arithmetic, 0/0. A typo in a config key is enough.

The fix is to write guards as an allow-list, not a deny-list:

if (!Number.isFinite(x) || x < 0) throw new RangeError("must be a finite number >= 0");

That one line (plus checking typeof if strings might arrive) closed most of the cases we found. The same pattern turned up in a retry/backoff helper (a NaN wait became a 1 ms wait), a rate limiter (cost: NaN), a health check (timeoutMs: NaN) and a file-lock wait: NaN, which waited forever because now() >= NaN never becomes true.

2. Timers above 2^31-1 milliseconds fire immediately

setTimeout stores its delay in a signed 32-bit integer. Anything above 2,147,483,647 ms (about 24.8 days), Infinity and NaN all become 1 millisecond, with only a TimeoutOverflowWarning on stderr. The output above shows setTimeout(2**31) resolving after 1 ms.

That is nasty because "no timeout" is a natural thing to express as Infinity: timeoutMs: Infinity makes a supervisor kill the child process immediately, and a sleep(30 * 24 * 3600 * 1000) returns at once. If you wrap timers, either reject out-of-range values with a clear error, or split long waits into steps of at most 2^31-1 ms. Treat Infinity as "don't set a timer at all".

3. JSON.stringify is not a safe cache key

A common memoize shortcut is JSON.stringify(args) as the key. But undefined, NaN and Infinity all serialise to null, so these calls share one cache entry:

JSON.stringify([undefined]) === JSON.stringify([null])   // true
JSON.stringify([NaN])       === JSON.stringify([null])   // true
JSON.stringify([Infinity])  === JSON.stringify([null])   // true

A function called with NaN can return the cached result computed for null. Map and Set serialise to {}, so all of them collide too, and BigInt throws. If you cache on arguments, build the key explicitly or refuse values you can't key.

4. Never trust a stored parameter to be reasonable

Password hashes are stored as strings that carry their own cost parameters, so you can raise the cost later. That makes the stored string an input. With scrypt, memory is about 128 × N × r bytes. We measured N=2^21, r=8 at 3.7 seconds and about 2 GiB on one core; a stored value claiming N=2^22, r=32, p=16 would, by the same formula, ask for roughly 16 GiB. Node's crypto.scrypt refuses such parameters by default (ERR_CRYPTO_INVALID_SCRYPT_PARAMS), but a library that raises maxmem to support its own settings removes that protection. If an attacker or a corrupted row can change the stored string, a login attempt can exhaust your server's memory.

The fix is a ceiling on what you'll accept from storage (we used 1 GiB and 64× the default work) and treating anything above it as "doesn't verify, needs rehash", not as an error that crashes the request.

A checklist you can paste into a code review

  • Every numeric option: is it checked with Number.isFinite, not just < 0?
  • Does a string like "1000" get rejected, or silently concatenated or coerced?
  • Every duration passed to a timer: can it exceed 2^31-1 ms, Infinity or NaN?
  • Is JSON.stringify used to build a key or to compare values?
  • Does a value read from a database, a cookie or a token set a cost, size or time limit? Is there a ceiling?
  • Is there a test per case, named for the behaviour ("refuses time options that would switch the expiry check off")?

The cheapest habit is also the best one: when you fix one of these, write the test first and watch it fail. A test you have never seen fail may not be testing anything.

← Alle artikelen

Een vraag of een idee?

Stuur ons een mail. Je praat direct met de mensen die de software bouwen en krijgt binnen 2 werkdagen antwoord.