nist-password-validator
Version:
A lightweight, zero-dependencies open-source password validator according to NIST guidelines.
258 lines (249 loc) • 9.23 kB
JavaScript
;
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 src_exports = {};
__export(src_exports, {
blocklistValidator: () => blocklistValidator,
hibpValidator: () => hibpValidator,
lengthValidator: () => lengthValidator,
validatePassword: () => validatePassword
});
module.exports = __toCommonJS(src_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")];
const aArray = normalizeAndSplit(a);
const bArray = normalizeAndSplit(b);
const matrix = Array.from(
{ length: aArray.length + 1 },
(_, i) => Array.from({ length: bArray.length + 1 }, (_2, j) => i === 0 ? j : j === 0 ? i : 0)
);
for (let i = 1; i <= aArray.length; i++) {
for (let j = 1; j <= bArray.length; j++) {
matrix[i][j] = aArray[i - 1] === bArray[j - 1] ? matrix[i - 1][j - 1] : Math.min(matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]) + 1;
}
}
return matrix[aArray.length][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) {
const errorMessage = error.message;
console.error("Error during password breach check:", errorMessage);
throw new Error(`HaveIBeenPwned check failed: ${errorMessage}`);
}
}
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/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.");
} else if (options.trimWhitespace !== false) {
options.blocklist = options.blocklist.map((term) => term.trim());
}
}
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.");
}
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 = 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 = {
blocklistValidator,
hibpValidator,
lengthValidator,
validatePassword
});