npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bernierllc/validators-header-policy

v1.2.0

Published

Primitive validator for HTTP security header policy validation (CSP, HSTS, CORS, security headers)

Downloads

98

Readme

@bernierllc/validators-header-policy

Primitive validator for HTTP security header policy validation (CSP, HSTS, CORS, security headers).

Installation

npm install @bernierllc/validators-header-policy

Overview

This package validates HTTP security headers to ensure they follow security best practices. It checks Content-Security-Policy, Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Permissions-Policy headers.

Features

  • Content-Security-Policy (CSP) - Validates CSP directives, detects unsafe-inline/eval, checks for wildcards
  • Strict-Transport-Security (HSTS) - Validates max-age, includeSubDomains, and preload directives
  • X-Frame-Options - Validates clickjacking protection headers
  • X-Content-Type-Options - Validates MIME sniffing prevention
  • Referrer-Policy - Validates referrer information leakage controls
  • Permissions-Policy - Validates browser feature access controls

Usage

Basic Validation

import { validateHeaderPolicy } from '@bernierllc/validators-header-policy';

const headers = {
  'Content-Security-Policy': "default-src 'self'; script-src 'self' https://cdn.example.com",
  'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload',
  'X-Frame-Options': 'DENY',
  'X-Content-Type-Options': 'nosniff',
  'Referrer-Policy': 'strict-origin-when-cross-origin'
};

const problems = await validateHeaderPolicy(headers);

if (problems.length > 0) {
  console.log('Security issues found:');
  problems.forEach(p => {
    console.log(`[${p.severity}] ${p.message}`);
  });
}

Quick Security Check

import { hasSecurityIssues } from '@bernierllc/validators-header-policy';

const headers = {
  'Content-Security-Policy': "script-src 'unsafe-inline'"
};

if (await hasSecurityIssues(headers)) {
  console.log('Warning: Security headers need attention');
}

Security Scoring

import { getSecurityScore } from '@bernierllc/validators-header-policy';

const score = await getSecurityScore(headers);
console.log(`Security score: ${score}/100`);

// Score interpretation:
// 100: Perfect security headers
// 80-99: Good security with minor issues
// 60-79: Moderate security, improvements recommended
// <60: Poor security, critical issues present

Detailed Summary

import { getHeaderPolicySummary } from '@bernierllc/validators-header-policy';

const summary = await getHeaderPolicySummary(headers);

console.log(`Total issues: ${summary.total}`);
console.log(`Errors: ${summary.errors}`);
console.log(`Warnings: ${summary.warnings}`);
console.log(`Security Score: ${summary.securityScore}`);
console.log('Issues by rule:', summary.byRule);

API Reference

Main Functions

validateHeaderPolicy(headers, options?)

Validates HTTP security headers against security best practices.

Parameters:

  • headers: Record<string, string | string[]> - HTTP headers object
  • options?: HeaderPolicyOptions - Optional validation configuration

Returns: Promise<ValidationProblem[]> - Array of validation problems found

Example:

const problems = await validateHeaderPolicy(headers, {
  requireCsp: true,
  strictMode: true
});

hasSecurityIssues(headers, options?)

Quick check if headers have any security issues.

Parameters:

  • headers: Record<string, string | string[]> - HTTP headers object
  • options?: HeaderPolicyOptions - Optional validation configuration

Returns: Promise<boolean> - True if security issues found

Example:

if (await hasSecurityIssues(headers)) {
  console.warn('Security headers need attention');
}

getSecurityScore(headers, options?)

Calculate a security score (0-100) for the given headers.

Parameters:

  • headers: Record<string, string | string[]> - HTTP headers object
  • options?: HeaderPolicyOptions - Optional validation configuration

Returns: Promise<number> - Security score from 0 (worst) to 100 (perfect)

Example:

const score = await getSecurityScore(headers);
console.log(`Security score: ${score}/100`);

getHeaderPolicySummary(headers, options?)

Get a comprehensive summary of validation results.

Parameters:

  • headers: Record<string, string | string[]> - HTTP headers object
  • options?: HeaderPolicyOptions - Optional validation configuration

