A CLI to lint a lockfile for security policies
npx @tessl/cli install tessl/npm-lockfile-lint@4.14.00
# lockfile-lint
1
2
lockfile-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.
3
4
## Package Information
5
6
- **Package Name**: lockfile-lint (CLI) + lockfile-lint-api (Core API)
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lockfile-lint` (includes lockfile-lint-api as dependency)
10
- **Separate API Installation**: `npm install lockfile-lint-api` (for direct API usage only)
11
12
## Core Imports
13
14
This is primarily a CLI tool accessed via the `lockfile-lint` executable. For programmatic usage:
15
16
**CLI Package (lockfile-lint):**
17
```javascript
18
const { runValidators } = require('lockfile-lint/src/main');
19
const config = require('lockfile-lint/src/config');
20
```
21
22
**Core API Package (lockfile-lint-api):**
23
```javascript
24
const {
25
ParseLockfile,
26
ValidateHost,
27
ValidateHttps,
28
ValidatePackageNames,
29
ValidateScheme,
30
ValidateUrl,
31
ValidateIntegrity
32
} = require('lockfile-lint-api');
33
```
34
35
For ES modules:
36
```javascript
37
import { runValidators } from 'lockfile-lint/src/main';
38
import {
39
ParseLockfile,
40
ValidateHost,
41
ValidateHttps
42
} from 'lockfile-lint-api';
43
```
44
45
## Basic Usage
46
47
### CLI Usage
48
49
```bash
50
# Basic validation with HTTPS enforcement
51
lockfile-lint --path yarn.lock --validate-https
52
53
# Validate against specific hosts
54
lockfile-lint --path package-lock.json --allowed-hosts npm yarn verdaccio
55
56
# Multiple validations with custom schemes
57
lockfile-lint --path yarn.lock --allowed-hosts yarn github.com --allowed-schemes "https:" "git+https:"
58
59
# Validate package names match URLs
60
lockfile-lint --path yarn.lock --allowed-hosts npm --validate-package-names
61
62
# Validate integrity hashes
63
lockfile-lint --path package-lock.json --validate-integrity
64
65
# Multiple lockfiles with glob patterns
66
lockfile-lint --path '/path/to/**/package-lock.json' --validate-https --allowed-hosts npm
67
```
68
69
### Configuration File Usage
70
71
Create `.lockfile-lintrc.json`:
72
73
```json
74
{
75
"path": "yarn.lock",
76
"allowedHosts": ["npm", "github.com"],
77
"validateHttps": true,
78
"validatePackageNames": true,
79
"format": "pretty"
80
}
81
```
82
83
Or in `package.json`:
84
85
```json
86
{
87
"lockfile-lint": {
88
"path": "package-lock.json",
89
"allowedHosts": ["npm"],
90
"validateHttps": true,
91
"validateIntegrity": true
92
}
93
}
94
```
95
96
## Capabilities
97
98
### Lockfile Parsing
99
100
Core lockfile parsing functionality provided by the lockfile-lint-api package for handling npm and yarn lockfiles.
101
102
```javascript { .api }
103
/**
104
* ParseLockfile class for parsing and analyzing lockfile contents
105
* @param options - Configuration options for parsing
106
* @param options.lockfilePath - Path to lockfile (optional if lockfileText provided)
107
* @param options.lockfileText - UTF-8 string content (optional if lockfilePath provided)
108
* @param options.lockfileType - Type: "npm", "npmjs", "yarn", "yarnpkg" (optional, auto-detected)
109
*/
110
class ParseLockfile {
111
constructor(options: {
112
lockfilePath?: string;
113
lockfileText?: string;
114
lockfileType?: "npm" | "npmjs" | "yarn" | "yarnpkg";
115
});
116
117
/** Parse lockfile and return normalized package structure */
118
parseSync(): { type: "success"; object: Object };
119
120
/** Check if lockfile type was explicitly provided */
121
isLockfileTypeGiven(): boolean;
122
123
/** Resolve package manager function for lockfile type */
124
resolvePkgMgrForLockfile(): Function;
125
126
/** Extract clean package name from npm lockfile paths */
127
extractedPackageName(packageName: string): string;
128
}
129
```
130
131
**Usage Example:**
132
```javascript
133
const { ParseLockfile } = require('lockfile-lint-api');
134
135
const parser = new ParseLockfile({
136
lockfilePath: './package-lock.json'
137
});
138
139
const result = parser.parseSync();
140
console.log('Lockfile type:', result.type);
141
console.log('Package count:', Object.keys(result.object).length);
142
```
143
144
### Direct Validation Classes
145
146
Individual validator classes from lockfile-lint-api for custom validation workflows.
147
148
```javascript { .api }
149
/**
150
* Host validation - validates package registry hosts
151
* @param packages - Parsed lockfile packages object
152
* @param debug - Debug function (optional)
153
*/
154
class ValidateHost {
155
constructor({ packages: Object, debug?: Function });
156
157
/** Validate hosts with options */
158
validate(hosts: string[], options?: {
159
emptyHostname?: boolean;
160
allowedHosts?: string[];
161
allowedUrls?: string[];
162
}): ValidationResult;
163
164
/** Validate single package against hosts */
165
validateSingle(packageName: string, hosts: string[]): boolean;
166
}
167
168
/**
169
* HTTPS protocol validation - ensures all packages use secure protocols
170
*/
171
class ValidateHttps {
172
constructor({ packages: Object });
173
174
/** Validate all packages use HTTPS */
175
validate(): ValidationResult;
176
}
177
178
/**
179
* Package name validation - ensures package names match their resolved URLs
180
*/
181
class ValidatePackageNames {
182
constructor({ packages: Object });
183
184
/** Validate package names with optional aliases */
185
validate(packageNameAliases?: string[]): ValidationResult;
186
}
187
188
/**
189
* Protocol scheme validation - validates allowed URI schemes
190
*/
191
class ValidateScheme {
192
constructor({ packages: Object });
193
194
/** Validate allowed schemes */
195
validate(schemes: string[]): ValidationResult;
196
}
197
198
/**
199
* URL validation - validates specific allowed URLs
200
*/
201
class ValidateUrl {
202
constructor({ packages: Object });
203
204
/** Validate against allowed URLs */
205
validate(allowedUrls: string[], options?: Object): ValidationResult;
206
207
/** Validate single package against URLs */
208
validateSingle(packageName: string, allowedUrls: string[]): boolean;
209
}
210
211
/**
212
* Integrity hash validation - validates SHA512 integrity hashes
213
*/
214
class ValidateIntegrity {
215
constructor({ packages: Object });
216
217
/** Validate integrity hashes with exclusion options */
218
validate(options?: {
219
integrityExclude?: string[];
220
}): ValidationResult;
221
222
/** Validate single package integrity */
223
validateSingle(packageName: string): boolean;
224
}
225
226
interface ValidationResult {
227
type: "success" | "error";
228
errors: Array<{
229
message: string;
230
package: string;
231
}>;
232
}
233
```
234
235
**Direct API Usage Example:**
236
```javascript
237
const { ParseLockfile, ValidateHost, ValidateHttps } = require('lockfile-lint-api');
238
239
// Parse lockfile
240
const parser = new ParseLockfile({ lockfilePath: './yarn.lock' });
241
const { object: packages } = parser.parseSync();
242
243
// Validate hosts
244
const hostValidator = new ValidateHost({ packages });
245
const hostResult = hostValidator.validate(['npm', 'github.com'], {
246
emptyHostname: false
247
});
248
249
// Validate HTTPS
250
const httpsValidator = new ValidateHttps({ packages });
251
const httpsResult = httpsValidator.validate();
252
253
if (hostResult.type === 'error' || httpsResult.type === 'error') {
254
console.error('Validation failed');
255
process.exit(1);
256
}
257
```
258
259
### CLI Command Interface
260
261
Primary interface for linting lockfiles with comprehensive security validation options.
262
263
```bash { .api }
264
lockfile-lint [options]
265
266
# Required Options
267
--path, -p <string> # Path to lockfile or glob pattern
268
269
# Lockfile Type
270
--type, -t <string> # Lockfile type: "npm" or "yarn" (auto-detected if omitted)
271
272
# Security Validations
273
--validate-https, -s # Validates HTTPS protocol usage
274
--allowed-hosts, -a <array> # Validates allowed hosts (supports npm, yarn, verdaccio aliases)
275
--allowed-schemes, -o <array> # Validates allowed URI schemes (conflicts with --validate-https)
276
--allowed-urls, -u <array> # Validates specific allowed URLs
277
--validate-package-names, -n # Validates package names match URLs (requires --allowed-hosts)
278
--validate-integrity, -i # Validates sha512 integrity hashes
279
280
# Configuration Options
281
--empty-hostname, -e # Allow empty hostnames (default: true)
282
--allowed-package-name-aliases, -l <array> # Package name aliases (format: "alias:package")
283
--integrity-exclude <array> # Exclude packages from integrity validation
284
--format, -f <string> # Output format: "pretty" or "plain" (default: "pretty")
285
286
# Help & Info
287
--help, -h # Display help information
288
--version # Display version information
289
```
290
291
**Exit Codes**:
292
- `0`: Success, no security issues detected
293
- `1`: Error, security issues detected or command failed
294
295
**Host Aliases**:
296
- `npm` → `https://registry.npmjs.org`
297
- `yarn` → `https://registry.yarnpkg.com`
298
- `verdaccio` → `https://registry.verdaccio.org`
299
300
### Programmatic Validation
301
302
Core validation function for custom implementations and integrations.
303
304
```javascript { .api }
305
/**
306
* Executes validation checks on lockfile using specified validators
307
* @param options - Validation configuration
308
* @param options.type - Lockfile type ("npm" or "yarn")
309
* @param options.path - Path to lockfile
310
* @param options.validators - Array of validator configurations
311
* @returns Validation results summary
312
*/
313
function runValidators({
314
type: string,
315
path: string,
316
validators: ValidatorConfig[]
317
}): ValidationResult;
318
319
interface ValidatorConfig {
320
name: string; // Validator function name
321
values: any; // Validation values/configuration
322
options: object; // Validation options
323
}
324
325
interface ValidationResult {
326
validatorCount: number; // Total validators executed
327
validatorFailures: number; // Number of validation failures
328
validatorSuccesses: number; // Number of validation successes
329
}
330
```
331
332
**Usage Example:**
333
334
```javascript
335
const { runValidators } = require('lockfile-lint/src/main');
336
337
const result = runValidators({
338
path: './yarn.lock',
339
type: 'yarn',
340
validators: [
341
{
342
name: 'validateHosts',
343
values: ['npm', 'github.com'],
344
options: {
345
emptyHostname: true,
346
allowedUrls: ['https://github.com/org/repo#hash']
347
}
348
},
349
{
350
name: 'validateHttps',
351
values: true,
352
options: {}
353
}
354
]
355
});
356
357
console.log(`Executed ${result.validatorCount} validators`);
358
if (result.validatorFailures > 0) {
359
console.error(`Found ${result.validatorFailures} security issues`);
360
process.exit(1);
361
}
362
```
363
364
### Configuration Loading
365
366
Configuration file discovery and CLI argument parsing.
367
368
```javascript { .api }
369
/**
370
* Parses CLI arguments and loads configuration files
371
* @param argv - Command line arguments array
372
* @param exitProcess - Whether to exit process on error (default: false)
373
* @param searchFrom - Directory to search for config files (default: process.cwd())
374
* @returns Parsed configuration object
375
*/
376
function loadConfig(
377
argv: string[],
378
exitProcess?: boolean,
379
searchFrom?: string
380
): ConfigObject;
381
382
interface ConfigObject {
383
path: string; // Lockfile path/pattern
384
type?: string; // Lockfile type
385
format: 'pretty' | 'plain'; // Output format
386
'validate-https'?: boolean; // HTTPS validation
387
'allowed-hosts'?: string[]; // Allowed hosts
388
'allowed-schemes'?: string[]; // Allowed schemes
389
'allowed-urls'?: string[]; // Allowed URLs
390
'validate-package-names'?: boolean; // Package name validation
391
'validate-integrity'?: boolean; // Integrity validation
392
'empty-hostname'?: boolean; // Allow empty hostnames
393
'allowed-package-name-aliases'?: string[]; // Package aliases
394
'integrity-exclude'?: string[]; // Integrity exclusions
395
}
396
```
397
398
### Validator Managers
399
400
Individual validation managers that wrap lockfile-lint-api functionality.
401
402
```javascript { .api }
403
/**
404
* Validates allowed hosts for package URLs
405
*/
406
function ValidateHostManager({
407
path: string,
408
type: string,
409
validatorValues: string[],
410
validatorOptions: {
411
emptyHostname?: boolean,
412
allowedUrls?: string[]
413
}
414
}): ValidationResult;
415
416
/**
417
* Validates HTTPS protocol usage
418
*/
419
function ValidateHttpsManager({
420
path: string,
421
type: string,
422
validatorValues: boolean,
423
validatorOptions: object
424
}): ValidationResult;
425
426
/**
427
* Validates package names match their resolved URLs
428
*/
429
function ValidatePackageNamesManager({
430
path: string,
431
type: string,
432
validatorValues: boolean,
433
validatorOptions: {
434
allowedPackageNameAliases?: string[]
435
}
436
}): ValidationResult;
437
438
/**
439
* Validates allowed URI schemes
440
*/
441
function ValidateSchemeManager({
442
path: string,
443
type: string,
444
validatorValues: string[],
445
validatorOptions: object
446
}): ValidationResult;
447
448
/**
449
* Validates allowed URLs
450
*/
451
function ValidateUrlManager({
452
path: string,
453
type: string,
454
validatorValues: string[],
455
validatorOptions: object
456
}): ValidationResult;
457
458
/**
459
* Validates integrity hash formats (sha512)
460
*/
461
function ValidateIntegrityManager({
462
path: string,
463
type: string,
464
validatorValues: boolean,
465
validatorOptions: {
466
integrityExclude?: string[]
467
}
468
}): ValidationResult;
469
470
interface ValidationResult {
471
type: 'success' | 'error';
472
errors: ValidationError[];
473
}
474
475
interface ValidationError {
476
message: string;
477
package: object; // Package details from lockfile
478
}
479
```
480
481
## Configuration File Support
482
483
lockfile-lint uses [cosmiconfig](https://github.com/davidtheclark/cosmiconfig) for configuration file discovery, supporting:
484
485
1. `package.json` "lockfile-lint" key
486
2. `.lockfile-lintrc` (JSON/YAML)
487
3. `.lockfile-lintrc.json/.yaml/.yml`
488
4. `.lockfile-lintrc.js`
489
5. `lockfile-lint.config.js`
490
491
Configuration files use camelCase property names (e.g., `allowedHosts` not `allowed-hosts`).
492
493
## Supported Lockfile Types
494
495
- **npm**: `package-lock.json`, `npm-shrinkwrap.json`
496
- **yarn**: `yarn.lock`
497
498
Lockfile type is auto-detected from filename if `--type` is not specified.
499
500
## Error Handling
501
502
**Common Error Scenarios**:
503
- Invalid lockfile format or path
504
- Security policy violations (non-HTTPS URLs, unauthorized hosts)
505
- Package name mismatches
506
- Invalid integrity hashes
507
- Configuration file parsing errors
508
509
**Output Formats**:
510
- `pretty` (default): Colored output with status symbols
511
- `plain`: Plain text output without colors or symbols
512
513
**Debug Mode**:
514
```bash
515
DEBUG=* lockfile-lint --path yarn.lock --validate-https
516
```
517
518
Provides detailed logging of validation processes and configuration loading.