Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

nist-password-validator

ypreiser196MIT3.0.3TypeScript support: included

A lightweight, zero-dependencies open-source password validator according to NIST guidelines.

password, validation, security, NIST, npm, authentication, password-strength, compliance, hashing, encryption, user-security, password-policy, nist-800-63b, cyber, cybersecurity, cyber-security, cyber-security-policy

readme

NIST Password Validator Library

A lightweight, zero-dependency open-source password validator adhering to NIST guidelines.

Try it out: Test the library with a user-friendly front-end demo site.


Introduction

This library provides a robust solution for password validation based on the NIST Digital Identity Guidelines (SP 800-63B). It promotes modern password security with support for Unicode, breach checks, customizable rules, and advanced features like error limits for flexible feedback.


Why NIST Guidelines?

Passwords are a cornerstone of digital security. The National Institute of Standards and Technology (NIST) has established guidelines to improve password policies with principles like:

  • Minimum Length: At least 8 characters; 15+ recommended.
  • Maximum Length: Support up to 64+ characters.
  • No Arbitrary Composition Rules: Avoid forcing special characters or case mixing.
  • Unicode Support: Inclusive acceptance of all Unicode characters.
  • Compromised Password Checks: Block passwords found in breaches.
  • Blocklist with Fuzzy Matching: Prevent predictable or context-specific terms.

This library implements these principles to enhance security and usability.


Features

  • NIST-Compliant Validation:
    • Unicode-based minimum/maximum length checks.
    • Smart whitespace handling.
  • Error Limiting:
    • Control the number of errors returned for a password.
    • Balance detailed feedback and performance.
  • HIBP Integration:
    • Check passwords against the Have I Been Pwned (HIBP) breach database.
  • Blocklist with Fuzzy Matching:
    • Detect passwords similar to blocklisted terms.
    • Customizable sensitivity and matching rules.
  • Flexible Configuration:
    • Adjustable length limits, blocklists, and sensitivity.
    • Toggle HIBP checks for local environments.

Installation

Install via npm:

npm install nist-password-validator

Usage

Basic Example

import { validatePassword } from "nist-password-validator";

async function checkPassword() {
  const result = await validatePassword("examplepassword");
  if (!result.isValid) {
    console.log("Password validation failed:", result.errors);
  } else {
    console.log("Password is valid!");
  }
}

checkPassword();

Using the PasswordValidator Class

For scenarios where you need to reuse the same validation configuration or update it dynamically:

import { PasswordValidator } from "nist-password-validator";

// Create a validator with initial options
const validator = new PasswordValidator({
  minLength: 8,
  maxLength: 64,
  blocklist: ["password", "admin"],
});

// Validate a password
async function validateWithClass() {
  const result = await validator.validate("mypassword123");
  console.log(result.isValid ? "Valid!" : "Invalid:", result.errors);
}

// Update configuration as needed
validator.updateConfig({
  minLength: 12, // This will merge with existing config
  errorLimit: 2,
});

// Validate again with new config
validateWithClass();

The PasswordValidator class provides several benefits:

  • Reusable Configuration: Create a validator instance with your preferred settings
  • Dynamic Updates: Change validation rules on the fly with updateConfig
  • Consistent Validation: Ensure the same rules are applied across multiple password checks
  • Memory Efficient: Reuse the same validator instance instead of creating new configurations

Methods:

  • constructor(options?: ValidationOptions): Create a new validator with optional initial options
  • validate(password: string): Promise<ValidationResult>: Validate a password using current configuration
  • updateConfig(options: ValidationOptions): void: Update the current configuration by merging new options

Custom Configuration

async function checkCustomPassword() {
  const result = await validatePassword("myp@ssw0rd!", {
    minLength: 10, // Custom minimum length (default: 15)
    maxLength: 500000, // Custom maximum length (default: 100K)
    hibpCheck: false, // Disable HIBP check if using local hash database
    blocklist: ["password"], // Custom blocklist
    matchingSensitivity: 0.2, // Custom matching sensitivity (default: 0.25)
    trimWhitespace: true, // Handle leading/trailing whitespace (default: true)
    errorLimit: 3, // Amount of errors to check before stopping (defult: infinty)
  });

  if (!result.isValid) {
    console.log("Password validation failed:", result.errors);
  } else {
    console.log("Password is valid!");
  }
}

checkCustomPassword();

Error Limit Feature

The errorLimit option allows users to control how many errors are returned during validation. This helps balance:

  • Performance: Avoid unnecessary checks after reaching the limit.
  • Feedback: Provide detailed insights without overwhelming users.

Example Usage

const result = await validatePassword("mypassword", {
  errorLimit: 2, // Report up to 2 errors
});
console.log(result.errors); // Returns a maximum of 2 errors
  • Default: Unlimited errors (errorLimit defaults to Infinity).
  • Customizable: Adjust based on user needs or environment constraints.

Validators

1. Length Validation

Ensures the password meets specified length requirements based on Unicode code points.

import { lengthValidator } from "nist-password-validator";

const result = lengthValidator("mypassword", 8, 64);
console.log(result.errors);

2. Blocklist Validation

Prevents passwords that resemble blocked terms using fuzzy matching.

import { blocklistValidator } from "nist-password-validator";

const result = blocklistValidator("myp@ssword", ["password"], {
  matchingSensitivity: 0.25,
});
console.log(result.errors);

3. HIBP Validation

Checks passwords against the Have I Been Pwned breach database.