Returns: Promise<HeaderPolicySummary> - Summary object with counts and details

Example:

const summary = await getHeaderPolicySummary(headers);
console.log(`Errors: ${summary.errors}, Warnings: ${summary.warnings}`);

Types

ValidationProblem

interface ValidationProblem {
  message: string;
  severity: 'error' | 'warn' | 'info';
  ruleId: string;
  location?: string;
}

HeaderPolicySummary

interface HeaderPolicySummary {
  total: number;
  errors: number;
  warnings: number;
  infos: number;
  securityScore: number;
  byRule: Record<string, number>;
}

Configuration Options

HeaderPolicyOptions

interface HeaderPolicyOptions {
  // CSP Options
  checkCsp?: boolean;              // Default: true
  requireCsp?: boolean;            // Default: false
  allowUnsafeInline?: boolean;     // Default: false
  allowUnsafeEval?: boolean;       // Default: false
  cspDirectives?: {                // Custom CSP directive requirements
    defaultSrc?: string[];
    scriptSrc?: string[];
    styleSrc?: string[];
    // ... other CSP directives
  };

  // HSTS Options
  checkHsts?: boolean;             // Default: true
  requireHsts?: boolean;           // Default: false
  minHstsMaxAge?: number;          // Default: 31536000 (1 year)
  requireHstsIncludeSubDomains?: boolean;
  requireHstsPreload?: boolean;

  // X-Frame-Options
  checkXFrameOptions?: boolean;    // Default: true
  requireXFrameOptions?: boolean;  // Default: false
  allowedXFrameValues?: ('DENY' | 'SAMEORIGIN')[];

  // X-Content-Type-Options
  checkXContentTypeOptions?: boolean;    // Default: true
  requireXContentTypeOptions?: boolean;  // Default: false

  // Referrer-Policy
  checkReferrerPolicy?: boolean;   // Default: true
  requireReferrerPolicy?: boolean; // Default: false
  allowedReferrerPolicies?: ReferrerPolicyValue[];

  // Permissions-Policy
  checkPermissionsPolicy?: boolean;    // Default: true
  requirePermissionsPolicy?: boolean;  // Default: false
  requiredPermissions?: string[];

  // General
  strictMode?: boolean;            // Default: false (enforce stricter checks)
}

Example with Custom Options

const problems = await validateHeaderPolicy(headers, {
  requireCsp: true,
  requireHsts: true,
  allowUnsafeInline: false,
  minHstsMaxAge: 63072000, // 2 years
  requireHstsIncludeSubDomains: true,
  strictMode: true,
  cspDirectives: {
    scriptSrc: ["'self'", "https://trusted-cdn.example.com"],
    styleSrc: ["'self'"]
  },
  allowedReferrerPolicies: ['no-referrer', 'strict-origin-when-cross-origin']
});

Validation Rules

Content-Security-Policy (CSP)

What it validates:

  • Presence of default-src directive
  • Detection of unsafe-inline in script-src
  • Detection of unsafe-eval in script-src
  • Detection of unsafe-inline in style-src
  • Wildcard (*) usage in directives
  • Custom directive requirements

Example problems detected:

// Missing default-src
"default-src directive missing" // severity: warn

// Unsafe inline scripts
"script-src 'unsafe-inline'" // severity: warn/error (strict mode)

// Wildcard in script-src
"script-src *" // severity: warn

Strict-Transport-Security (HSTS)

What it validates:

  • Presence and value of max-age directive
  • Presence of includeSubDomains directive
  • Presence of preload directive
  • HSTS preload requirements (31536000+ max-age + includeSubDomains)

Example problems detected:

// Low max-age
"max-age=3600 is below recommended 31536000" // severity: warn

// Missing includeSubDomains
"Should include includeSubDomains" // severity: warn

// Preload without includeSubDomains
"preload requires includeSubDomains" // severity: error

X-Frame-Options

What it validates:

  • Valid values (DENY, SAMEORIGIN)
  • Deprecated ALLOW-FROM directive
  • Redundancy with CSP frame-ancestors

Example problems detected:

// Invalid value
"X-Frame-Options: INVALID not recommended" // severity: warn

