nist-password-validator
Version:
A lightweight, zero-dependencies open-source password validator according to NIST guidelines.
74 lines (72 loc) • 2.75 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/validators/hibpValidator.ts
var hibpValidator_exports = {};
__export(hibpValidator_exports, {
generateSHA1: () => generateSHA1,
hibpValidator: () => hibpValidator
});
module.exports = __toCommonJS(hibpValidator_exports);
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();
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
generateSHA1,
hibpValidator
});