Skip to content

fix: replace Math.random() with crypto.randomUUID() in generateUUID()#691

Open
derek-codebridge wants to merge 1 commit into
GoogleChromeLabs:mainfrom
derek-codebridge:fix/use-crypto-randomuuid
Open

fix: replace Math.random() with crypto.randomUUID() in generateUUID()#691
derek-codebridge wants to merge 1 commit into
GoogleChromeLabs:mainfrom
derek-codebridge:fix/use-crypto-randomuuid

Conversation

@derek-codebridge
Copy link
Copy Markdown

@derek-codebridge derek-codebridge commented Apr 19, 2026

Problem

generateUUID() uses Math.random() to produce message correlation IDs:

function generateUUID(): string {
  return new Array(4)
    .fill(0)
    .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))
    .join("-");
}

Two issues:

  1. Not cryptographically randomMath.random() is a PRNG, not a CSPRNG. While these IDs never leave the browser, using Math.random() for ID generation is a code quality issue that static analysis tools flag.
  2. Not valid UUIDs — the function is named generateUUID() but produces hex-hex-hex-hex strings that don't conform to RFC 4122.

Fix

function generateUUID(): string {
  return crypto.randomUUID();
}

crypto.randomUUID() is available in all environments where comlink runs:

  • Browsers: Chrome 92+, Firefox 95+, Safari 15.4+ (July 2021+)
  • Web Workers: same as main thread
  • Service Workers: same as main thread
  • Node.js: global crypto.randomUUID() available since Node.js 19

Testing

No test changes needed — this is a drop-in replacement with identical semantics for the callers. The ID is only used as a pendingListeners map key within the same process.

crypto.randomUUID() is available in all environments where comlink runs:
browsers (Chrome 92+, Firefox 95+, Safari 15.4+), Web Workers, Service
Workers, and Node.js 19+. The previous implementation used Math.random()
which is not cryptographically random and also produced non-RFC-4122
identifiers despite the function being named generateUUID.
@google-cla
Copy link
Copy Markdown

google-cla Bot commented Apr 19, 2026

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@derek-codebridge
Copy link
Copy Markdown
Author

Done. CLA Completed.

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.

1 participant