UNPKG

nist-password-validator

Version:

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

451 lines (439 loc) 16.3 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { PasswordValidator: () => PasswordValidator, blocklistValidator: () => blocklistValidator, hibpValidator: () => hibpValidator, lengthValidator: () => lengthValidator, validatePassword: () => validatePassword }); module.exports = __toCommonJS(index_exports); // src/utils/utf8Length.ts function getUtf8Length(input) { return [...input].length; } // src/validators/lengthValidator.ts function lengthValidator(password, min = 15, max = 1e5) { const length = getUtf8Length(password); const errors = []; if (length < min) errors.push(`Password must be at least ${min} characters.`); if (length > max) errors.push(`Password must not exceed ${max} characters.`); return { isValid: errors.length === 0, errors }; } // src/utils/levenshteinDistance.ts function levenshteinDistance(a, b) { const normalizeAndSplit = (str) => [...str.normalize("NFC")]; let aArray = normalizeAndSplit(a); let bArray = normalizeAndSplit(b); if (aArray.length === 0) return bArray.length; if (bArray.length === 0) return aArray.length; if (aArray.length < bArray.length) { [aArray, bArray] = [bArray, aArray]; } const previousRow = Array.from({ length: bArray.length + 1 }, (_, j) => j); const currentRow = new Array(bArray.length + 1); for (let i = 1; i <= aArray.length; i++) { currentRow[0] = i; for (let j = 1; j <= bArray.length; j++) { const substitutionCost = aArray[i - 1] === bArray[j - 1] ? 0 : 1; currentRow[j] = Math.min( previousRow[j] + 1, // deletion currentRow[j - 1] + 1, // insertion previousRow[j - 1] + substitutionCost // substitution ); } for (let j = 0; j <= bArray.length; j++) { previousRow[j] = currentRow[j]; } } return previousRow[bArray.length]; } // src/validators/blocklistValidator.ts function blocklistValidator(password, blocklist, options = {}) { const { matchingSensitivity = 0.25, maxEditDistance = 5, customDistanceCalculator, trimWhitespace = true, errorLimit = Infinity } = options; const errors = []; if (!Array.isArray(blocklist) || blocklist.length === 0 || blocklist.every((term) => term === "")) { return { isValid: true, errors }; } const processedBlocklistSet = new Set( blocklist.filter((term) => term.trim() !== "").map( (term) => trimWhitespace ? term.trim().toLowerCase() : term.toLowerCase() ) ); const calculateFuzzyTolerance = (term) => { if (customDistanceCalculator) { return customDistanceCalculator(term, password); } return Math.max( Math.min( Math.floor(getUtf8Length(term) * matchingSensitivity), maxEditDistance ), 0 ); }; const isTermBlocked = (blockedWord) => { const fuzzyTolerance = calculateFuzzyTolerance(blockedWord); if (getUtf8Length(blockedWord) <= fuzzyTolerance) { return processedBlocklistSet.has(blockedWord.toLowerCase()); } for (let i = 0; i <= getUtf8Length(password) - getUtf8Length(blockedWord); i++) { const substring = password.substring(i, i + getUtf8Length(blockedWord)).toLowerCase(); const distance = levenshteinDistance(substring, blockedWord); if (distance <= fuzzyTolerance) { return true; } } return false; }; for (const term of processedBlocklistSet) { if (isTermBlocked(term)) { errors.push(`Password contains a substring too similar to: "${term}".`); if (errors.length >= errorLimit) { break; } } } return { isValid: errors.length === 0, errors }; } // src/validators/hibpValidator.ts var API_URL = "https://api.pwnedpasswords.com/range/"; async function hibpValidator(password) { try { const sha1 = await generateSHA1(password); const prefix = sha1.substring(0, 5); const suffix = sha1.substring(5); const response = await fetch(`${API_URL}${prefix}`, { method: "GET", headers: { "User-Agent": "NIST-password-validator-ts", "Add-Padding": "true" } }); if (!response.ok) { const errorDetails = await response.text(); throw new Error( `Failed to check password against HaveIBeenPwned API. Status: ${response.status}, Details: ${errorDetails}` ); } const text = await response.text(); const lines = text.split("\n"); const found = lines.some((line) => { const [hashSuffix, count] = line.split(":"); return hashSuffix.trim() === suffix && parseInt(count.trim(), 10) > 0; }); return found ? { isValid: false, errors: ["Password has been compromised in a data breach."] } : { isValid: true, errors: [] }; } catch (_error) { return { isValid: false, errors: ["Unable to verify password against breach database. Please try again later."] }; } } async function generateSHA1(password) { const encoder = new TextEncoder(); const data = encoder.encode(password); const hashBuffer = await crypto.subtle.digest("SHA-1", data); const hashArray = Array.from(new Uint8Array(hashBuffer)); return hashArray.map((b) => (b < 16 ? "0" : "") + b.toString(16)).join("").toUpperCase(); } // src/utils/debounce.ts function createDebouncer(fn, delay) { let timeoutId = null; let pendingResolvers = []; return (...args) => { return new Promise((resolve, reject) => { if (timeoutId !== null) { clearTimeout(timeoutId); } pendingResolvers.push({ resolve, reject }); timeoutId = setTimeout(async () => { const resolversToNotify = pendingResolvers; pendingResolvers = []; timeoutId = null; try { const result = await fn(...args); resolversToNotify.forEach(({ resolve: resolve2 }) => resolve2(result)); } catch (error) { resolversToNotify.forEach(({ reject: reject2 }) => reject2(error)); } }, delay); }); }; } // src/validators/debouncedHibpValidator.ts var debouncerCache = /* @__PURE__ */ new Map(); function getDebouncer(delayMs) { let debouncer = debouncerCache.get(delayMs); if (!debouncer) { debouncer = createDebouncer(hibpValidator, delayMs); debouncerCache.set(delayMs, debouncer); } return debouncer; } async function debouncedHibpValidator(password, delayMs) { const debouncer = getDebouncer(delayMs); return debouncer(password); } // src/validators/inputValidator.ts function validateInput(password, options) { const errors = []; if (typeof password !== "string") { errors.push("Password must be a string."); return errors; } if (options.trimWhitespace !== false) { password = password.trim(); } if (!password) { errors.push("Password cannot be empty."); return errors; } if (options.minLength && (typeof options.minLength !== "number" || options.minLength < 1)) { errors.push("Minimum length must be a positive number."); } if (options.maxLength && (typeof options.maxLength !== "number" || options.maxLength < 1)) { errors.push("Maximum length must be a positive number."); } if (options.minLength && options.maxLength && options.minLength > options.maxLength) { errors.push("Minimum length cannot be greater than maximum length."); } if (options.blocklist) { if (!Array.isArray(options.blocklist)) { errors.push("Blocklist must be an array."); } } if (options.matchingSensitivity && typeof options.matchingSensitivity !== "number") { errors.push("Matching sensitivity must be a number."); } if (options.matchingSensitivity && (options.matchingSensitivity < 0 || options.matchingSensitivity > 1)) { errors.push("Matching sensitivity must be between 0 and 1."); } if (options.maxEditDistance && typeof options.maxEditDistance !== "number") { errors.push("Max tolerance must be a number."); } if (options.maxEditDistance && options.maxEditDistance < 0) { errors.push("Max tolerance must be greater than or equal to 0."); } if (options.errorLimit && typeof options.errorLimit !== "number") { errors.push("Error limit must be a number."); } if (options.errorLimit !== void 0 && options.errorLimit < 1) { errors.push("Error limit must be greater than or equal to 1."); } if (options.hibpDebounceMs !== void 0 && (typeof options.hibpDebounceMs !== "number" || options.hibpDebounceMs < 0)) { errors.push("HIBP debounce must be a non-negative number."); } return errors; } // src/validatePassword.ts async function validatePassword(password, options = {}) { const errors = []; const { errorLimit = Infinity } = options; const addErrors = (newErrors) => { const remainingLimit = errorLimit - errors.length; errors.push(...newErrors.slice(0, remainingLimit)); }; const inputErrors = validateInput(password, options); addErrors(inputErrors); if (errors.length >= errorLimit) { return { isValid: false, errors }; } const lengthResult = lengthValidator( password, options.minLength, options.maxLength ); addErrors(lengthResult.errors); if (errors.length >= errorLimit) { return { isValid: false, errors }; } if (options.blocklist) { const blocklistResult = blocklistValidator(password, options.blocklist, { trimWhitespace: options.trimWhitespace, matchingSensitivity: options.matchingSensitivity, maxEditDistance: options.maxEditDistance, customDistanceCalculator: options.customDistanceCalculator, errorLimit: errorLimit - errors.length // Adjust error limit based on current errors }); addErrors(blocklistResult.errors); if (errors.length >= errorLimit) { return { isValid: false, errors }; } } if (options.hibpCheck !== false) { const hibpResult = options.hibpDebounceMs ? await debouncedHibpValidator(password, options.hibpDebounceMs) : await hibpValidator(password); addErrors(hibpResult.errors); } return { isValid: errors.length === 0, errors }; } // src/utils/createPasswordValidator.ts var PasswordValidator = class { options; /** * Creates a new PasswordValidator instance with the specified options. * * @param {ValidationOptions} options - Configuration options for password validation * @param {number} [options.minLength=15] - Minimum password length (NIST recommends 8+) * @param {number} [options.maxLength=100000] - Maximum password length * @param {string[]} [options.blocklist=[]] - Array of forbidden password substrings * @param {number} [options.matchingSensitivity=0.25] - Fuzzy matching tolerance (0-1) * @param {number} [options.maxEditDistance=5] - Maximum Levenshtein distance for fuzzy matching * @param {boolean} [options.hibpCheck=true] - Check password against Have I Been Pwned database * @param {boolean} [options.trimWhitespace=true] - Trim leading/trailing whitespace * @param {number} [options.errorLimit=Infinity] - Maximum number of errors to return * @param {Function} [options.customDistanceCalculator] - Custom function for edit distance calculation */ constructor(options = { blocklist: [], trimWhitespace: true }) { this.options = options; } /** * Updates the validator's configuration by merging new options with existing ones. * * This method allows you to change validation rules without creating a new validator instance. * New options are shallow-merged with existing options, allowing partial updates. * * @param {ValidationOptions} options - New validation options to merge * * @example * ```typescript * const validator = new PasswordValidator({ minLength: 8 }); * * // Update just the minLength * validator.updateConfig({ minLength: 12 }); * * // Add a blocklist while keeping minLength * validator.updateConfig({ blocklist: ['password', 'admin'] }); * ``` */ updateConfig(options) { this.options = { ...this.options, ...options }; } /** * Validates a password against the configured rules and optionally provided overrides. * * This method performs comprehensive password validation including: * - Input type and format validation * - Length requirements (UTF-8 aware) * - Blocklist checking with fuzzy matching * - Have I Been Pwned breach database lookup (if enabled) * * The validation process stops early if the error limit is reached, improving performance * for passwords with multiple issues. * * @param {string} password - The password string to validate * @param {ValidationOptions} [options={}] - Optional overrides for this specific validation * @returns {Promise<ValidationResult>} Validation result with isValid flag and error messages * * @example * ```typescript * const validator = new PasswordValidator({ minLength: 10 }); * * const result = await validator.validate('short'); * // result = { * // isValid: false, * // errors: ['Password must be at least 10 characters.'] * // } * ``` * * @example * Override options for specific validation * ```typescript * const validator = new PasswordValidator({ minLength: 10 }); * * // Temporarily use different requirements * const result = await validator.validate('test', { minLength: 8 }); * ``` */ async validate(password, options = {}) { const errors = []; const combinedOptions = { ...this.options, ...options }; const { errorLimit = Infinity } = combinedOptions; const addErrors = (newErrors) => { const remainingLimit = errorLimit - errors.length; errors.push(...newErrors.slice(0, remainingLimit)); }; const inputErrors = validateInput(password, combinedOptions); addErrors(inputErrors); if (errors.length >= errorLimit) { return { isValid: false, errors }; } if (combinedOptions.minLength && getUtf8Length(password) < combinedOptions.minLength) { addErrors([ `Password must be at least ${combinedOptions.minLength} characters.` ]); if (errors.length >= errorLimit) { return { isValid: false, errors }; } } if (combinedOptions.maxLength && getUtf8Length(password) > combinedOptions.maxLength) { addErrors([ `Password must not exceed ${combinedOptions.maxLength} characters.` ]); if (errors.length >= errorLimit) { return { isValid: false, errors }; } } if (combinedOptions.blocklist) { const blocklistResult = blocklistValidator( password, combinedOptions.blocklist, { trimWhitespace: combinedOptions.trimWhitespace, matchingSensitivity: combinedOptions.matchingSensitivity, maxEditDistance: combinedOptions.maxEditDistance, customDistanceCalculator: combinedOptions.customDistanceCalculator, errorLimit: errorLimit - errors.length } ); addErrors(blocklistResult.errors); if (errors.length >= errorLimit) { return { isValid: false, errors }; } } if (combinedOptions.hibpCheck !== false) { const hibpResult = combinedOptions.hibpDebounceMs ? await debouncedHibpValidator(password, combinedOptions.hibpDebounceMs) : await hibpValidator(password); addErrors(hibpResult.errors); } return { isValid: errors.length === 0, errors }; } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { PasswordValidator, blocklistValidator, hibpValidator, lengthValidator, validatePassword });