workers-sdk icon indicating copy to clipboard operation
workers-sdk copied to clipboard

🐛 BUG: Uncaught Error: Dynamic require of "node:crypto" is not supported

Open vbarbarosh opened this issue 2 years ago • 9 comments

Which Cloudflare product(s) does this pertain to?

Workers Runtime, Wrangler core

What version(s) of the tool(s) are you using?

[email protected]

What version of Node are you using?

v20.2.0

What operating system are you using?

Linux

Describe the Bug

Some time ago, I wrote a Cloudflare worker. Today, I added one small change to it. However, I wasn't able to deploy it because wrangler-cli showed me a message that it is too old and refused to work. After upgrading and spending a couple of hours trying to figure out how I could deploy previously working code with the new tool, I gave up.

Basically, this is my .js file, which I can't deploy:

const crypto = require('crypto');

addEventListener('fetch', async function (event) {
    event.respondWith(main(event.request, event).catch(function (error) {
        const m = crypto_encrypt_aes256('SECRET', JSON.stringify({...error, message: error.message, stack: error.stack}, null, 4));
        return new Response(`Failed\n\n${m.toString('base64')}\n`, {status: 400, 'Content-Type': 'text/plain'});
    }));
});

async function main(request, event)
{
    [...]
}

function crypto_encrypt_aes256(password, data)
{
    const iv = crypto.randomBytes(16);
    const key = crypto.createHash('sha256').update(password).digest();
    const cipher = crypto.createCipheriv('aes-256-ctr', key, iv);
    if (iv.length > 255) {
        throw new Error('iv size is too big');
    }
    return Buffer.concat([Buffer.from([iv.length]), iv, cipher.update(data), cipher.final()]);
}

With the old wrangler-cli I used webpack. How could I do it with the new version of wrangler?

Please provide a link to a minimal reproduction

No response

Please provide any relevant error logs

 ⛅️ wrangler 3.22.3
-------------------
Your worker has access to the following bindings:
- Vars:
  - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Total Upload: 3.72 KiB / gzip: 1.46 KiB

✘ [ERROR] A request to the Cloudflare API (/accounts/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/workers/scripts/xxxxxxxxxxxxxxxxx) failed.

  Uncaught Error: Dynamic require of "node:crypto" is not supported
    at null.<anonymous> (worker.js:7:11)
    at null.<anonymous>
  (file:///xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/src/index.js:1:16)
    at null.<anonymous> (worker.js:78:3)
   [code: 10021]

  
  If you think this is a bug, please open an issue at:
  https://github.com/cloudflare/workers-sdk/issues/new/choose

vbarbarosh avatar Jan 08 '24 22:01 vbarbarosh

It looks like you're trying to use Node's crypto module, which isn't supported by default in the Workers runtime. The best path forward will be to enable Node.js compatibility mode by adding this snippet to your wrangler.toml:

compatibility_flags = [ "nodejs_compat" ]

and modifying your import to be require("node:crypto") instead of require("crypto").

penalosa avatar Jan 09 '24 12:01 penalosa

I did all of this. The message I got I put into title.

The solution, which worked for me, is custom build:

wrangler.toml

name = "xxxxxxxxxxx"
main = "build/index.js"
compatibility_date = "2022-07-12"

account_id = "xxxxxxxxxxxxxxx"
workers_dev = true

[build]
command = "npm run build"
# cwd = "build"
# watch_dir = "build"

[vars]
XXXXXXXX = "YYYYYYYYYY"

webpack.config.js

const path = require('path');
const pkg = require('./package.json');
const webpack = require('webpack');

const config = {
    mode: 'production',
    target: 'webworker',
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'index.js',
    },
    plugins: [
        new webpack.ProvidePlugin({
            Buffer: ['buffer', 'Buffer'],
        }),
        new webpack.DefinePlugin({
            __NAME__: JSON.stringify(pkg.name),
            __VERSION__: JSON.stringify(pkg.version),
            __COMPILED_AT__: JSON.stringify(new Date()),
        })
    ],
    resolve: {
        fallback: {
            buffer: require.resolve('buffer'),
            crypto: require.resolve('crypto-browserify'),
            stream: require.resolve('stream-browserify'),
        },
    },
    performance: {
        hints: false,
    },
};

module.exports = config;

package.json

{
  "name": "xxxxxxxxxxxxxxx",
  "version": "0.0.0",
  "scripts": {
    "build": "webpack",
    "watch": "wrangler --config=wrangler.dev.toml dev",
    "deploy-dev": "wrangler --config=wrangler.dev.toml deploy",
    "deploy-prod": "wrangler --config=wrangler.prod.toml deploy"
  },
  "devDependencies": {
    "buffer": "^6.0.3",
    "buffer-browserify": "^0.2.5",
    "crypto-browserify": "^3.12.0",
    "stream-browserify": "^3.0.0",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4",
    "wrangler": "^3.22.3"
  }
}

vbarbarosh avatar Jan 09 '24 15:01 vbarbarosh

For others experiencing a similar error message, make sure your using 'import' instead of 'require'. Unfortunately many npm packages still use the 'require' format.

delphian avatar Apr 28 '24 12:04 delphian

I'm experiencing this as well but the require statement is in the remix package so I am not able to change that. Any suggestions?

Specifically /node_modules/@remix-run/node/dist/sessions/fileStorage.js on remix v2.7.2

mmiondev avatar May 02 '24 12:05 mmiondev

I'm facing the same issue. I've added compatibility_flags = [ "nodejs_compat" ] to wrangler.toml, following the instructions on https://developers.cloudflare.com/workers/runtime-apis/nodejs with import { Crypto } from 'node:crypto'; and I get exactly that error as well locally. So either something's still not supported here or the docs are wrong - or I don't get it.

sattes-faction avatar Jun 19 '24 06:06 sattes-faction

Trying to deploy a remix-run app to cloudflare with @remix-run/cloudflare also brought me to this thread

NeilWkz avatar Sep 21 '24 16:09 NeilWkz

Hit this issue today. I'm guessing the exact reason has to do with the file to bundle.


For me this happened with a ESM file containing require('crypto').

Wrangler (and maybe esbuild in it) emits this which apparently fails without a real require in runtime:

var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined")
    return require.apply(this, arguments);
  throw new Error('Dynamic require of "' + x + '" is not supported');
});

...

var crypto = __require2("crypto"); // FAIL

If the input file contains import 'crypto' instead, wrangler emits fine code that imports from polyfilled crypto.

IMO wrangler could do better to either support this imperfect input (this is not rare, not every npm packages ships perfect ESM). At least the error message could be improved.

jokester avatar Oct 06 '24 14:10 jokester

@jokester what error do you see when you use Wrangler v3.80.0 (https://github.com/cloudflare/workers-sdk/releases/tag/wrangler%403.80.0)

See: https://github.com/cloudflare/workers-sdk/pull/6872

irvinebroque avatar Oct 07 '24 00:10 irvinebroque

@irvinebroque Thanks. I tested with wrangler 3.80.0 and realized my previous report could be invalid (the input to wrangler was already a dynamic require).

Wrangler 3.80.0 has no problem recognizing non-dynamic requires like require('node:crypto') , and provide them with polyfills.

jokester avatar Oct 12 '24 12:10 jokester