I'm trying to run a npm install
command with a preinstall script at my package.json
. I know it's antipattern but I need to run some scripts as root.
It's working fine by adding a .npmrc
file containing unsafe-perm = true
to my root directory. But it's not working by add a config property in my package.json
file:
{
"name": "foo",
"version": "1.4.4",
"config": {
"unsafe-perm":true
},
"scripts" : {
"preinstall" : "npm install -g bower"
}
}
// It is not working
According with NPM config docs it's ok adding this property in my package file. I want to understand why it's not working.
When you add that property, you are adding it to the environment of your script with the prefix npm_config_package
:
$ cat package.json
{
"config": { "unsafe-perm": true }
}
$ npm run env | grep perm
$ npm run env | grep perm
npm_package_config_unsafe_perm=true
npm_config_unsafe_perm=true
$ sudo npm run env | grep perm
npm_package_config_unsafe_perm=true
npm_config_unsafe_perm=
$
This is for security reasons, sort of. It would not be good for an arbitrary package from the npm
registry to allow you to change npm
's config settings (e.g., what if it set prefix to /etc
and installed a file named passwd
)
However you can still get around it by setting the environment variable in on your script line (this will not work on Windows):
$ cat package.json
{
"config": { "unsafe-perm": true },
"scripts": { "foo": "npm_config_unsafe_perm=true env" }
}
$ npm run foo | grep unsafe_perm
npm_config_unsafe_perm=true
npm_package_config_unsafe_perm=true
npm_lifecycle_script=npm_config_unsafe_perm=true env
npm_package_scripts_foo=npm_config_unsafe_perm=true env
$ sudo npm run foo | grep unsafe_perm
npm_config_unsafe_perm=true
npm_package_config_unsafe_perm=true
npm_lifecycle_script=npm_config_unsafe_perm=true env
npm_package_scripts_foo=npm_config_unsafe_perm=true env
$
This may be a bug in npm
though, so I would recommend not relying on this behavior. Can you get away with using a different user than root
?
Source: Tested with npm@2.6.1
on OSX. I am a support volunteer on the npm
issue tracker, https://github.com/npm/npm/issues.
unsafe-perm
Default: false if running as root, true otherwise
Type: Boolean
Set to true to suppress the UID/GID switching when running package scripts. If set explicitly to false, then installing as a non-root user will fail.
see the https://docs.npmjs.com/misc/config#unsafe-perm