Common Misconfigurations
- Running untrusted packages’ scripts automatically
- Using unsafe script commands
- Not validating environment variables in scripts
- Missing script injection protection
- Excessive permissions in scripts
Vulnerable Example
Secure Solution
Key Commands for Managing Scripts
Understanding these commands is critical for implementing the security practices described above.1. Running a Script
This is the standard command to execute a script defined in yourpackage.json scripts object.
test, start, stop, and restart have shortcuts and can be run without the run keyword (e.g., npm test).
2. Disabling All Lifecycle Scripts
This is the most important command for securing your environment, as shown in the.npmrc solution. It prevents potentially malicious preinstall, install, and postinstall scripts from running automatically when you add packages.
3. Running npm install Safely (One Time)
If you don’t want to set ignore-scripts permanently but want to install a new, untrusted package safely, you can use the --ignore-scripts flag for a single command:
4. Listing All Available Scripts
To see all scripts defined in thepackage.json, simply run:
5. Passing Arguments to Scripts
This is essential for the secure pattern of using Node.js scripts. To pass arguments (like--validate in the example), you must use -- to separate the npm command from the arguments you want to pass to your script.
-- are for npm itself; any arguments after are for your script.
Best Practices
- Set
ignore-scripts=truein.npmrc. - Validate all environment variables.
- Use dedicated script files instead of inline commands.
- Avoid shell command execution when possible.
- Implement proper input validation.
- Never use
eval()orFunction()with user input.

