UNPKG

auth-pass

Version:

auth-pass is a lightweight & powerful password validation package that ensures smooth, secure, and password updates. No more weak passwords, no more reuse—just pure security vibes!

58 lines (48 loc) 2.45 kB
const commonPasswords = new Set([ "password", "123456", "123456789", "qwerty", "abc123", "password1", "admin", "welcome", "123123", "iloveyou", "letmein", "football", "monkey", "shadow", "sunshine" ]); function validatePasswordUpdate(oldPassword, newPassword, confirmPassword) { let errors = {}; if (!oldPassword) { errors.oldPassword = "Old password is required."; } if (!newPassword) { errors.newPassword = "New password is required."; } else if (newPassword.length < 8) { errors.newPassword = "New password must be at least 8 characters long."; } else if (newPassword.length > 16) { errors.newPassword = "New password must be at most 16 characters long."; } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/.test(newPassword)) { errors.newPassword = "New password must contain at least one uppercase letter, one lowercase letter, one number, and one special character."; } else if (commonPasswords.has(newPassword.toLowerCase())) { errors.newPassword = "New password is too common. Choose a stronger password."; } else if (levenshteinDistance(oldPassword, newPassword) < 4) { errors.newPassword = "New password is too similar to the old password. Use a more unique password."; } if (!confirmPassword) { errors.confirmPassword = "Confirm password is required."; } else if (confirmPassword !== newPassword) { errors.confirmPassword = "Confirm password does not match new password."; } return Object.keys(errors).length > 0 ? errors : null; } // Levenshtein Distance Algorithm (Checks similarity between old & new passwords) function levenshteinDistance(s1, s2) { if (!s1.length) return s2.length; if (!s2.length) return s1.length; const matrix = Array.from({ length: s1.length + 1 }, (_, i) => [i]); for (let j = 1; j <= s2.length; j++) matrix[0][j] = j; for (let i = 1; i <= s1.length; i++) { for (let j = 1; j <= s2.length; j++) { const cost = s1[i - 1] === s2[j - 1] ? 0 : 1; matrix[i][j] = Math.min( matrix[i - 1][j] + 1, // Deletion matrix[i][j - 1] + 1, // Insertion matrix[i - 1][j - 1] + cost // Substitution ); } } return matrix[s1.length][s2.length]; } module.exports = validatePasswordUpdate;