~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
refactor: extract duplicated safeFetch into shared utility (#1998)
LearningCircuit220e763df3c9
diff --git a/src/local_deep_research/web/static/js/collection_create.js b/src/local_deep_research/web/static/js/collection_create.jsindex ddaaa16e3a..b42c5c11bd 100644--- a/src/local_deep_research/web/static/js/collection_create.js+++ b/src/local_deep_research/web/static/js/collection_create.js@@ -7,17 +7,7 @@// Use existing URLS configuration from config/urls.js// Collection create endpoint is now available as URLS.LIBRARY_API.COLLECTION_CREATE--// Safe fetch wrapper with URL validation-async function safeFetch(url, options = {}) {- // Internal URLs starting with '/' are safe- if (!url.startsWith('/')) {- if (!URLValidator.isSafeUrl(url)) {- throw new Error(`Blocked unsafe URL: ${url}`);- }- }- return fetch(url, options);-}+// safeFetch is now provided by utils/safe-fetch.js loaded in base.html/*** Initialize the create pagediff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.jsindex 6efbcf7a6c..f92a59b4ed 100644--- a/src/local_deep_research/web/static/js/collection_details.js+++ b/src/local_deep_research/web/static/js/collection_details.js@@ -8,18 +8,7 @@ let documentsData = [];let currentFilter = 'all';let indexingPollInterval = null;-/**- * Safe fetch wrapper with URL validation- */-async function safeFetch(url, options = {}) {- // Internal URLs starting with '/' are safe- if (!url.startsWith('/')) {- if (!URLValidator.isSafeUrl(url)) {- throw new Error(`Blocked unsafe URL: ${url}`);- }- }- return fetch(url, options);-}+// safeFetch (with URLValidator) is now provided by utils/safe-fetch.js loaded in base.html/*** Initialize the pagediff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.jsindex 20b8736919..120654fe07 100644--- a/src/local_deep_research/web/static/js/collection_upload.js+++ b/src/local_deep_research/web/static/js/collection_upload.js@@ -5,17 +5,7 @@// Use existing URLS configuration from config/urls.js// Collection upload endpoint is now available as URLS.LIBRARY_API.COLLECTION_UPLOAD--// Safe fetch wrapper with URL validation-async function safeFetch(url, options = {}) {- // Internal URLs starting with '/' are safe- if (!url.startsWith('/')) {- if (!URLValidator.isSafeUrl(url)) {- throw new Error(`Blocked unsafe URL: ${url}`);- }- }- return fetch(url, options);-}+// safeFetch (with URLValidator) is now provided by utils/safe-fetch.js loaded in base.html// Local fallback in case this script loads before services/ui.js or xss-protection.jsvar escapeHtml = window.escapeHtml || window.escapeHtmlFallback || function(str) {diff --git a/src/local_deep_research/web/static/js/collections_manager.js b/src/local_deep_research/web/static/js/collections_manager.jsindex 97f4f31f02..3eeda65895 100644--- a/src/local_deep_research/web/static/js/collections_manager.js+++ b/src/local_deep_research/web/static/js/collections_manager.js@@ -7,16 +7,7 @@let collections = [];let currentCollectionId = null;-// Safe fetch wrapper with URL validation-async function safeFetch(url, options = {}) {- // Internal URLs starting with '/' are safe- if (!url.startsWith('/')) {- if (!URLValidator.isSafeUrl(url)) {- throw new Error(`Blocked unsafe URL: ${url}`);- }- }- return fetch(url, options);-}+// safeFetch is now provided by utils/safe-fetch.js loaded in base.html/*** Initialize the pagediff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.jsindex 6dd264e7bb..546309e7c4 100644--- a/src/local_deep_research/web/static/js/embedding_settings.js+++ b/src/local_deep_research/web/static/js/embedding_settings.js@@ -8,19 +8,7 @@ let providerOptions = [];let availableModels = {};let currentSettings = null;-/**- * Safe fetch wrapper with URL validation- */-async function safeFetch(url, options = {}) {- // Internal URLs starting with '/' are safe- if (!url.startsWith('/')) {- if (!URLValidator.isSafeUrl(url)) {- throw new Error(`Blocked unsafe URL: ${url}`);- }- }- return fetch(url, options);-}-+// safeFetch is now provided by utils/safe-fetch.js loaded in base.html/*** Initialize the pagediff --git a/src/local_deep_research/web/static/js/security/safe-fetch.js b/src/local_deep_research/web/static/js/security/safe-fetch.jsnew file mode 100644index 0000000000..2247314a49--- /dev/null+++ b/src/local_deep_research/web/static/js/security/safe-fetch.js@@ -0,0 +1,24 @@+/**+ * Safe fetch wrapper with URL validation.+ * Blocks external URLs that haven't been validated.+ * Requires url-validator.js to be loaded first.+ */+async function safeFetch(url, options = {}) {+ // Internal URLs starting with '/' are safe+ if (!url.startsWith('/')) {+ if (!URLValidator.isSafeUrl(url)) {+ throw new Error(`Blocked unsafe URL: ${url}`);+ }+ }+ return fetch(url, options);+}++// Export for Node.js testing+if (typeof module !== 'undefined' && module.exports) {+ module.exports = { safeFetch };+}++// Make safeFetch available globally for browser usage+if (typeof window !== 'undefined') {+ window.safeFetch = safeFetch;+}diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.htmlindex bfebd7cede..460a2caefa 100644--- a/src/local_deep_research/web/templates/base.html+++ b/src/local_deep_research/web/templates/base.html@@ -193,6 +193,7 @@<!-- Mobile Navigation --><script src="/static/js/security/url-validator.js"></script>+ <script src="/static/js/security/safe-fetch.js"></script><script src="/static/js/mobile-navigation.js"></script></body></html>diff --git a/tests/infrastructure_tests/test_safe_fetch.test.js b/tests/infrastructure_tests/test_safe_fetch.test.jsnew file mode 100644index 0000000000..b8e3105ea0--- /dev/null+++ b/tests/infrastructure_tests/test_safe_fetch.test.js@@ -0,0 +1,140 @@+/**+ * JavaScript tests for safe-fetch.js+ * Run with: npm test tests/infrastructure_tests/test_safe_fetch.test.js+ *+ * Tests the safeFetch function which wraps fetch() with URL validation.+ */++// Mock fetch+global.fetch = jest.fn(() => Promise.resolve({ ok: true }));++// Mock SafeLogger (used by url-validator.js)+global.SafeLogger = {+ warn: jest.fn(),+ error: jest.fn(),+ info: jest.fn(),+ debug: jest.fn()+};++// Mock window.location for URL parsing+global.window = {+ location: {+ href: 'http://localhost:5000/',+ origin: 'http://localhost:5000'+ }+};++// Load the URL validator first (dependency) and expose as global+const URLValidator = require('../../src/local_deep_research/web/static/js/security/url-validator.js');+global.URLValidator = URLValidator;++// Load safe-fetch module and expose as global+const { safeFetch } = require('../../src/local_deep_research/web/static/js/security/safe-fetch.js');+global.safeFetch = safeFetch;++describe('safeFetch', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ global.fetch.mockClear();+ });++ describe('Internal URLs (starting with /)', () => {+ test('should allow internal API URLs without validation', async () => {+ await safeFetch('/api/settings');+ expect(global.fetch).toHaveBeenCalledWith('/api/settings', {});+ });++ test('should allow internal page URLs', async () => {+ await safeFetch('/history');+ expect(global.fetch).toHaveBeenCalledWith('/history', {});+ });++ test('should pass options through for internal URLs', async () => {+ const options = { method: 'POST', body: JSON.stringify({ key: 'value' }) };+ await safeFetch('/api/data', options);+ expect(global.fetch).toHaveBeenCalledWith('/api/data', options);+ });++ test('should allow deep internal paths', async () => {+ await safeFetch('/api/v1/research/123/status');+ expect(global.fetch).toHaveBeenCalledWith('/api/v1/research/123/status', {});+ });+ });++ describe('External URLs with safe schemes', () => {+ test('should allow https URLs', async () => {+ await safeFetch('https://example.com/api');+ expect(global.fetch).toHaveBeenCalledWith('https://example.com/api', {});+ });++ test('should allow http URLs', async () => {+ await safeFetch('http://example.com/api');+ expect(global.fetch).toHaveBeenCalledWith('http://example.com/api', {});+ });+ });++ describe('Unsafe URLs', () => {+ test('should block javascript: URLs', async () => {+ await expect(safeFetch('javascript:alert(1)')).rejects.toThrow('Blocked unsafe URL');+ expect(global.fetch).not.toHaveBeenCalled();+ });++ test('should block data: URLs', async () => {+ await expect(safeFetch('data:text/html,<script>alert(1)</script>')).rejects.toThrow('Blocked unsafe URL');+ expect(global.fetch).not.toHaveBeenCalled();+ });++ test('should block vbscript: URLs', async () => {+ await expect(safeFetch('vbscript:msgbox(1)')).rejects.toThrow('Blocked unsafe URL');+ expect(global.fetch).not.toHaveBeenCalled();+ });++ test('should block javascript: with mixed case', async () => {+ await expect(safeFetch('JavaScript:alert(1)')).rejects.toThrow('Blocked unsafe URL');+ expect(global.fetch).not.toHaveBeenCalled();+ });++ test('should block javascript: with leading whitespace', async () => {+ await expect(safeFetch(' javascript:alert(1)')).rejects.toThrow('Blocked unsafe URL');+ expect(global.fetch).not.toHaveBeenCalled();+ });+ });++ describe('Edge cases', () => {+ test('should handle empty options object', async () => {+ await safeFetch('/api/test', {});+ expect(global.fetch).toHaveBeenCalledWith('/api/test', {});+ });++ test('should handle URLs with query parameters', async () => {+ await safeFetch('/api/search?q=test&limit=10');+ expect(global.fetch).toHaveBeenCalledWith('/api/search?q=test&limit=10', {});+ });++ test('should handle URLs with fragments', async () => {+ await safeFetch('/page#section');+ expect(global.fetch).toHaveBeenCalledWith('/page#section', {});+ });+ });+});++describe('URLValidator integration', () => {+ test('URLValidator should be available globally', () => {+ expect(global.URLValidator).toBeDefined();+ expect(typeof global.URLValidator.isSafeUrl).toBe('function');+ });++ test('URLValidator.isSafeUrl should validate https URLs', () => {+ expect(global.URLValidator.isSafeUrl('https://example.com')).toBe(true);+ });++ test('URLValidator.isSafeUrl should reject javascript URLs', () => {+ expect(global.URLValidator.isSafeUrl('javascript:alert(1)')).toBe(false);+ });++ test('URLValidator.isUnsafeScheme should detect unsafe schemes', () => {+ expect(global.URLValidator.isUnsafeScheme('javascript:void(0)')).toBe(true);+ expect(global.URLValidator.isUnsafeScheme('data:text/html,test')).toBe(true);+ expect(global.URLValidator.isUnsafeScheme('https://example.com')).toBe(false);+ });+});