Ran into a usage of
npm config set unsafe-perm true in the codebase and was wondering what it did. A quick google search results in this fairly detailed article about the history of this change, where it originated etc.
The key takeaway from that article was that this feature was added in 2011 to essentially not require sudo
But, this article is 2 years old and there’s been some updates since. Namely:
- unsafe-perm does not show up in the docs for npm v8.x
- it does show up for npm v6.x
In order to understand the reasoning behind the original
unsafe-perm feature, you need a good understanding of file permissions model in linux.
The gist of it is there are three groups of users:
- group and
- anyone else
This forms the basis for file permissions, the numbering system (
755) and all the
chmod commands you may have to run to allow files to be run by specific users (like your CI machine user).
In addition to these three categories, there’s also the root user that has unlimited powers and access. The root user or super user has access to everything and you enter into the root user mode when using the
Typically, it is dangerous to run any command as sudo unless you know exactly what you are doing because of how limitless the command is. It can write any file to any location, execute any script and has too much freedom.
Knowing that, let’s read through v6 docs of npm to see what this config flag is meant to do.
If npm was invoked with root privileges, then it will change the uid to the user account or uid specified by the
userconfig, which defaults to
nobody. Set the
unsafe-permflag to run scripts with root privileges.
By default, npm will avoid running as root user. It makes sense given the implications. You wouldn’t want some random npm script (postinstall or preinstall) to run as super user and make a bunch of changes. When you run an npm install with sudo, it will try to change the user to whoever owns the current working directory. You can override this behavior using the
unsafe-perm flag. Setting it to true in v6 would have allowed you to run npm install as the root user.
You can opt out of this behavior if you want. Setting the flag to true will prevent switching the user and group when running scripts.
unsafe-perm flag does not appear anywhere in the latest npm documentation (v8 as of this writing). It appears that the behavior of this command changed on around Nov 2020 and was introduced as of v7.
When npm is run as root, scripts are always run with the effective uid and gid of the working directory owner.
Bottom line is if you were using it in a project earlier, you probably don’t need it anymore. Try removing it. If you are running into issues in a CI environment, your CI user probably doesn’t have the required permissions.
In general, avoid using
sudo when installing anything whether it’s via