diff --git a/backend/utils/passwordPolicy.js b/backend/utils/passwordPolicy.js index 016af05b..f5363fe5 100644 --- a/backend/utils/passwordPolicy.js +++ b/backend/utils/passwordPolicy.js @@ -1,42 +1,61 @@ /** - * OWASP-recommended special-character set. - * Covers all printable non-alphanumeric ASCII characters that are - * unambiguous in most encoding contexts. + * Password policy validation utility. + * Checks password strength against defined security rules. */ + const SPECIAL_CHAR_REGEX = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?`~]/; -const PASSWORD_RULES = [ +const PASSWORD_RULES = Object.freeze([ { - test: (pw) => typeof pw === 'string' && pw.length >= 8, - message: 'Password must be at least 8 characters long.', + test: (password) => password.length >= 8, + message: "Password must be at least 8 characters long.", }, { - test: (pw) => /[A-Z]/.test(pw), - message: 'Password must contain at least one uppercase letter.', + test: (password) => /[A-Z]/.test(password), + message: "Password must contain at least one uppercase letter.", }, { - test: (pw) => /[a-z]/.test(pw), - message: 'Password must contain at least one lowercase letter.', + test: (password) => /[a-z]/.test(password), + message: "Password must contain at least one lowercase letter.", }, { - test: (pw) => /[0-9]/.test(pw), - message: 'Password must contain at least one number.', + test: (password) => /[0-9]/.test(password), + message: "Password must contain at least one number.", }, { - test: (pw) => SPECIAL_CHAR_REGEX.test(pw), + test: (password) => SPECIAL_CHAR_REGEX.test(password), message: - 'Password must contain at least one special character (e.g. !@#$%^&*()_+-=[]{};\':"|,.<>/?`~).', + "Password must contain at least one special character (e.g. !@#$%^&*()_+-=[]{};':\"|,.<>/?`~).", }, -]; +]); /** - * Validate a password against all rules. + * Validate a password against all security rules. + * * @param {string} password * @returns {{ valid: boolean, errors: string[] }} */ function validatePassword(password) { - const errors = PASSWORD_RULES.filter((r) => !r.test(password)).map((r) => r.message); - return { valid: errors.length === 0, errors }; + if (typeof password !== "string" || password.length === 0) { + return { + valid: false, + errors: ["Password is required and must be a valid string."], + }; + } + + const errors = PASSWORD_RULES + .filter((rule) => !rule.test(password)) + .map((rule) => rule.message); + + return { + valid: errors.length === 0, + errors, + }; } -module.exports = { validatePassword, SPECIAL_CHAR_REGEX, PASSWORD_RULES }; \ No newline at end of file +module.exports = { + validatePassword, + SPECIAL_CHAR_REGEX, + PASSWORD_RULES, +}; +``