The ValidateHttps class validates that all package resources use HTTPS protocol, ensuring secure package downloads.
Creates a new HTTPS validator instance.
/**
* Creates a new HTTPS protocol validator
* @param {Object} [options={}] - Validator configuration (defaults to empty object)
* @param {Object} options.packages - Package object from parsed lockfile
* @throws {Error} If options is provided but packages is missing or not an object
*/
class ValidateHttps {
constructor(options?: {
packages: Object;
});
}Requirements: The options.packages parameter must be an object (typically from ParseLockfile.parseSync().object). Throws an error if the options object is provided but packages is missing or not an object.
Usage Examples:
const { ValidateHttps, ParseLockfile } = require('lockfile-lint-api');
// Parse lockfile first
const parser = new ParseLockfile({ lockfilePath: './package-lock.json' });
const lockfile = parser.parseSync();
// Create validator
const validator = new ValidateHttps({ packages: lockfile.object });Validates that all packages in the lockfile use HTTPS protocol.
/**
* Validates all packages use HTTPS protocol
* @returns {Object} Validation result with type ('success' or 'error') and errors array
*/
validate(): {
type: 'success' | 'error';
errors: Array<{
message: string;
package: string;
}>;
}Behavior:
https: protocolresolved field are automatically skipped (e.g., local filesystem packages)http:, git:, file:)Usage Examples:
const { ValidateHttps, ParseLockfile } = require('lockfile-lint-api');
// Basic usage
const parser = new ParseLockfile({ lockfilePath: './package-lock.json' });
const lockfile = parser.parseSync();
const validator = new ValidateHttps({ packages: lockfile.object });
const result = validator.validate();
if (result.type === 'success') {
console.log('All packages use HTTPS protocol');
} else {
console.error('HTTPS validation failed:');
result.errors.forEach(error => {
console.error(` ${error.package}: ${error.message}`);
});
}Example with Error Handling:
const { ValidateHttps, ParseLockfile } = require('lockfile-lint-api');
function ensureHttpsProtocol(lockfilePath) {
try {
const parser = new ParseLockfile({ lockfilePath });
const lockfile = parser.parseSync();
const validator = new ValidateHttps({ packages: lockfile.object });
const result = validator.validate();
if (result.type === 'error') {
console.error('Security violation: Non-HTTPS packages detected!');
result.errors.forEach(error => {
console.error(` Package: ${error.package}`);
console.error(` ${error.message}`);
});
return false;
}
console.log('All packages use secure HTTPS protocol');
return true;
} catch (error) {
console.error('Validation error:', error.message);
return false;
}
}
const isSecure = ensureHttpsProtocol('./package-lock.json');
if (!isSecure) {
process.exit(1);
}The validate() method returns a consistent result object:
interface HttpsValidationResult {
type: 'success' | 'error';
errors: HttpsValidationError[];
}
interface HttpsValidationError {
message: string; // Detailed error message with expected and actual protocols
package: string; // Package name that failed validation
}Success Example:
{
type: 'success',
errors: []
}Error Example:
{
type: 'error',
errors: [
{
message: 'detected invalid protocol for package: insecure-package@1.0.0\n expected: https:\n actual: http:\n',
package: 'insecure-package@1.0.0'
}
]
}HTTPS validation is critical for preventing man-in-the-middle attacks:
Example CI/CD Integration:
const { ValidateHttps, ParseLockfile } = require('lockfile-lint-api');
function validateBuildSecurity() {
const parser = new ParseLockfile({ lockfilePath: './package-lock.json' });
const lockfile = parser.parseSync();
const httpsValidator = new ValidateHttps({ packages: lockfile.object });
const httpsResult = httpsValidator.validate();
if (httpsResult.type === 'error') {
console.error('BUILD FAILED: Insecure package sources detected');
httpsResult.errors.forEach(error => {
console.error(` ${error.package}`);
console.error(` ${error.message}`);
});
process.exit(1);
}
console.log('✓ All packages use secure HTTPS protocol');
}
validateBuildSecurity();Pre-commit Hook Example:
#!/usr/bin/env node
const { ValidateHttps, ParseLockfile } = require('lockfile-lint-api');
const fs = require('fs');
const lockfiles = ['package-lock.json', 'yarn.lock'];
let hasErrors = false;
lockfiles.forEach(lockfile => {
if (!fs.existsSync(lockfile)) {
return;
}
const parser = new ParseLockfile({ lockfilePath: lockfile });
const parsed = parser.parseSync();
const validator = new ValidateHttps({ packages: parsed.object });
const result = validator.validate();
if (result.type === 'error') {
console.error(`\nHTTPS validation failed for ${lockfile}:`);
result.errors.forEach(error => console.error(error.message));
hasErrors = true;
}
});
if (hasErrors) {
console.error('\nCommit rejected: Fix HTTPS protocol violations first');
process.exit(1);
}
console.log('✓ HTTPS validation passed');Constructor Errors:
// Throws: 'expecting an object passed to validator constructor'
const validator = new ValidateHttps(); // Missing packages
const validator = new ValidateHttps({ packages: null }); // Invalid type
const validator = new ValidateHttps({ packages: [] }); // Array instead of objectURL.protocol against the constant 'https:'URL class to parse package resolved URLsresolved field)The ValidateHttps validator is simpler than most other validators because:
ValidateHost for comprehensive securityCombined Security Example:
const { ValidateHttps, ValidateHost, ParseLockfile } = require('lockfile-lint-api');
function validateLockfileSecurity(lockfilePath) {
const parser = new ParseLockfile({ lockfilePath });
const lockfile = parser.parseSync();
// Ensure HTTPS protocol
const httpsValidator = new ValidateHttps({ packages: lockfile.object });
const httpsResult = httpsValidator.validate();
// Ensure trusted hosts
const hostValidator = new ValidateHost({ packages: lockfile.object });
const hostResult = hostValidator.validate(['npm', 'registry.mycompany.com']);
const allErrors = [...httpsResult.errors, ...hostResult.errors];
if (allErrors.length > 0) {
console.error('Lockfile security validation failed:');
allErrors.forEach(error => console.error(error.message));
return false;
}
console.log('Lockfile security validation passed');
return true;
}
if (!validateLockfileSecurity('./package-lock.json')) {
process.exit(1);
}// These will fail validation
resolved: 'http://registry.npmjs.org/package/-/package-1.0.0.tgz'
resolved: 'git://github.com/user/repo.git'
resolved: 'file:///path/to/package.tgz'
// These will pass validation
resolved: 'https://registry.npmjs.org/package/-/package-1.0.0.tgz'
resolved: 'https://registry.yarnpkg.com/package/-/package-1.0.0.tgz'// Packages without resolved field are automatically skipped
{
'local-package@1.0.0': {
version: '1.0.0'
// No resolved field - automatically skipped
}
}