Skip to content

fix: use crypto.getRandomValues on non-secure origins - #734

Open
smartcalsystems-sketch wants to merge 1 commit into
MergeFi:mainfrom
smartcalsystems-sketch:fix-idempotency-key-getrandomvalues-706
Open

smartcalsystems-sketch wants to merge 1 commit into
MergeFi:mainfrom
smartcalsystems-sketch:fix-idempotency-key-getrandomvalues-706

Conversation

@smartcalsystems-sketch

Copy link
Copy Markdown

Problem

crypto.randomUUID requires a secure context (HTTPS or localhost) and is missing on any non-secure origin, including a plain-http staging deploy — not just "very unlikely browsers" as the old comment assumed. When it's missing, generateIdempotencyKey fell all the way back to Math.random(), which is predictable and collision-prone. Since idempotency keys are scoped per caller on the backend, a collision replays someone's cached response instead of executing the request.

Fix

crypto.getRandomValues does not require a secure context and is still available in that case, so it's now used as the middle fallback: draw 16 random bytes, fix the RFC 4122 v4 version/variant bits, format as a standard UUID string. Math.random is now only reached if the Web Crypto API is entirely absent.

Testing

  • Added 3 tests that stub out crypto.randomUUID to simulate a non-secure origin: valid UUID v4 format, uniqueness across 50 calls, and an explicit assertion that Math.random is never called when getRandomValues is available.
  • Full utils.test.ts suite: 96/96 passing (93 pre-existing + 3 new), zero regressions.
  • tsc --noEmit and eslint clean on both changed files.

Closes #706

…#706)

crypto.randomUUID requires a secure context (HTTPS or localhost), but
that's not the only non-secure case in practice -- a plain-http staging
deploy hits it too. When randomUUID is missing, generateIdempotencyKey
fell all the way back to Math.random, which is predictable and
collision-prone. Since idempotency keys are scoped per caller on the
backend, a collision replays someone's cached response instead of
executing the request.

crypto.getRandomValues does not require a secure context and is still
available in that case, so prefer it: draw 16 random bytes, fix the
RFC 4122 v4 version/variant bits, and format as a standard UUID. Only
fall back to Math.random if the Web Crypto API is entirely absent.
@vercel

vercel Bot commented Oct 13, 2026

Copy link
Copy Markdown

@smartcalsystems-sketch is attempting to deploy a commit to the chonilius' projects Team on Vercel.

A member of the Team first needs to authorize it.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

generateIdempotencyKey falls back to Math.random on non-secure origins

1 participant