or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

examples

edge-cases.mdreal-world-scenarios.md
index.md
tile.json

real-world-scenarios.mddocs/examples/

Real-World Scenarios

Comprehensive usage examples for common integration patterns and workflows.

CI/CD Integration

Basic Build Validation

const { ValidateHttps, ValidateHost, ParseLockfile } = require('lockfile-lint-api');

function validateBuildSecurity(lockfilePath) {
  const parser = new ParseLockfile({ lockfilePath });
  const lockfile = parser.parseSync();

  // Validate HTTPS
  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);
  }

  // Validate hosts
  const hostValidator = new ValidateHost({ packages: lockfile.object });
  const hostResult = hostValidator.validate(['npm', 'registry.mycompany.com']);

  if (hostResult.type === 'error') {
    console.error('BUILD FAILED: Unauthorized package sources detected');
    hostResult.errors.forEach(error => console.error(error.message));
    process.exit(1);
  }

  console.log('✓ All security validations passed');
}

validateBuildSecurity('./package-lock.json');

Comprehensive Security Validation

const {
  ParseLockfile,
  ValidateHost,
  ValidateHttps,
  ValidatePackageNames,
  ValidateScheme,
  ValidateIntegrity
} = require('lockfile-lint-api');

function comprehensiveSecurityValidation(lockfilePath) {
  const parser = new ParseLockfile({ lockfilePath });
  const lockfile = parser.parseSync();

  const validations = [
    {
      name: 'HTTPS Protocol',
      validator: new ValidateHttps({ packages: lockfile.object }),
      validate: (v) => v.validate()
    },
    {
      name: 'Allowed Hosts',
      validator: new ValidateHost({ packages: lockfile.object }),
      validate: (v) => v.validate(['npm'])
    },
    {
      name: 'Package Names',
      validator: new ValidatePackageNames({ packages: lockfile.object }),
      validate: (v) => v.validate()
    },
    {
      name: 'URI Schemes',
      validator: new ValidateScheme({ packages: lockfile.object }),
      validate: (v) => v.validate(['https:'])
    },
    {
      name: 'Integrity Hashes',
      validator: new ValidateIntegrity({ packages: lockfile.object }),
      validate: (v) => v.validate({
        integrityExclude: ['legacy-package']
      })
    }
  ];

  let allPassed = true;
  const allErrors = [];

  validations.forEach(({ name, validator, validate }) => {
    const result = validate(validator);
    if (result.type === 'error') {
      console.error(`\n✗ ${name} validation failed:`);
      result.errors.forEach(error => {
        console.error(`  ${error.message}`);
        allErrors.push({ validation: name, ...error });
      });
      allPassed = false;
    } else {
      console.log(`✓ ${name} validation passed`);
    }
  });

  if (!allPassed) {
    console.error(`\n${allErrors.length} total validation error(s) found`);
    return false;
  }

  return true;
}

if (!comprehensiveSecurityValidation('./package-lock.json')) {
  process.exit(1);
}

Pre-commit Hooks

HTTPS Validation Hook

#!/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');

Multi-Validator Pre-commit Hook

#!/usr/bin/env node
const {
  ParseLockfile,
  ValidateHttps,
  ValidateHost,
  ValidateScheme
} = require('lockfile-lint-api');
const fs = require('fs');

function validateLockfile(lockfilePath) {
  const parser = new ParseLockfile({ lockfilePath });
  const lockfile = parser.parseSync();

  const validators = [
    {
      name: 'HTTPS',
      validator: new ValidateHttps({ packages: lockfile.object }),
      validate: (v) => v.validate()
    },
    {
      name: 'Hosts',
      validator: new ValidateHost({ packages: lockfile.object }),
      validate: (v) => v.validate(['npm'])
    },
    {
      name: 'Schemes',
      validator: new ValidateScheme({ packages: lockfile.object }),
      validate: (v) => v.validate(['https:'])
    }
  ];

  let hasErrors = false;

  validators.forEach(({ name, validator, validate }) => {
    const result = validate(validator);
    if (result.type === 'error') {
      console.error(`\n${name} validation failed:`);
      result.errors.forEach(error => console.error(error.message));
      hasErrors = true;
    }
  });

  return !hasErrors;
}

const lockfiles = ['package-lock.json', 'yarn.lock'];
let allPassed = true;

lockfiles.forEach(lockfile => {
  if (fs.existsSync(lockfile)) {
    if (!validateLockfile(lockfile)) {
      allPassed = false;
    }
  }
});

if (!allPassed) {
  console.error('\nCommit rejected: Lockfile validation failed');
  process.exit(1);
}

console.log('✓ All lockfile validations passed');

Environment-Specific Validation

Production vs Development

const { ValidateScheme, ParseLockfile } = require('lockfile-lint-api');

function validateSchemesByEnvironment(lockfilePath) {
  const parser = new ParseLockfile({ lockfilePath });
  const lockfile = parser.parseSync();
  const validator = new ValidateScheme({ packages: lockfile.object });

  const env = process.env.NODE_ENV || 'development';

  let allowedSchemes;
  switch (env) {
    case 'production':
      allowedSchemes = ['https:'];
      break;
    case 'staging':
      allowedSchemes = ['https:', 'http:'];
      break;
    case 'development':
      allowedSchemes = ['https:', 'http:', 'git:', 'git+ssh:', 'file:'];
      break;
    default:
      allowedSchemes = ['https:'];
  }

  const result = validator.validate(allowedSchemes);

  if (result.type === 'error') {
    console.error(`Scheme validation failed for ${env} environment:`);
    result.errors.forEach(error => console.error(error.message));
    return false;
  }

  console.log(`✓ All schemes valid for ${env} environment`);
  return true;
}

validateSchemesByEnvironment('./package-lock.json');

