webauthn-open-source / fido2-lib

A node.js library for performing FIDO 2.0 / WebAuthn server functionality
https://webauthn.io
MIT License
409 stars 120 forks source link

Usage in edge environments - Cloudflare workers, Vercel edge #135

Open rakeshpai opened 1 year ago

rakeshpai commented 1 year ago

I'm trying to use this lib in an edge runtime using next.js's Edge runtime, which like the browser has a global crypto object, and not an importable module for crypto. This is also how Cloudflare Workers behaves, and I believe this is part of the WinterCG common minimum API.

The issue is that the code in toolbox.ts imports the "crypto" module, which doesn't exist in such environments. https://github.com/webauthn-open-source/fido2-lib/blob/9da9eb90f32f8f6bc49eabd2d9873872812c6323/lib/toolbox.js#L22-L38

It seems that the node.js crypto module is only used in these lines and nowhere else in this package.

While I'm not familiar with @peculiar/webcrypto, it seems that it exists solely for this purpose - to provide an abstraction over such issues and always point to the natively supported crypto implementation. I might be wrong about this - again, not familiar with @peculiar/webcrypto.

Could you consider not importing the native crypto module, and instead just using the @peculiar/webcrypto module? The implication of this is that lines 31-34 above will go away, and when using node.js, all calls to the crypto module will always go through @peculiar/webcrypto, thus supporting a larger number of runtimes.

JamesCullum commented 1 year ago

Hey rakeshpai, thanks for the question. Basically the module tries to import the native and global crypto (L26), and has two layers of fallbacks if this is not supported - first using a platform-specific crypto, and then using JS emulation.

So if your environment has one of the fallbacks before @peculiar/webcrypto, it will use those and should never use peculiar.

Do you maybe have a simple example for an environment where this code leads to issues?