PackShip v2 is now available! 🚀 Learn more

Security Best Practices

Security is a critical aspect of package development. This guide outlines best practices for ensuring the security of your PackShip projects and the packages you publish.

Dependency Security

Auditing Dependencies

Regularly audit your dependencies for security vulnerabilities:

npm audit

To automatically fix vulnerabilities when possible:

npm audit fix

For more severe issues that require major version updates:

npm audit fix --force

Always review the changes made by npm audit fix --force as they might include breaking changes.

Keeping Dependencies Updated

Regularly update your dependencies to get security patches:

npm update

Use tools like npm-check-updates to identify outdated dependencies:

# Install the tool
npm install -g npm-check-updates

# Check for updates
ncu

# Apply updates to package.json
ncu -u

# Install updated packages
npm install

Minimizing Dependencies

Each dependency you add increases your security risk surface. Consider these guidelines:

  • Only add dependencies that provide essential functionality
  • Prefer well-maintained, popular packages with good security records
  • Consider implementing simple functionality yourself instead of adding a dependency
  • Regularly review and remove unused dependencies

Code Security

Input Validation

Always validate and sanitize inputs to prevent injection attacks:

// Bad - vulnerable to injection
function processUserInput(input) {
  eval(input); // Never do this!
}

// Good - validate input
function processUserInput(input) {
  if (typeof input !== 'string' || !input.match(/^[a-zA-Z0-9]+$/)) {
    throw new Error('Invalid input');
  }
  // Process the validated input
}

Avoiding Dangerous Functions

Avoid using functions that can lead to security vulnerabilities:

  • eval() - Executes arbitrary code
  • Function() constructor - Similar to eval()
  • setTimeout() / setInterval() with string arguments
  • document.write() - Can enable XSS attacks
  • innerHTML - Can enable XSS attacks if not properly sanitized

Secure DOM Manipulation

When manipulating the DOM, use safe methods to prevent XSS attacks:

// Bad - vulnerable to XSS
element.innerHTML = userProvidedContent;

// Good - use textContent for text
element.textContent = userProvidedContent;

// Good - create elements safely
const newElement = document.createElement('div');
newElement.textContent = userProvidedContent;
element.appendChild(newElement);

npm Security

Two-Factor Authentication

Enable two-factor authentication (2FA) for your npm account to prevent unauthorized access:

  • Log in to your npm account at npmjs.com
  • Go to Account Settings
  • Enable Two-Factor Authentication

You can also enable 2FA from the command line:

npm profile enable-2fa auth-only

npm Tokens

Use npm tokens for CI/CD pipelines instead of your npm password:

# Create a new token
npm token create

# List existing tokens
npm token list

# Revoke a token
npm token revoke <token_id>

Never commit npm tokens to your repository. Use environment variables or secrets management in your CI/CD system.

Package Access Control

For organization scoped packages, you can control who has access to publish:

# Add a user as a maintainer
npm access grant read-write username @scope/package

# Remove a user
npm access revoke username @scope/package

# List package permissions
npm access ls-collaborators @scope/package

Secure Development Practices

Using HTTPS

Always use HTTPS for external resources and API calls:

// Bad - insecure HTTP
fetch('http://api.example.com/data');

// Good - secure HTTPS
fetch('https://api.example.com/data');

Content Security Policy

If your package includes a web component, consider implementing a Content Security Policy (CSP) to prevent XSS attacks:

// Example CSP header
{
  'Content-Security-Policy': "default-src 'self'; script-src 'self'; object-src 'none';"
}

Secure Storage

If your package needs to store sensitive data:

  • Never store sensitive data in client-side code
  • Use environment variables for configuration
  • Consider using a secure storage solution
  • Encrypt sensitive data at rest

Security Tools

Static Analysis

Use static analysis tools to identify potential security issues:

# Install ESLint security plugin
npm install --save-dev eslint-plugin-security

# Add to your ESLint configuration
// .eslintrc.js
module.exports = {
  plugins: ['security'],
  extends: ['plugin:security/recommended']
};

Snyk

Snyk is a tool that helps you find and fix vulnerabilities in your dependencies:

# Install Snyk
npm install -g snyk

# Authenticate
snyk auth

# Test your project
snyk test

# Monitor your project
snyk monitor

GitHub Security Features

If you host your code on GitHub, take advantage of its security features:

  • Enable Dependabot alerts for vulnerability notifications
  • Use Dependabot security updates to automatically fix vulnerabilities
  • Enable code scanning with CodeQL to find security issues in your code
  • Set up branch protection rules to prevent force pushes and require reviews

Security Checklist

Use this interactive checklist to track your progress in implementing security best practices for your package:

Security Checklist

Progress: 0%
  • Enable 2FA for your npm account
  • Regularly audit dependencies with npm audit
  • Keep dependencies updated
  • Validate and sanitize all inputs
  • Avoid dangerous functions like eval()
  • Use HTTPS for all external resources
  • Implement proper error handling without exposing sensitive information
  • Use static analysis tools to identify security issues
  • Follow the principle of least privilege
  • Document security considerations for users of your package