// Deprecated directive
"ALLOW-FROM is deprecated" // severity: error

X-Content-Type-Options

What it validates:

  • Must be set to nosniff (only valid value)

Example problems detected:

// Invalid value
"X-Content-Type-Options: invalid is invalid" // severity: error

Referrer-Policy

What it validates:

  • Valid referrer policy values
  • Detection of unsafe policies (unsafe-url)
  • Custom allowed policies

Recommended values:

  • no-referrer
  • strict-origin
  • strict-origin-when-cross-origin

Example problems detected:

// Invalid policy
"invalid-policy is not valid" // severity: error

// Unsafe policy
"unsafe-url leaks full URL" // severity: warn

Permissions-Policy

What it validates:

  • Deprecated Feature-Policy header
  • Wildcard usage in sensitive permissions
  • Unquoted origins
  • Required permissions

Sensitive permissions monitored:

  • camera, microphone, geolocation
  • payment, usb, bluetooth, midi, serial

Example problems detected:

// Wildcard in sensitive permission
"geolocation allows all origins (*)" // severity: warn

// Unquoted origin
"Origin should be quoted" // severity: warn

Severities

  • error - Critical security issue that should block deployment
  • warn - Security concern that should be addressed
  • info - Informational message or best practice recommendation

Integration Status

  • Logger Integration: Not applicable - Pure validation package with no logging requirements. As a primitive validator following validators-principles, this package has no observable state changes or operational events requiring structured logging. All validation results are returned synchronously through function return values.
  • Docs-Suite: Ready - Markdown documentation exportable
  • NeverHub Integration: Not applicable - Primitive validator with no service dependencies. Following validators-principles architecture, this is a pure validation utility with no event publishing, service discovery, or orchestration needs. The package operates synchronously with no external service communication requirements.

Advanced Usage

Using Individual Rules

import { cspRule, hstsRule } from '@bernierllc/validators-header-policy';

// Access rule metadata
console.log(cspRule.meta.id); // 'header-policy/csp'
console.log(cspRule.meta.title); // 'Content-Security-Policy Validation'

Primitive Validator

import { headerPolicyValidator } from '@bernierllc/validators-header-policy';

console.log(headerPolicyValidator.name); // 'header-policy'
console.log(headerPolicyValidator.domain); // 'security'
console.log(headerPolicyValidator.rules.length); // 6

Examples

Validating Express Response Headers

import express from 'express';
import { validateHeaderPolicy, getSecurityScore } from '@bernierllc/validators-header-policy';

const app = express();

app.use(async (req, res, next) => {
  // Set security headers
  res.setHeader('Content-Security-Policy', "default-src 'self'");
  res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
  res.setHeader('X-Frame-Options', 'DENY');
  res.setHeader('X-Content-Type-Options', 'nosniff');

  // Validate headers
  const headers = res.getHeaders() as Record<string, string | string[]>;
  const problems = await validateHeaderPolicy(headers);

  if (problems.length > 0) {
    console.warn('Security header issues:', problems);
  }

  next();
});

Testing Headers in CI/CD

import { getSecurityScore } from '@bernierllc/validators-header-policy';

async function testSecurityHeaders() {
  const response = await fetch('https://example.com');
  const headers = Object.fromEntries(response.headers.entries());

  const score = await getSecurityScore(headers);

  if (score < 80) {
    throw new Error(`Security score ${score} is below minimum 80`);
  }

  console.log('Security headers validated successfully');
}

Monitoring Header Policy

import { getHeaderPolicySummary } from '@bernierllc/validators-header-policy';

setInterval(async () => {
  const response = await fetch('https://example.com');
  const headers = Object.fromEntries(response.headers.entries());

  const summary = await getHeaderPolicySummary(headers);

  console.log('Security Header Summary:');
  console.log(`  Score: ${summary.securityScore}/100`);
  console.log(`  Errors: ${summary.errors}`);
  console.log(`  Warnings: ${summary.warnings}`);

  if (summary.errors > 0) {
    // Alert team
    sendAlert('Security header errors detected');
  }
}, 300000); // Check every 5 minutes

See Also

License

Copyright (c) 2025 Bernier LLC. All rights reserved.