Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
rakeshpai opened this issue Aug 13, 2023 · 1 comment
Open

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

rakeshpai opened this issue Aug 13, 2023 · 1 comment

Comments

@rakeshpai
Copy link

rakeshpai commented Aug 13, 2023

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.

fido2-lib/lib/toolbox.js

Lines 22 to 38 in 9da9eb9

import * as platformCrypto from "crypto";
import * as peculiarCrypto from "@peculiar/webcrypto";
let webcrypto;
if ((typeof self !== "undefined") && "crypto" in self) {
// Always use crypto if available natively (browser / Deno)
webcrypto = self.crypto;
} else {
// Always use node webcrypto if available ( >= 16.0 )
if(platformCrypto && platformCrypto.webcrypto) {
webcrypto = platformCrypto.webcrypto;
} else {
// Fallback to @peculiar/webcrypto
webcrypto = new peculiarCrypto.Crypto();
}
}

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
Copy link
Member

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants