Skip to content

Instantly share code, notes, and snippets.

@web-devel
Last active November 13, 2023 11:28
Show Gist options
  • Save web-devel/68a7f346500208846af1c14eb2ae174b to your computer and use it in GitHub Desktop.
Save web-devel/68a7f346500208846af1c14eb2ae174b to your computer and use it in GitHub Desktop.
Use Docker image to perform npm install and running node scripts

Problem

NPM is very popular / widespread. Typically JS developers run npm install/yarn install on dev machines and CI servers many times per day. Modern npm-based project usually brings thousands of packages. There are two types of threats:

  • Vulnerable packages targeting runtime of your app - can harvest user data / perform mining etc.
  • Vulnerable packages targeting your environment - can harvest ssh keys / auth tokens etc.

Threat #1 can be mitigated by npm audit / lockfiles / caches as typically there is some time span between dependency installation and go live.

Threat #2 is more dangerous as it takes place immediately after npm install is executed. One should keep in mind that when install performed any dependency can execute post install script which is regular node process. It can do anything whatever allowed to the current user. (That’s why sudo npm is double dangerous)

https://blog.npmjs.org/post/141702881055/package-install-scripts-vulnerability

Note on npm packages

That might be surprise but there is no relation between github repo and package in npm registry (which is used by yarn/pnpm also). One may publish any code as a package with a link to some existing popular github repo.

Proposed Solution

In order to protect your environment run node/npm in isolation, use docker node image

Example of npm install:

docker run -u node -v "$PWD":/home/node/app -w /home/node/app --rm node:10.14-alpine npm install

Running server:

docker run -u node -v "$PWD":/home/node/app -w /home/node/app -p 3000:3000 --rm node:10.14-alpine npm run start

Run interactive session

docker run -it --entrypoint /bin/bash -u node -v "$PWD":/home/node/app -w /home/node/app --rm node:10.14-alpine

In order to use it conveniently make shortcuts in .bashrc:

alias dn10 = 'docker run -u node -v "$PWD":/home/node/app -w /home/node/app --rm node:10.14-alpine'
alias dn10p = 'docker run -u node -v "$PWD":/home/node/app -w /home/node/app -p 3000:3000 --rm node:10.14-alpine'
alias dn10i = 'docker run -it --entrypoint /bin/bash -u node -v "$PWD":/home/node/app -w /home/node/app --rm node:10.14-alpine'

You can use yarn since it's also in node image

cd my_project
dn10 yarn install
dn10p yarn start
version: "2"
services:
node:
image: "node:8.9.4"
user: "node"
working_dir: /home/node/app
environment:
- NODE_ENV=production
volumes:
- ./:/home/node/app
ports:
- "3000:3000"
command: "npm start"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment