javascript icon indicating copy to clipboard operation
javascript copied to clipboard

Crypto API isn't detected on alternative platforms

Open blakeembrey opened this issue 5 years ago • 5 comments

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/.

blakeembrey avatar May 20 '20 02:05 blakeembrey

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?

perry-mitchell avatar Nov 05 '20 11:11 perry-mitchell

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

SokichiFujita avatar Dec 21 '20 16:12 SokichiFujita

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

perry-mitchell avatar Mar 26 '21 08:03 perry-mitchell

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

@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.

perry-mitchell avatar Jun 03 '22 10:06 perry-mitchell