Issue with crypto (native node modules?)

So I’m currently using typescript/node.js with serverless and I am using a library called openpgp in one of my services. Testing these services in my environment without serverless, they run fine. However, when I invoke the test with sls, I get

Error --------------------------------------------------

Cannot find module ‘crypto’

Crypto is used by openpgp and the only reason that it is being used in my environment. Is there an issue with native node modules or another way I should go about this? I am only having this issue when invoking through sls.

Only thing that’s really being returned from my service

const options = {
    message: openpgp.message.readArmored(encryptedData),
    privateKey: privKeyObj
};

return openpgp.decrypt(options)
    .then((plaintext) => {
        return plaintext.data;
    });

in the handler, I’m returning the typical callback(null, response) from the resolved promise

Thanks, I’ve tried many different options to no avail.

We’re using crypto directly (no openpgp) without any problems. Our Lambda’s are all written in TypeScript and use Node 6.

It could be a red herring. ‘crypto’ is a built-in module in node, so it should always be available.

If openpgp is using native modules however it could be that those modules are failing to load. You have to make sure the binaries you’re publishing are compatible with the operating system the lambdas are running in (e.g linux).

So if you are publishing from mac or windows you will need to build linux binaries before publishing. Fortunately this is pretty easy to do for both systems using docker.

What I do before publish is:

  1. Clean my build directory
  2. Do a fresh build and copy of all code back into the build dir
  3. Use docker to linux install / build of all dependencies.
  4. sls deploy

So for that 3rd step what that looks like for me essentially is this:

$ docker run --rm -v "$PWD/build":/usr/src/app -w /usr/src/app node:6 npm install --production

This will download a linux container running node v6.11.0, then run the command npm install --production with my ./build folder sym-linked to the /usr/src/app folder on the container.

Once docker is done the end result is that I now have a ./build/node_modules folder which is full of linux binaries.

Pro Tips:

  1. Travis-ci supports docker, you can replicate this and do deployments from automated builds on travis
  2. Unless your host OS is also linux you won’t be able to run unit tests anymore without either cleaning and re-installing without docker or making your unit tests run inside docker also.
1 Like

Thanks a lot Justin, this was exactly the issue. We ended up requiring ec2 for many other irrelevant reasons but this helped me in another project. I did exactly what you were talking about and got it working. Thanks again man! :grin:

1 Like