A CLI to lint a lockfile for security policies
npx @tessl/cli install tessl/npm-lockfile-lint@4.14.0lockfile-lint is a comprehensive security linting solution for JavaScript lockfiles (package-lock.json, yarn.lock, npm-shrinkwrap.json) that enforces security policies and detects potential vulnerabilities in package dependencies. It consists of a CLI tool (lockfile-lint) and a core API library (lockfile-lint-api) that enables both command-line and programmatic validation of lockfiles against predefined security policies such as allowing only specific hosts, enforcing HTTPS protocols, and preventing malicious package injections.
npm install lockfile-lint (includes lockfile-lint-api as dependency)npm install lockfile-lint-api (for direct API usage only)This is primarily a CLI tool accessed via the lockfile-lint executable. For programmatic usage:
CLI Package (lockfile-lint):
const { runValidators } = require('lockfile-lint/src/main');
const config = require('lockfile-lint/src/config');Core API Package (lockfile-lint-api):
const {
ParseLockfile,
ValidateHost,
ValidateHttps,
ValidatePackageNames,
ValidateScheme,
ValidateUrl,
ValidateIntegrity
} = require('lockfile-lint-api');For ES modules:
import { runValidators } from 'lockfile-lint/src/main';
import {
ParseLockfile,
ValidateHost,
ValidateHttps
} from 'lockfile-lint-api';# Basic validation with HTTPS enforcement
lockfile-lint --path yarn.lock --validate-https
# Validate against specific hosts
lockfile-lint --path package-lock.json --allowed-hosts npm yarn verdaccio
# Multiple validations with custom schemes
lockfile-lint --path yarn.lock --allowed-hosts yarn github.com --allowed-schemes "https:" "git+https:"
# Validate package names match URLs
lockfile-lint --path yarn.lock --allowed-hosts npm --validate-package-names
# Validate integrity hashes
lockfile-lint --path package-lock.json --validate-integrity
# Multiple lockfiles with glob patterns
lockfile-lint --path '/path/to/**/package-lock.json' --validate-https --allowed-hosts npmCreate .lockfile-lintrc.json:
{
"path": "yarn.lock",
"allowedHosts": ["npm", "github.com"],
"validateHttps": true,
"validatePackageNames": true,
"format": "pretty"
}Or in package.json:
{
"lockfile-lint": {
"path": "package-lock.json",
"allowedHosts": ["npm"],
"validateHttps": true,
"validateIntegrity": true
}
}Core lockfile parsing functionality provided by the lockfile-lint-api package for handling npm and yarn lockfiles.
/**
* ParseLockfile class for parsing and analyzing lockfile contents
* @param options - Configuration options for parsing
* @param options.lockfilePath - Path to lockfile (optional if lockfileText provided)
* @param options.lockfileText - UTF-8 string content (optional if lockfilePath provided)
* @param options.lockfileType - Type: "npm", "npmjs", "yarn", "yarnpkg" (optional, auto-detected)
*/
class ParseLockfile {
constructor(options: {
lockfilePath?: string;
lockfileText?: string;
lockfileType?: "npm" | "npmjs" | "yarn" | "yarnpkg";
});
/** Parse lockfile and return normalized package structure */
parseSync(): { type: "success"; object: Object };
/** Check if lockfile type was explicitly provided */
isLockfileTypeGiven(): boolean;
/** Resolve package manager function for lockfile type */
resolvePkgMgrForLockfile(): Function;
/** Extract clean package name from npm lockfile paths */
extractedPackageName(packageName: string): string;
}Usage Example:
const { ParseLockfile } = require('lockfile-lint-api');
const parser = new ParseLockfile({
lockfilePath: './package-lock.json'
});
const result = parser.parseSync();
console.log('Lockfile type:', result.type);
console.log('Package count:', Object.keys(result.object).length);Individual validator classes from lockfile-lint-api for custom validation workflows.
/**
* Host validation - validates package registry hosts
* @param packages - Parsed lockfile packages object
* @param debug - Debug function (optional)
*/
class ValidateHost {
constructor({ packages: Object, debug?: Function });
/** Validate hosts with options */
validate(hosts: string[], options?: {
emptyHostname?: boolean;
allowedHosts?: string[];
allowedUrls?: string[];
}): ValidationResult;
/** Validate single package against hosts */
validateSingle(packageName: string, hosts: string[]): boolean;
}
/**
* HTTPS protocol validation - ensures all packages use secure protocols
*/
class ValidateHttps {
constructor({ packages: Object });
/** Validate all packages use HTTPS */
validate(): ValidationResult;
}
/**
* Package name validation - ensures package names match their resolved URLs
*/
class ValidatePackageNames {
constructor({ packages: Object });
/** Validate package names with optional aliases */
validate(packageNameAliases?: string[]): ValidationResult;
}
/**
* Protocol scheme validation - validates allowed URI schemes
*/
class ValidateScheme {
constructor({ packages: Object });
/** Validate allowed schemes */
validate(schemes: string[]): ValidationResult;
}
/**
* URL validation - validates specific allowed URLs
*/
class ValidateUrl {
constructor({ packages: Object });
/** Validate against allowed URLs */
validate(allowedUrls: string[], options?: Object): ValidationResult;
/** Validate single package against URLs */
validateSingle(packageName: string, allowedUrls: string[]): boolean;
}
/**
* Integrity hash validation - validates SHA512 integrity hashes
*/
class ValidateIntegrity {
constructor({ packages: Object });
/** Validate integrity hashes with exclusion options */
validate(options?: {
integrityExclude?: string[];
}): ValidationResult;
/** Validate single package integrity */
validateSingle(packageName: string): boolean;
}
interface ValidationResult {
type: "success" | "error";
errors: Array<{
message: string;
package: string;
}>;
}Direct API Usage Example:
const { ParseLockfile, ValidateHost, ValidateHttps } = require('lockfile-lint-api');
// Parse lockfile
const parser = new ParseLockfile({ lockfilePath: './yarn.lock' });
const { object: packages } = parser.parseSync();
// Validate hosts
const hostValidator = new ValidateHost({ packages });
const hostResult = hostValidator.validate(['npm', 'github.com'], {
emptyHostname: false
});
// Validate HTTPS
const httpsValidator = new ValidateHttps({ packages });
const httpsResult = httpsValidator.validate();
if (hostResult.type === 'error' || httpsResult.type === 'error') {
console.error('Validation failed');
process.exit(1);
}Primary interface for linting lockfiles with comprehensive security validation options.
lockfile-lint [options]
# Required Options
--path, -p <string> # Path to lockfile or glob pattern
# Lockfile Type
--type, -t <string> # Lockfile type: "npm" or "yarn" (auto-detected if omitted)
# Security Validations
--validate-https, -s # Validates HTTPS protocol usage
--allowed-hosts, -a <array> # Validates allowed hosts (supports npm, yarn, verdaccio aliases)
--allowed-schemes, -o <array> # Validates allowed URI schemes (conflicts with --validate-https)
--allowed-urls, -u <array> # Validates specific allowed URLs
--validate-package-names, -n # Validates package names match URLs (requires --allowed-hosts)
--validate-integrity, -i # Validates sha512 integrity hashes
# Configuration Options
--empty-hostname, -e # Allow empty hostnames (default: true)
--allowed-package-name-aliases, -l <array> # Package name aliases (format: "alias:package")
--integrity-exclude <array> # Exclude packages from integrity validation
--format, -f <string> # Output format: "pretty" or "plain" (default: "pretty")
# Help & Info
--help, -h # Display help information
--version # Display version informationExit Codes:
0: Success, no security issues detected1: Error, security issues detected or command failedHost Aliases:
npm → https://registry.npmjs.orgyarn → https://registry.yarnpkg.comverdaccio → https://registry.verdaccio.orgCore validation function for custom implementations and integrations.
/**
* Executes validation checks on lockfile using specified validators
* @param options - Validation configuration
* @param options.type - Lockfile type ("npm" or "yarn")
* @param options.path - Path to lockfile
* @param options.validators - Array of validator configurations
* @returns Validation results summary
*/
function runValidators({
type: string,
path: string,
validators: ValidatorConfig[]
}): ValidationResult;
interface ValidatorConfig {
name: string; // Validator function name
values: any; // Validation values/configuration
options: object; // Validation options
}
interface ValidationResult {
validatorCount: number; // Total validators executed
validatorFailures: number; // Number of validation failures
validatorSuccesses: number; // Number of validation successes
}Usage Example:
const { runValidators } = require('lockfile-lint/src/main');
const result = runValidators({
path: './yarn.lock',
type: 'yarn',
validators: [
{
name: 'validateHosts',
values: ['npm', 'github.com'],
options: {
emptyHostname: true,
allowedUrls: ['https://github.com/org/repo#hash']
}
},
{
name: 'validateHttps',
values: true,
options: {}
}
]
});
console.log(`Executed ${result.validatorCount} validators`);
if (result.validatorFailures > 0) {
console.error(`Found ${result.validatorFailures} security issues`);
process.exit(1);
}Configuration file discovery and CLI argument parsing.
/**
* Parses CLI arguments and loads configuration files
* @param argv - Command line arguments array
* @param exitProcess - Whether to exit process on error (default: false)
* @param searchFrom - Directory to search for config files (default: process.cwd())
* @returns Parsed configuration object
*/
function loadConfig(
argv: string[],
exitProcess?: boolean,
searchFrom?: string
): ConfigObject;
interface ConfigObject {
path: string; // Lockfile path/pattern
type?: string; // Lockfile type
format: 'pretty' | 'plain'; // Output format
'validate-https'?: boolean; // HTTPS validation
'allowed-hosts'?: string[]; // Allowed hosts
'allowed-schemes'?: string[]; // Allowed schemes
'allowed-urls'?: string[]; // Allowed URLs
'validate-package-names'?: boolean; // Package name validation
'validate-integrity'?: boolean; // Integrity validation
'empty-hostname'?: boolean; // Allow empty hostnames
'allowed-package-name-aliases'?: string[]; // Package aliases
'integrity-exclude'?: string[]; // Integrity exclusions
}Individual validation managers that wrap lockfile-lint-api functionality.
/**
* Validates allowed hosts for package URLs
*/
function ValidateHostManager({
path: string,
type: string,
validatorValues: string[],
validatorOptions: {
emptyHostname?: boolean,
allowedUrls?: string[]
}
}): ValidationResult;
/**
* Validates HTTPS protocol usage
*/
function ValidateHttpsManager({
path: string,
type: string,
validatorValues: boolean,
validatorOptions: object
}): ValidationResult;
/**
* Validates package names match their resolved URLs
*/
function ValidatePackageNamesManager({
path: string,
type: string,
validatorValues: boolean,
validatorOptions: {
allowedPackageNameAliases?: string[]
}
}): ValidationResult;
/**
* Validates allowed URI schemes
*/
function ValidateSchemeManager({
path: string,
type: string,
validatorValues: string[],
validatorOptions: object
}): ValidationResult;
/**
* Validates allowed URLs
*/
function ValidateUrlManager({
path: string,
type: string,
validatorValues: string[],
validatorOptions: object
}): ValidationResult;
/**
* Validates integrity hash formats (sha512)
*/
function ValidateIntegrityManager({
path: string,
type: string,
validatorValues: boolean,
validatorOptions: {
integrityExclude?: string[]
}
}): ValidationResult;
interface ValidationResult {
type: 'success' | 'error';
errors: ValidationError[];
}
interface ValidationError {
message: string;
package: object; // Package details from lockfile
}lockfile-lint uses cosmiconfig for configuration file discovery, supporting:
package.json "lockfile-lint" key.lockfile-lintrc (JSON/YAML).lockfile-lintrc.json/.yaml/.yml.lockfile-lintrc.jslockfile-lint.config.jsConfiguration files use camelCase property names (e.g., allowedHosts not allowed-hosts).
package-lock.json, npm-shrinkwrap.jsonyarn.lockLockfile type is auto-detected from filename if --type is not specified.
Common Error Scenarios:
Output Formats:
pretty (default): Colored output with status symbolsplain: Plain text output without colors or symbolsDebug Mode:
DEBUG=* lockfile-lint --path yarn.lock --validate-httpsProvides detailed logging of validation processes and configuration loading.