ulid / javascript

Universally Unique Lexicographically Sortable Identifier
MIT License
3.04k stars 107 forks source link

Crypto API isn't detected on alternative platforms #72

Open blakeembrey opened 4 years ago

blakeembrey commented 4 years ago

I run across this using Cloudflare Workers. It should be possible to use this library by instead checking for a crypto global instead of trying to detect `window. Documentation from Cloudflare here: https://developers.cloudflare.com/workers/reference/apis/web-crypto/.

perry-mitchell commented 4 years ago

Hoping this aligns with the original point of this issue, but I've noticed too that on some platforms like Mobile Safari on iOS 8-10.3, crypto is window.webkitCrypto, not crypto or msCrypto as read in the source: https://github.com/ulid/javascript/blob/master/lib/index.ts#L123

Along with using a generic global lookup, perhaps expand the crypto lookup to include the webkit reference?

SokichiFujita commented 3 years ago

I also could not use ulid in Web Worker of Chrome or Safari by the same reason.

perry-mitchell commented 3 years ago

@SokichiFujita Added an issue for that at #83. Should be fixed by my PR at #82.

DavidJFelix commented 2 years ago

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.

perry-mitchell commented 2 years ago

@DavidJFelix I've made a supported fork here, in case that's of interest: ulidx. There's also another fork designed specifically for cloudflare workers: ulid-workers.