mirror of
https://github.com/hanzoai/iam-js-sdk.git
synced 2026-10-30 18:34:08 +00:00
The OAuth 2.0 "state" parameter is the canonical defence against CSRF
on the authorization endpoint (RFC 6749 §10.12). It must be
unguessable to an attacker.
Previously `getOrSaveState` used `Math.random().toString(36).slice(2)`,
which:
- is not cryptographically secure (predictable PRNG)
- produces ~10 chars of base36 (~52 bits of effective entropy at best,
far less in practice because Math.random is not uniform)
This switches state generation to a Web Crypto `getRandomValues`-based
helper with a Node `crypto.randomFillSync` fallback for SSR/test
environments where `window.crypto` is not polyfilled (older jsdom).
The output is 32 random bytes encoded as URL-safe base64 (RFC 4648 §5)
without padding — 43 chars, 256 bits of entropy.
Adds two tests covering:
- state has the expected length and only URL-safe base64 chars
- states are unique across many instances (collision probability ~2^-244)
No public API change. `getOrSaveState` keeps the same signature.