Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 38 additions & 19 deletions backend/utils/passwordPolicy.js
Original file line number Diff line number Diff line change
@@ -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 };
module.exports = {
validatePassword,
SPECIAL_CHAR_REGEX,
PASSWORD_RULES,
};
``
Loading