javascript icon indicating copy to clipboard operation
javascript copied to clipboard

Look for crypto library using `self` keyword instead of `window`

Open jrsun opened this issue 2 years ago • 1 comments

The name of the global namespace varies in different execution environments. The self keyword allows accessing crypto in both the browser and WorkerGlobalScope (web workers/service workers), whereas window only works for the browser. This change allows the library to work in more environments than previously.

References

Window.self WorkerGlobalScope.self Web APIs available in Workers

jrsun avatar Apr 22 '22 20:04 jrsun

Hey, if anyone else finds this issue like I did and is using cloudflare workers, here's what worked for me:

import {monotonicFactory} from 'ulid'
// or import {factory} from 'ulid'

const prng = () => {
  const buffer = new Uint8Array(1)
  crypto.getRandomValues(buffer)
  return buffer[0] / 0xff
}
export const ulid = monotonicFactory(prng) // or factory(prng)

This will bypass the code that checks for browser crypto and allow you to set your own. The PRNG function is the same as used internally with a different global reference.

I think this package may be abandoned, I'm working on potentially forking it.

DavidJFelix avatar Jun 01 '22 13:06 DavidJFelix