import { hibpValidator } from "nist-password-validator";

hibpValidator("mypassword123").then((result) => console.log(result.errors));

Whitespace Handling

Handles leading/trailing whitespace in passwords for NIST compliance. Enabled by default.

// Default: Trims whitespace
const result1 = await validatePassword("  mypassword  ");

// Disable trimming
const result2 = await validatePassword("  mypassword  ", {
  trimWhitespace: false,
});

Security Considerations

  • Normalize passwords to UTF-8 before hashing.
  • Use local hash databases for HIBP checks in high-security environments.
  • Customize blocklists with sensitive or organization-specific terms.
  • Implement rate limiting for external API calls.

Publishing

This package uses automated npm publishing via GitHub Actions. To publish a new version:

  1. Update version: npm version patch|minor|major (this updates package.json and creates a git tag)
  2. Push with tags: git push origin master --tags
  3. The GitHub Action will automatically:
    • Run tests and linting
    • Build the package
    • Publish to npm with provenance

First-time Setup

To enable automated publishing, add your npm token to GitHub:

  1. Generate an npm access token:
    • Go to npmjs.com
    • Account Settings → Access Tokens → Generate New Token
    • Select "Automation" type (for CI/CD)
  2. Add token to GitHub:
    • Go to your repository → Settings → Secrets and variables → Actions
    • Click "New repository secret"
    • Name: NPM_TOKEN
    • Value: (paste your npm token)

Contributing

We welcome contributions! Fork the repo, create a branch, and submit a pull request.


License

This library is released under the MIT License.

changelog

Changelog

All notable changes to this project are documented here.


[3.0.3] - 2025-11-13

Fixed

  • Fixed CHANGELOG.md for consistncy

Added

  • Added github workflow

[3.0.2] - 2025-10-29

Fixed

  • Fixed minor bugs

Added

  • Added HIBP (Have I Been Pwned) support to PasswordValidator class
  • Added forceConsistentCasingInFileNames to TypeScript config for cross-platform compatibility
  • Added ESLint ignore patterns for dist, node_modules, and coverage folders

Changed

  • Removed console logging from library code (better separation of concerns)
  • Updated minEditDistance parameter documentation to indicate it's a legacy parameter
  • Fixed README.md and JSDoc documentation

[3.0.1] - 2025-01-23

removed

  • unused devDependencies: vite, semantic-release

[3.0.0] - 2025-01-20

Added

  • New PasswordValidator class for stateful validation with reusable configuration
  • updateConfig method to dynamically modify validation rules

Changed

  • BREAKING: Deleted minEditDistance
  • Updated documentation to reflect new class-based approach

[2.1.0] - 2025-01-12

Added

  • Introduced the errorLimit feature to control the maximum number of validation errors returned, improving feedback clarity and performance.
  • Updated README to include detailed documentation and examples for the errorLimit option.

Fixed

  • Negative length option handling.

[2.0.2] - 2025-01-06

Fixed

  • Empty string handling in blocklist.

[2.0.1] - 2024-12-31

Added

  • Improved the efficiency of the blocklist validator.
  • Added a detailed example to the README for customizing the blocklist with personal information.

Fixed

  • Disabled minEditDistance to prevent false positives caused by short blocklist terms.
  • Updated the README for better clarity and usage details.
  • Adjusted the Levenshtein Distance algorithm to better handle UTF-8 characters.

[2.0.0] - 2024-12-22

Breaking Changes

  • Removed fuzzyTolerance parameter.
  • Replaced static fuzzy matching with a dynamic system.

Added

  • New blocklist validation configuration options:
    • matchingSensitivity
    • minEditDistance
    • maxEditDistance
    • customDistanceCalculator
    • trimWhitespace
  • Comprehensive documentation and examples for the new matching system.
  • Improved handling of Unicode characters for blocklist validation.
  • Optional whitespace trimming for passwords and blocklist terms:
    • Enabled by default (NIST recommendation).
    • Configurable via the trimWhitespace option.

Fixed

  • Resolved an issue where short blocklist terms caused excessive false positives.

Migration Guide

Users upgrading from 1.x.x to 2.0.0 should:

  1. Replace fuzzyTolerance with the new configuration options (matchingSensitivity, minEditDistance, maxEditDistance, or customDistanceCalculator).
  2. Review and test existing blocklists to ensure compatibility with the new dynamic matching algorithm.
  3. Update integration tests to align with the updated API.

[1.0.7] - 2024-12-19

Fixed

  • Resolved a bug where short blocklist terms caused false positives.
  • Updated README for better clarity.

[1.0.6] - 2024-12-18

Added

  • Added padding for HIBP (Have I Been Pwned) API integration.

[1.0.5] - 2024-12-17

Fixed

  • Minor corrections in the README.

[1.0.4] - 2024-12-15

Added

  • New test cases for additional validation scenarios.
  • Improved code documentation with JSDoc comment blocks.
  • README updates for detailed usage examples.

[1.0.3] - 2024-12-12

Changed

  • Terminology update: Replaced "blacklist" with "blocklist."
  • Updated default maximum password length to 100K characters.

Added

  • Expanded test coverage with new cases.
  • Added project keywords for discoverability.

[1.0.2] - 2024-12-12

Fixed

  • Export issues resolved for smoother library usage.
  • README corrections for consistency.

[1.0.1] - 2024-12-12

Changed

  • Renamed the library file from nist-password-validator.js to nist-password-validator.