~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix: make PasswordValidator single source of truth for password rules (#2664)
LearningCircuit842d9dac0ba3
diff --git a/src/local_deep_research/security/password_validator.py b/src/local_deep_research/security/password_validator.pyindex d406f28612..f2de84ddea 100644--- a/src/local_deep_research/security/password_validator.py+++ b/src/local_deep_research/security/password_validator.py@@ -11,6 +11,19 @@ import reclass PasswordValidator:"""Validate password strength requirements."""+ @staticmethod+ def get_requirements() -> list[str]:+ """Return human-readable password requirement labels.++ Co-located with ``validate_strength`` so the two cannot drift apart.+ """+ return [+ "At least 8 characters long",+ "At least one uppercase letter",+ "At least one lowercase letter",+ "At least one digit",+ ]+@staticmethoddef validate_strength(password: str) -> list[str]:"""Return a list of error strings for *password*.diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex 2f18c23e68..4f2814736b 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -268,6 +268,14 @@ def _perform_post_login_tasks(username: str, password: str) -> None:logger.info(f"Post-login tasks completed for user {username}")+@auth_bp.route("/validate-password", methods=["POST"])+def validate_password():+ """Validate password strength via API (used by client-side forms)."""+ password = request.form.get("password", "")+ errors = PasswordValidator.validate_strength(password)+ return jsonify({"valid": len(errors) == 0, "errors": errors})++@auth_bp.route("/register", methods=["GET"])def register_page():"""@@ -280,7 +288,9 @@ def register_page():return redirect(url_for("auth.login_page"))return render_template(- "auth/register.html", has_encryption=db_manager.has_encryption+ "auth/register.html",+ has_encryption=db_manager.has_encryption,+ password_requirements=PasswordValidator.get_requirements(),)@@ -343,7 +353,9 @@ def register():for error in errors:flash(error, "error")return render_template(- "auth/register.html", has_encryption=db_manager.has_encryption+ "auth/register.html",+ has_encryption=db_manager.has_encryption,+ password_requirements=PasswordValidator.get_requirements(),), 400# Create user in auth database@@ -362,14 +374,18 @@ def register():"Registration failed. Please try a different username.", "error")return render_template(- "auth/register.html", has_encryption=db_manager.has_encryption+ "auth/register.html",+ has_encryption=db_manager.has_encryption,+ password_requirements=PasswordValidator.get_requirements(),), 400except Exception:logger.exception(f"Registration failed for {username}")auth_db.rollback()flash("Registration failed. Please try again.", "error")return render_template(- "auth/register.html", has_encryption=db_manager.has_encryption+ "auth/register.html",+ has_encryption=db_manager.has_encryption,+ password_requirements=PasswordValidator.get_requirements(),), 500try:@@ -439,7 +455,9 @@ def register():logger.exception(f"Registration failed for {username}")flash("Registration failed. Please try again.", "error")return render_template(- "auth/register.html", has_encryption=db_manager.has_encryption+ "auth/register.html",+ has_encryption=db_manager.has_encryption,+ password_requirements=PasswordValidator.get_requirements(),), 500@@ -525,7 +543,10 @@ def change_password_page():if not username:return redirect(url_for("auth.login"))- return render_template("auth/change_password.html")+ return render_template(+ "auth/change_password.html",+ password_requirements=PasswordValidator.get_requirements(),+ )@auth_bp.route("/change-password", methods=["POST"])@@ -565,7 +586,10 @@ def change_password():if errors:for error in errors:flash(error, "error")- return render_template("auth/change_password.html"), 400+ return render_template(+ "auth/change_password.html",+ password_requirements=PasswordValidator.get_requirements(),+ ), 400# Attempt password changesuccess = db_manager.change_password(@@ -588,7 +612,10 @@ def change_password():return redirect(url_for("auth.login"))else:flash("Current password is incorrect", "error")- return render_template("auth/change_password.html"), 401+ return render_template(+ "auth/change_password.html",+ password_requirements=PasswordValidator.get_requirements(),+ ), 401@auth_bp.route("/integrity-check", methods=["GET"])diff --git a/src/local_deep_research/web/static/js/security/auth-validation.js b/src/local_deep_research/web/static/js/security/auth-validation.jsnew file mode 100644index 0000000000..157bb7be98--- /dev/null+++ b/src/local_deep_research/web/static/js/security/auth-validation.js@@ -0,0 +1,36 @@+(function() {+ 'use strict';++ // URL safety: this file only fetches a hardcoded relative API path+ // ('/auth/validate-password') — no user-supplied URLs. See url-validator.js+ // for dynamic URL validation.++ /**+ * Validate password strength via server API.+ * Single source of truth — calls PasswordValidator.validate_strength() on server.+ * @param {string} password - The password to validate+ * @param {string} csrfToken - CSRF token from the form+ * @returns {Promise<{valid: boolean, errors: string[]}>}+ */+ async function validatePasswordViaAPI(password, csrfToken) {+ const formData = new FormData();+ formData.append('password', password);+ formData.append('csrf_token', csrfToken);+ try {+ const resp = await fetch('/auth/validate-password', {+ method: 'POST',+ body: formData,+ });+ if (!resp.ok) {+ // CSRF expiry or server error — let server-side catch it on submit+ return { valid: true, errors: [] };+ }+ return await resp.json();+ } catch (e) {+ // Network error — let server-side validation catch it on submit+ return { valid: true, errors: [] };+ }+ }++ window.validatePasswordViaAPI = validatePasswordViaAPI;+})();diff --git a/src/local_deep_research/web/templates/auth/change_password.html b/src/local_deep_research/web/templates/auth/change_password.htmlindex de389f59bd..a9688c5283 100644--- a/src/local_deep_research/web/templates/auth/change_password.html+++ b/src/local_deep_research/web/templates/auth/change_password.html@@ -10,6 +10,7 @@<!-- SafeLogger must load before app.js which uses it at init --><script src="/static/js/security/safe-logger.js"></script>+ <script src="/static/js/security/auth-validation.js"></script><!-- Load all vendor dependencies and styles through Vite -->{{ vite_asset('js/app.js') }}<link rel="stylesheet" href="/static/css/themes.css">@@ -149,7 +150,9 @@<div class="ldr-process-info"><strong>New Password Requirements:</strong><ul>- <li>At least 8 characters long</li>+ {% for req in password_requirements %}+ <li>{{ req }}</li>+ {% endfor %}<li>Different from your current password</li><li>Remember to update your password manager</li></ul>@@ -163,8 +166,7 @@placeholder="New Password"autocomplete="off"required- minlength="8"- onkeyup="checkPasswordStrength(this.value)">+ minlength="8"><label for="new_password">New Password</label><div id="password-strength" class="ldr-password-strength" style="display: none;"></div></div>@@ -198,56 +200,104 @@</div><script>- function checkPasswordStrength(password) {- const strengthBar = document.getElementById('password-strength');+ const csrfToken = document.querySelector('input[name="csrf_token"]').value;+ const strengthBar = document.getElementById('password-strength');++ // Blur validation on new password field+ const newPasswordInput = document.getElementById('new_password');+ newPasswordInput.addEventListener('blur', function() {+ const value = this.value;+ if (value.length > 0) {+ validatePasswordViaAPI(value, csrfToken).then(result => {+ if (!result.valid && result.errors.length > 0) {+ this.classList.add('is-invalid');+ // Show first error via alert-style inline (reuse existing pattern)+ let errorEl = document.getElementById('new-password-error');+ if (!errorEl) {+ errorEl = document.createElement('div');+ errorEl.id = 'new-password-error';+ errorEl.style.color = 'var(--error-color)';+ errorEl.style.fontSize = '0.85rem';+ errorEl.style.marginTop = '0.25rem';+ this.parentNode.appendChild(errorEl);+ }+ errorEl.textContent = result.errors[0];+ } else {+ this.classList.remove('is-invalid');+ const errorEl = document.getElementById('new-password-error');+ if (errorEl) errorEl.textContent = '';+ }+ });+ }+ });++ // Strength indicator + clear error on input+ newPasswordInput.addEventListener('input', function() {+ const value = this.value;- if (password.length === 0) {+ // Strength indicator (always show during typing - helpful feedback)+ if (value.length === 0) {strengthBar.style.display = 'none';+ this.classList.remove('is-invalid');+ var errorEl = document.getElementById('new-password-error');+ if (errorEl) errorEl.textContent = '';return;}strengthBar.style.display = 'block';-let strength = 0;+ if (value.length >= 8) strength++;+ if (/[a-z]/.test(value)) strength++;+ if (/[A-Z]/.test(value)) strength++;+ if (/[0-9]/.test(value)) strength++;- // Length check- if (password.length >= 8) strength++;- if (password.length >= 12) strength++;-- // Character variety- if (/[a-z]/.test(password)) strength++;- if (/[A-Z]/.test(password)) strength++;- if (/[0-9]/.test(password)) strength++;- if (/[^a-zA-Z0-9]/.test(password)) strength++;-- // Update strength barstrengthBar.className = 'ldr-password-strength';- if (strength <= 2) {+ if (strength <= 1) {strengthBar.classList.add('ldr-strength-weak');- } else if (strength <= 4) {+ } else if (strength <= 3) {strengthBar.classList.add('ldr-strength-medium');} else {strengthBar.classList.add('ldr-strength-strong');}- }++ // If field was marked invalid, re-check via API to clear error+ if (this.classList.contains('is-invalid')) {+ validatePasswordViaAPI(value, csrfToken).then(result => {+ if (result.valid) {+ this.classList.remove('is-invalid');+ const errorEl = document.getElementById('new-password-error');+ if (errorEl) errorEl.textContent = '';+ }+ });+ }+ });// Form validation- document.querySelector('form').addEventListener('submit', function(e) {+ document.querySelector('form').addEventListener('submit', async function(e) {+ e.preventDefault();const currentPassword = document.getElementById('current_password').value;const newPassword = document.getElementById('new_password').value;const confirmPassword = document.getElementById('confirm_password').value;if (newPassword !== confirmPassword) {- e.preventDefault();alert('New passwords do not match!');- return false;+ return;}if (currentPassword === newPassword) {- e.preventDefault();alert('New password must be different from current password!');- return false;+ return;}++ // Validate password strength via API (single source of truth)+ const result = await validatePasswordViaAPI(newPassword, csrfToken);+ if (!result.valid) {+ alert(result.errors[0]);+ return;+ }++ // All valid — submit the form+ this.submit();});</script></body>diff --git a/src/local_deep_research/web/templates/auth/register.html b/src/local_deep_research/web/templates/auth/register.htmlindex 07a96ee3fb..0c66068913 100644--- a/src/local_deep_research/web/templates/auth/register.html+++ b/src/local_deep_research/web/templates/auth/register.html@@ -10,6 +10,7 @@<!-- SafeLogger must load before app.js which uses it at init --><script src="/static/js/security/safe-logger.js"></script>+ <script src="/static/js/security/auth-validation.js"></script><!-- Load all vendor dependencies and styles through Vite -->{{ vite_asset('js/app.js') }}@@ -437,10 +438,10 @@autocomplete="username"requiredautofocus- minlength="1"+ minlength="3"pattern="[a-zA-Z0-9_\-]+"aria-describedby="username-error">- <small>Letters, numbers, underscores, and hyphens only.</small>+ <small>At least 3 characters. Letters, numbers, underscores, and hyphens only.</small><div class="ldr-error-message" id="username-error"></div></div>@@ -462,8 +463,9 @@<div class="ldr-password-requirements"><strong>Password Requirements:</strong><ul>- <li>At least 8 characters long</li>- <li>Use a mix of letters, numbers, and symbols</li>+ {% for req in password_requirements %}+ <li>{{ req }}</li>+ {% endfor %}<li>Store it in your browser's password manager</li></ul></div>@@ -550,7 +552,9 @@return;}- if (!usernamePattern.test(value)) {+ if (value.length < 3) {+ setFieldInvalid(this, usernameError, 'Username must be at least 3 characters');+ } else if (!usernamePattern.test(value)) {setFieldInvalid(this, usernameError, 'Username can only contain letters, numbers, underscores, and hyphens');} else {setFieldValid(this, usernameError);@@ -561,6 +565,12 @@const value = this.value.trim();if (value.length === 0) {setFieldInvalid(this, usernameError, 'Username is required');+ } else if (value.length < 3) {+ setFieldInvalid(this, usernameError, 'Username must be at least 3 characters');+ } else if (!usernamePattern.test(value)) {+ setFieldInvalid(this, usernameError, 'Username can only contain letters, numbers, underscores, and hyphens');+ } else {+ setFieldValid(this, usernameError);}});@@ -568,6 +578,7 @@const passwordInput = document.getElementById('password');const passwordError = document.getElementById('password-error');const strengthBar = document.getElementById('password-strength');+ const csrfToken = document.querySelector('input[name="csrf_token"]').value;passwordInput.addEventListener('input', function() {const value = this.value;@@ -582,25 +593,26 @@strengthBar.style.display = 'block';let strength = 0;if (value.length >= 8) strength++;- if (value.length >= 12) strength++;if (/[a-z]/.test(value)) strength++;if (/[A-Z]/.test(value)) strength++;if (/[0-9]/.test(value)) strength++;- if (/[^a-zA-Z0-9]/.test(value)) strength++;strengthBar.className = 'ldr-password-strength';- if (strength <= 2) {+ if (strength <= 1) {strengthBar.classList.add('ldr-strength-weak');- } else if (strength <= 4) {+ } else if (strength <= 3) {strengthBar.classList.add('ldr-strength-medium');} else {strengthBar.classList.add('ldr-strength-strong');}- // DON'T show validation error during typing- // Only clear error state if password is now valid- if (value.length >= 8 && this.classList.contains('is-invalid')) {- setFieldValid(this, passwordError);+ // If field was marked invalid, re-check via API to clear error+ if (this.classList.contains('is-invalid')) {+ validatePasswordViaAPI(value, csrfToken).then(result => {+ if (result.valid) {+ setFieldValid(passwordInput, passwordError);+ }+ });}// Re-validate confirm password if it has a value@@ -610,11 +622,17 @@}});- // Add blur handler for password validation+ // Blur handler — validate via APIpasswordInput.addEventListener('blur', function() {const value = this.value;- if (value.length > 0 && value.length < 8) {- setFieldInvalid(this, passwordError, 'Password must be at least 8 characters');+ if (value.length > 0) {+ validatePasswordViaAPI(value, csrfToken).then(result => {+ if (!result.valid && result.errors.length > 0) {+ setFieldInvalid(passwordInput, passwordError, result.errors[0]);+ } else if (result.valid) {+ setFieldValid(passwordInput, passwordError);+ }+ });}});@@ -643,7 +661,8 @@confirmPasswordInput.addEventListener('input', validateConfirmPassword);// Form submission validation- document.querySelector('form').addEventListener('submit', function(e) {+ document.querySelector('form').addEventListener('submit', async function(e) {+ e.preventDefault();let hasError = false;// Validate username@@ -656,10 +675,11 @@hasError = true;}- // Validate password+ // Validate password via API (single source of truth)const password = passwordInput.value;- if (password.length < 8) {- setFieldInvalid(passwordInput, passwordError, 'Password must be at least 8 characters');+ const result = await validatePasswordViaAPI(password, csrfToken);+ if (!result.valid) {+ setFieldInvalid(passwordInput, passwordError, result.errors[0]);hasError = true;}@@ -678,15 +698,17 @@}if (hasError) {- e.preventDefault();// Scroll to first errorconst firstError = document.querySelector('.is-invalid');if (firstError) {firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });firstError.focus();}- return false;+ return;}++ // All valid — submit the form+ this.submit();});</script></body>diff --git a/tests/puppeteer/helpers/index.js b/tests/puppeteer/helpers/index.jsindex 77e38fa6ef..5b1f308f64 100644--- a/tests/puppeteer/helpers/index.js+++ b/tests/puppeteer/helpers/index.js@@ -281,6 +281,7 @@ async function ensureLoggedIn(page, username, password) {if (url.includes('/login')) {// Need to login after registrationsuccess = await loginUser(page, username, password);+ return success;}return !url.includes('/login');diff --git a/tests/puppeteer/test_deep_functionality.js b/tests/puppeteer/test_deep_functionality.jsindex 8efa1332ae..f02c614f9e 100644--- a/tests/puppeteer/test_deep_functionality.js+++ b/tests/puppeteer/test_deep_functionality.js@@ -28,7 +28,7 @@ const {// Generate unique username for this test run - ensures fresh state each timeconst TEST_RUN_ID = generateTestRunId();const TEST_USERNAME = `test_user_${TEST_RUN_ID}`;-const TEST_PASSWORD = 'test_password_123';+const TEST_PASSWORD = 'Test_password_123';console.log(`Test run ID: ${TEST_RUN_ID}`);console.log(`Test username: ${TEST_USERNAME}`);diff --git a/tests/puppeteer/test_openai_api_key_ui.js b/tests/puppeteer/test_openai_api_key_ui.jsindex f043729a67..965e4c6a93 100644--- a/tests/puppeteer/test_openai_api_key_ui.js+++ b/tests/puppeteer/test_openai_api_key_ui.js@@ -14,7 +14,7 @@ const { expect } = require('chai');// Test configurationconst BASE_URL = process.env.TEST_URL || 'http://localhost:5000';const TEST_USERNAME = 'test_openai_user';-const TEST_PASSWORD = 'test_password_123';+const TEST_PASSWORD = 'Test_password_123';const TEST_OPENAI_KEY = 'sk-test-1234567890abcdef';describe('OpenAI API Key Configuration UI Test', function() {diff --git a/tests/puppeteer/test_ssrf_protection.js b/tests/puppeteer/test_ssrf_protection.jsindex bb2564e1c0..70937cccdb 100644--- a/tests/puppeteer/test_ssrf_protection.js+++ b/tests/puppeteer/test_ssrf_protection.js@@ -27,7 +27,7 @@ const {// Test user credentialsconst TEST_USERNAME = 'ssrf_test_user';-const TEST_PASSWORD = 'testpassword123';+const TEST_PASSWORD = 'Testpassword123';describe('SSRF Protection - Functionality Tests', function() {this.timeout(120000); // 2 minute timeout for UI testsdiff --git a/tests/puppeteer/test_ui_functionality.js b/tests/puppeteer/test_ui_functionality.jsindex 61e446fc3f..32f47aa9ea 100644--- a/tests/puppeteer/test_ui_functionality.js+++ b/tests/puppeteer/test_ui_functionality.js@@ -26,7 +26,7 @@ const {// Test configuration - static username for UI testsconst TEST_USERNAME = 'ui_test_user';-const TEST_PASSWORD = 'test_password_123';+const TEST_PASSWORD = 'Test_password_123';// Helper to log page content (unique to this test file)async function logPageInfo(page, label = '') {diff --git a/tests/security/test_password_validator.py b/tests/security/test_password_validator.pyindex be702932ad..38f6a3eff9 100644--- a/tests/security/test_password_validator.py+++ b/tests/security/test_password_validator.py@@ -46,3 +46,17 @@ class TestPasswordValidator:def test_very_long_password_valid(self):errors = PasswordValidator.validate_strength("A1" + "a" * 200)assert errors == []++ def test_get_requirements_returns_non_empty_list(self):+ reqs = PasswordValidator.get_requirements()+ assert isinstance(reqs, list)+ assert len(reqs) > 0+ assert all(isinstance(r, str) for r in reqs)++ def test_get_requirements_count_matches_validate_strength_checks(self):+ """The number of requirements should match the number of checks+ in validate_strength (one error per check when all fail)."""+ reqs = PasswordValidator.get_requirements()+ # Empty string fails every check+ errors = PasswordValidator.validate_strength("")+ assert len(reqs) == len(errors)diff --git a/tests/web/auth/test_auth_routes.py b/tests/web/auth/test_auth_routes.pyindex 1f5f8b53f5..9fc186f78b 100644--- a/tests/web/auth/test_auth_routes.py+++ b/tests/web/auth/test_auth_routes.py@@ -14,6 +14,8 @@ from unittest.mock import MagicMock, patchfrom flask import Flask+from local_deep_research.security.password_validator import PasswordValidator+class TestGetCsrfToken:"""Tests for /csrf-token endpoint."""@@ -655,7 +657,10 @@ class TestChangePassword:},)assert response.status_code == 401- mock_render.assert_called_with("auth/change_password.html")+ mock_render.assert_called_with(+ "auth/change_password.html",+ password_requirements=PasswordValidator.get_requirements(),+ )def test_renders_page_when_authenticated(self):"""Should render change password page for authenticated user."""@@ -678,7 +683,10 @@ class TestChangePassword:response = client.get("/auth/change-password")assert response.status_code == 200- mock_render.assert_called_with("auth/change_password.html")+ mock_render.assert_called_with(+ "auth/change_password.html",+ password_requirements=PasswordValidator.get_requirements(),+ )def test_returns_400_for_weak_new_password(self):"""Should return 400 when new password is too weak."""diff --git a/tests/web/auth/test_validate_password_endpoint.py b/tests/web/auth/test_validate_password_endpoint.pynew file mode 100644index 0000000000..a3f6777889--- /dev/null+++ b/tests/web/auth/test_validate_password_endpoint.py@@ -0,0 +1,68 @@+"""Tests for POST /auth/validate-password endpoint."""++from flask import Flask+++class TestValidatePasswordEndpoint:+ """Tests for the validate-password API endpoint."""++ def _make_app(self):+ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False++ from local_deep_research.web.auth.routes import auth_bp++ app.register_blueprint(auth_bp)+ return app++ def test_strong_password_returns_valid(self):+ """Endpoint returns valid=true for a strong password."""+ app = self._make_app()+ with app.test_client() as client:+ response = client.post(+ "/auth/validate-password",+ data={"password": "StrongP4ss"},+ )+ assert response.status_code == 200+ data = response.get_json()+ assert data["valid"] is True+ assert data["errors"] == []++ def test_weak_password_returns_errors(self):+ """Endpoint returns valid=false with error list for a weak password."""+ app = self._make_app()+ with app.test_client() as client:+ response = client.post(+ "/auth/validate-password",+ data={"password": "abc"},+ )+ assert response.status_code == 200+ data = response.get_json()+ assert data["valid"] is False+ assert len(data["errors"]) > 0++ def test_empty_password_returns_all_errors(self):+ """Endpoint returns all errors for an empty password."""+ app = self._make_app()+ with app.test_client() as client:+ response = client.post(+ "/auth/validate-password",+ data={"password": ""},+ )+ data = response.get_json()+ assert data["valid"] is False+ # Should have errors for length, uppercase, lowercase, digit+ assert len(data["errors"]) == 4++ def test_missing_password_field(self):+ """Endpoint treats missing password field as empty string."""+ app = self._make_app()+ with app.test_client() as client:+ response = client.post(+ "/auth/validate-password",+ data={},+ )+ data = response.get_json()+ assert data["valid"] is False+ assert len(data["errors"]) == 4