URL Whitelisting Workflow

Generate Whitelist from Approved Lockfile

const { ParseLockfile } = require('lockfile-lint-api');
const fs = require('fs');
const crypto = require('crypto');

function generateUrlWhitelist(approvedLockfile, outputPath) {
  const parser = new ParseLockfile({ lockfilePath: approvedLockfile });
  const lockfile = parser.parseSync();

  const whitelist = {
    generated: new Date().toISOString(),
    hash: '',
    urls: []
  };

  // Extract all URLs
  for (const metadata of Object.values(lockfile.object)) {
    if (metadata.resolved) {
      whitelist.urls.push(metadata.resolved);
    }
  }

  // Generate hash for integrity
  const whitelistJson = JSON.stringify(whitelist.urls);
  whitelist.hash = crypto.createHash('sha256').update(whitelistJson).digest('hex');

  fs.writeFileSync(outputPath, JSON.stringify(whitelist, null, 2));
  console.log(`Generated whitelist with ${whitelist.urls.length} URLs`);
  console.log(`Whitelist hash: ${whitelist.hash}`);
}

// Validate against whitelist
function validateAgainstWhitelist(lockfilePath, whitelistPath) {
  const whitelist = JSON.parse(fs.readFileSync(whitelistPath, 'utf-8'));

  // Verify whitelist integrity
  const whitelistJson = JSON.stringify(whitelist.urls);
  const currentHash = crypto.createHash('sha256').update(whitelistJson).digest('hex');

  if (currentHash !== whitelist.hash) {
    console.error('Whitelist integrity check failed!');
    return false;
  }

  const { ValidateUrl, ParseLockfile } = require('lockfile-lint-api');
  const parser = new ParseLockfile({ lockfilePath });
  const lockfile = parser.parseSync();
  const validator = new ValidateUrl({ packages: lockfile.object });
  const result = validator.validate(whitelist.urls);

  return result.type === 'success';
}

// Usage
// generateUrlWhitelist('./approved-package-lock.json', './url-whitelist.json');
// if (!validateAgainstWhitelist('./package-lock.json', './url-whitelist.json')) {
//   console.error('Package URLs have changed from approved baseline!');
//   process.exit(1);
// }

Progressive Security Enforcement

Phased Integrity Hash Migration

const { ValidateIntegrity, ParseLockfile } = require('lockfile-lint-api');

// Start with extensive exclusions, gradually reduce over time
const exclusionConfig = {
  phase1: ['legacy-a', 'legacy-b', 'legacy-c', 'old-dep'],  // Initial
  phase2: ['legacy-a', 'legacy-b'],  // After updates
  phase3: ['legacy-a'],  // Near completion
  phase4: []  // Full enforcement
};

const currentPhase = process.env.SECURITY_PHASE || 'phase1';

const parser = new ParseLockfile({ lockfilePath: './package-lock.json' });
const lockfile = parser.parseSync();
const validator = new ValidateIntegrity({ packages: lockfile.object });

const result = validator.validate({
  integrityExclude: exclusionConfig[currentPhase]
});

if (result.type === 'error') {
  console.error(`Integrity validation failed (${currentPhase}):`);
  result.errors.forEach(error => console.error(error.message));
  process.exit(1);
}

console.log(`✓ Integrity validation passed (${currentPhase})`);

Security Audit Reporting

Comprehensive Audit Report

const { ValidateIntegrity, ParseLockfile } = require('lockfile-lint-api');

function auditIntegrityHashes(lockfilePath) {
  const parser = new ParseLockfile({ lockfilePath });
  const lockfile = parser.parseSync();

  const stats = {
    total: 0,
    withIntegrity: 0,
    sha512: 0,
    weak: []
  };

  for (const [packageName, metadata] of Object.entries(lockfile.object)) {
    stats.total++;

    if (metadata.integrity) {
      stats.withIntegrity++;
      const algorithm = metadata.integrity.split('-')[0];

      if (algorithm === 'sha512') {
        stats.sha512++;
      } else {
        stats.weak.push({
          package: packageName,
          algorithm: algorithm
        });
      }
    }
  }

  console.log('Integrity Hash Audit Results:');
  console.log(`  Total packages: ${stats.total}`);
  console.log(`  With integrity: ${stats.withIntegrity}`);
  console.log(`  Using SHA-512: ${stats.sha512}`);
  console.log(`  Using weak hashes: ${stats.weak.length}`);

  if (stats.weak.length > 0) {
    console.log('\nPackages with weak hashes:');
    stats.weak.forEach(({ package: pkg, algorithm }) => {
      console.log(`  ${pkg} (${algorithm})`);
    });
  }

  return stats.weak.length === 0;
}

if (!auditIntegrityHashes('./package-lock.json')) {
  console.error('\nAudit failed: Weak integrity hashes detected');
  process.exit(1);
}

Package Name Confusion Detection

Detect Name Confusion Attacks

const { ValidatePackageNames, ParseLockfile } = require('lockfile-lint-api');

function detectNameConfusionAttacks(lockfilePath) {
  try {
    const parser = new ParseLockfile({ lockfilePath });
    const lockfile = parser.parseSync();
    const validator = new ValidatePackageNames({ packages: lockfile.object });
    const result = validator.validate();

    if (result.type === 'error') {
      console.error('SECURITY ALERT: Package name confusion detected!');
      result.errors.forEach(error => {
        console.error(`  Package: ${error.package}`);
        console.error(`  ${error.message}`);
      });
      return false;
    }

    console.log('✓ All package names are consistent');
    return true;
  } catch (error) {
    console.error('Validation error:', error.message);
    return false;
  }
}

if (!detectNameConfusionAttacks('./package-lock.json')) {
  console.error('Build failed due to security concerns');
  process.exit(1);
}