~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
feat(js): migrate direct safeFetch call sites to auth-aware safeFetchWithAuth (#4945)
LearningCircuit4ffda397e094
diff --git a/eslint.config.js b/eslint.config.jsindex 5d17530f85..7db9f7364f 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -314,7 +314,8 @@ export default [// SafeLogger: security/safe-logger.js (sanitises console output)// URLBuilder, URLS, URLValidator: URL helpers loaded in base.html// ResearchStates: config/constants.js — research-status state machine- // safeFetch: utils/safe-fetch.js — fetch wrapper with URL validation+ // safeFetch, safeFetchWithAuth: security/safe-fetch.js — fetch wrapper+ // with URL validation (safeFetchWithAuth also redirects to login on 401)// escapeHtml, sanitizeHtml: security/xss-protection.js — XSS escaping// LDR_CONSTANTS: config/constants.js — shared frontend constants// DeleteManager: deletion/delete_manager.js — deletion UI helper@@ -324,6 +325,7 @@ export default [URLValidator: "readonly",ResearchStates: "readonly",safeFetch: "readonly",+ safeFetchWithAuth: "readonly",escapeHtml: "readonly",sanitizeHtml: "readonly",LDR_CONSTANTS: "readonly",diff --git a/src/local_deep_research/web/static/js/collection_create.js b/src/local_deep_research/web/static/js/collection_create.jsindex b8bce7099b..4977863ff9 100644--- a/src/local_deep_research/web/static/js/collection_create.js+++ b/src/local_deep_research/web/static/js/collection_create.js@@ -7,7 +7,7 @@// Use existing URLS configuration from config/urls.js// Collection create endpoint is now available as URLS.LIBRARY_API.COLLECTION_CREATE-// safeFetch is now provided by utils/safe-fetch.js loaded in base.html+// safeFetch/safeFetchWithAuth are now provided by utils/safe-fetch.js loaded in base.html/*** Initialize the create page@@ -84,7 +84,7 @@ async function handleCreateCollection(e) {agent_enabled: agentEnabledEl ? agentEnabledEl.checked : true};- const response = await safeFetch(URLS.LIBRARY_API.COLLECTION_CREATE, {+ const response = await safeFetchWithAuth(URLS.LIBRARY_API.COLLECTION_CREATE, {method: 'POST',headers: {'Content-Type': 'application/json',diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.jsindex d36eae9a37..b71324bde1 100644--- a/src/local_deep_research/web/static/js/collection_details.js+++ b/src/local_deep_research/web/static/js/collection_details.js@@ -8,7 +8,7 @@ let documentsData = [];let currentFilter = 'all';let indexingPollInterval = null;-// safeFetch (with URLValidator) is now provided by utils/safe-fetch.js loaded in base.html+// safeFetch/safeFetchWithAuth (with URLValidator) are now provided by utils/safe-fetch.js loaded in base.html/*** Initialize the page@@ -43,7 +43,7 @@ async function updateCollectionIsPublic(isPublic) {const toggle = document.getElementById('collection-is-public');try {const csrfToken = window.api ? window.api.getCsrfToken() : '';- const response = await safeFetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {+ const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {method: 'PUT',headers: {'Content-Type': 'application/json',@@ -73,7 +73,7 @@ async function updateCollectionAgentEnabled(agentEnabled) {const toggle = document.getElementById('collection-agent-enabled');try {const csrfToken = window.api ? window.api.getCsrfToken() : '';- const response = await safeFetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {+ const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {method: 'PUT',headers: {'Content-Type': 'application/json',@@ -100,7 +100,7 @@ async function updateCollectionAgentEnabled(agentEnabled) {*/async function loadCollectionDetails() {try {- const response = await safeFetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DOCUMENTS, COLLECTION_ID));+ const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DOCUMENTS, COLLECTION_ID));const data = await response.json();if (data.success) {@@ -348,7 +348,7 @@ async function indexCollection(forceReindex) {const csrfToken = window.api ? window.api.getCsrfToken() : '';// Start background indexing- const response = await safeFetch(`/library/api/collections/${COLLECTION_ID}/index/start`, {+ const response = await safeFetchWithAuth(`/library/api/collections/${COLLECTION_ID}/index/start`, {method: 'POST',headers: {'Content-Type': 'application/json',@@ -389,7 +389,7 @@ async function indexCollection(forceReindex) {*/async function checkAndResumeIndexing() {try {- const response = await safeFetch(`/library/api/collections/${COLLECTION_ID}/index/status`);+ const response = await safeFetchWithAuth(`/library/api/collections/${COLLECTION_ID}/index/status`);const data = await response.json();if (data.status === 'processing') {@@ -450,7 +450,7 @@ function startPolling() {// Poll every 2 secondsindexingPollInterval = setInterval(async () => {try {- const response = await safeFetch(`/library/api/collections/${COLLECTION_ID}/index/status`);+ const response = await safeFetchWithAuth(`/library/api/collections/${COLLECTION_ID}/index/status`);const data = await response.json();updateProgressFromStatus(data);@@ -505,7 +505,7 @@ async function cancelIndexing() {try {const csrfToken = window.api ? window.api.getCsrfToken() : '';- const response = await safeFetch(`/library/api/collections/${COLLECTION_ID}/index/cancel`, {+ const response = await safeFetchWithAuth(`/library/api/collections/${COLLECTION_ID}/index/cancel`, {method: 'POST',headers: {'X-CSRFToken': csrfToken@@ -547,7 +547,7 @@ async function deleteCollection() {try {const csrfToken = window.api ? window.api.getCsrfToken() : '';- const response = await safeFetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {+ const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {method: 'DELETE',headers: {'X-CSRFToken': csrfTokendiff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.jsindex e411c8a101..10680dfab0 100644--- a/src/local_deep_research/web/static/js/collection_upload.js+++ b/src/local_deep_research/web/static/js/collection_upload.js@@ -5,7 +5,7 @@// Use existing URLS configuration from config/urls.js// Collection upload endpoint is now available as URLS.LIBRARY_API.COLLECTION_UPLOAD-// safeFetch (with URLValidator) is now provided by utils/safe-fetch.js loaded in base.html+// safeFetch/safeFetchWithAuth (with URLValidator) are now provided by utils/safe-fetch.js loaded in base.html// escapeHtml is the canonical window.escapeHtml from security/xss-protection.js// (loaded first via base.html). Do NOT reintroduce a local fallback — it would// be weaker (e.g. not escape "/") and risk a duplicate-const SyntaxError (#3706).@@ -25,7 +25,7 @@ let supportedFormats = {*/async function fetchSupportedFormats() {try {- const response = await safeFetch(URLS.LIBRARY_API.SUPPORTED_FORMATS);+ const response = await safeFetchWithAuth(URLS.LIBRARY_API.SUPPORTED_FORMATS);if (!response.ok) {throw new Error(`HTTP ${response.status}`);}diff --git a/src/local_deep_research/web/static/js/collections_manager.js b/src/local_deep_research/web/static/js/collections_manager.jsindex 321aab8078..25dc82ec71 100644--- a/src/local_deep_research/web/static/js/collections_manager.js+++ b/src/local_deep_research/web/static/js/collections_manager.js@@ -6,7 +6,7 @@// Store collections datalet collections = [];-// safeFetch is now provided by utils/safe-fetch.js loaded in base.html+// safeFetch/safeFetchWithAuth are now provided by utils/safe-fetch.js loaded in base.html// escapeHtml is the canonical window.escapeHtml from security/xss-protection.js// (loaded first via base.html). Do NOT reintroduce a local fallback — it would// be weaker (e.g. not escape "/") and risk a duplicate-const SyntaxError (#3706).@@ -38,7 +38,7 @@ document.addEventListener('DOMContentLoaded', function() {*/async function loadAutoIndexSetting() {try {- const response = await safeFetch('/settings/api/research_library.auto_index_enabled');+ const response = await safeFetchWithAuth('/settings/api/research_library.auto_index_enabled');if (!response.ok) return;const data = await response.json();const toggle = document.getElementById('auto-index-toggle');@@ -55,7 +55,7 @@ async function saveAutoIndexSetting() {const toggle = document.getElementById('auto-index-toggle');try {const csrfToken = window.api ? window.api.getCsrfToken() : '';- const response = await safeFetch('/settings/api/research_library.auto_index_enabled', {+ const response = await safeFetchWithAuth('/settings/api/research_library.auto_index_enabled', {method: 'PUT',headers: {'Content-Type': 'application/json',@@ -86,7 +86,7 @@ async function saveAutoIndexSetting() {*/async function readBackgroundSweepLegacyArm() {try {- const legacy = await safeFetch('/settings/api/document_scheduler.generate_rag');+ const legacy = await safeFetchWithAuth('/settings/api/document_scheduler.generate_rag');if (!legacy.ok) {SafeLogger.warn('Could not read legacy generate_rag setting:', legacy.status);return null;@@ -121,7 +121,7 @@ function legacyArmNeedsClear(legacyOn) {async function loadBackgroundSweepSetting() {const row = document.getElementById('background-sweep-toggle-row');try {- const response = await safeFetch('/settings/api/document_scheduler.sweep_library_collections');+ const response = await safeFetchWithAuth('/settings/api/document_scheduler.sweep_library_collections');if (!response.ok) {// Setting isn't registered yet (e.g. 404 before #4627 merges).// Hide the whole row so the toggle isn't a dead control; it only@@ -166,7 +166,7 @@ async function saveBackgroundSweepSetting() {const toggle = document.getElementById('background-sweep-toggle');const desired = toggle.checked;const csrfToken = window.api ? window.api.getCsrfToken() : '';- const putSetting = (key, value) => safeFetch('/settings/api/' + key, {+ const putSetting = (key, value) => safeFetchWithAuth('/settings/api/' + key, {method: 'PUT',headers: {'Content-Type': 'application/json',@@ -223,7 +223,7 @@ async function loadCollections() {const noCollectionsMessage = document.getElementById('no-collections-message');try {- const response = await safeFetch(URLS.LIBRARY_API.COLLECTIONS);+ const response = await safeFetchWithAuth(URLS.LIBRARY_API.COLLECTIONS);const data = await response.json();if (data.success) {@@ -393,7 +393,7 @@ async function triggerReindex(btn) {try {const csrfToken = window.api ? window.api.getCsrfToken() : '';const startUrl = collectionApiUrl(URLS.LIBRARY_API.COLLECTION_INDEX_START, collectionId);- const response = await safeFetch(startUrl, {+ const response = await safeFetchWithAuth(startUrl, {method: 'POST',headers: {'Content-Type': 'application/json',@@ -460,8 +460,8 @@ async function pollReindexStatus(collectionId) {const poll = async () => {attempts += 1;try {- const response = await safeFetch(statusUrl);- // safeFetch does NOT throw on HTTP errors, and the status+ const response = await safeFetchWithAuth(statusUrl);+ // safeFetchWithAuth does NOT throw on HTTP errors (it only diverts on 401), and the status// endpoint's except path returns 500 with body {status:'error'}// — which is in TERMINAL. Without this guard a single transient// 500 would resolve the poll and fire a false "reindex failed"diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.jsindex 7a80a1275c..ec0713aa49 100644--- a/src/local_deep_research/web/static/js/embedding_settings.js+++ b/src/local_deep_research/web/static/js/embedding_settings.js@@ -9,7 +9,7 @@ let availableModels = {};let originalValues = {};let autoSaveListenersAttached = false;-// safeFetch is now provided by utils/safe-fetch.js loaded in base.html+// safeFetch/safeFetchWithAuth are now provided by utils/safe-fetch.js loaded in base.html// escapeHtml is the canonical window.escapeHtml from security/xss-protection.js// (loaded first via base.html). Do NOT reintroduce a local fallback — it would// be weaker (e.g. not escape "/") and risk a duplicate-const SyntaxError (#3706).@@ -44,7 +44,7 @@ document.addEventListener('DOMContentLoaded', function() {*/async function loadAvailableModels() {try {- const response = await safeFetch('/library/api/rag/models');+ const response = await safeFetchWithAuth('/library/api/rag/models');const data = await response.json();if (data.success) {@@ -73,7 +73,7 @@ async function loadAvailableModels() {*/async function loadCurrentSettings() {try {- const response = await safeFetch('/library/api/rag/settings');+ const response = await safeFetchWithAuth('/library/api/rag/settings');const data = await response.json();if (data.success && data.settings) {@@ -319,7 +319,7 @@ async function saveSetting(key, value, displayName, oldValue) {try {const csrfToken = window.api ? window.api.getCsrfToken() : '';- const response = await safeFetch('/settings/api/' + key, {+ const response = await safeFetchWithAuth('/settings/api/' + key, {method: 'PUT',headers: {'Content-Type': 'application/json',@@ -788,7 +788,7 @@ async function testConfiguration() {const csrfToken = window.api ? window.api.getCsrfToken() : '';// Send test embedding request with selected configuration- const response = await safeFetch('/library/api/rag/test-embedding', {+ const response = await safeFetchWithAuth('/library/api/rag/test-embedding', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -937,7 +937,7 @@ function toggleOllamaFields() {*/async function loadOllamaUrl() {try {- const response = await safeFetch('/settings/api/embeddings.ollama.url');+ const response = await safeFetchWithAuth('/settings/api/embeddings.ollama.url');const data = await response.json();if (data && data.value) {@@ -953,7 +953,7 @@ async function loadOllamaUrl() {*/async function loadOllamaNumCtx() {try {- const response = await safeFetch('/settings/api/embeddings.ollama.num_ctx');+ const response = await safeFetchWithAuth('/settings/api/embeddings.ollama.num_ctx');const data = await response.json();if (data && data.value !== undefined && data.value !== null) {diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex a664b74112..c2dc6e9c98 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -499,11 +499,10 @@ async function performAdvancedNewsSearch(query, strategy = 'source-based', modelif (response.status === 401) {showAlert('Authentication required. Please log in to perform research.', 'error');- // Redirect to login after a short delay+ // Redirect to login after a short delay. Uses the shared helper+ // (api.js) so the next= param is built the same way everywhere.setTimeout(() => {- // hardcoded /auth/login target, next param is current page URL- // bearer:disable javascript_lang_open_redirect- window.location.href = '/auth/login?next=' + encodeURIComponent(window.location.href);+ window.api.redirectToLogin();}, 2000);return;}diff --git a/src/local_deep_research/web/static/js/security/safe-fetch.js b/src/local_deep_research/web/static/js/security/safe-fetch.jsindex 2247314a49..9a9ba87aa7 100644--- a/src/local_deep_research/web/static/js/security/safe-fetch.js+++ b/src/local_deep_research/web/static/js/security/safe-fetch.js@@ -13,12 +13,37 @@ async function safeFetch(url, options = {}) {return fetch(url, options);}+/**+ * Auth-aware variant of safeFetch for our own API endpoints.+ *+ * Identical to safeFetch, except that a 401 from an internal URL (an expired+ * session) navigates to the login page instead of returning the Response, so+ * callers that inspect response.status don't each have to special-case+ * re-authentication. On the redirect path it returns a never-resolving Promise+ * (the page is navigating away), matching fetchWithErrorHandling's behavior.+ *+ * The "which 401s redirect" decision and the login-URL construction are reused+ * from api.js (window.api) so there is a single definition shared with+ * fetchWithErrorHandling — no duplicated/drifting logic.+ *+ * Do NOT use on /auth/* endpoints — those handle their own 401 states.+ */+async function safeFetchWithAuth(url, options = {}) {+ const response = await safeFetch(url, options);+ if (response.status === 401 && window.api.shouldRedirectToLoginOn401(url)) {+ window.api.redirectToLogin();+ return new Promise(() => {}); // never resolves; page is navigating away+ }+ return response;+}+// Export for Node.js testingif (typeof module !== 'undefined' && module.exports) {- module.exports = { safeFetch };+ module.exports = { safeFetch, safeFetchWithAuth };}-// Make safeFetch available globally for browser usage+// Make the helpers available globally for browser usageif (typeof window !== 'undefined') {window.safeFetch = safeFetch;+ window.safeFetchWithAuth = safeFetchWithAuth;}diff --git a/tests/js/collections-manager.test.js b/tests/js/collections-manager.test.jsindex 2b04833d0d..5c3013ef33 100644--- a/tests/js/collections-manager.test.js+++ b/tests/js/collections-manager.test.js@@ -25,9 +25,9 @@ window.escapeHtml = (s) => String(s);window.api = { getCsrfToken: () => 'test-csrf' };globalThis.alert = () => {};-// safeFetch is a global the module calls; default to a benign stub so the+// safeFetchWithAuth is the global the module calls (auth-aware fetch wrapper); default to a benign stub so the// import-time DOMContentLoaded handler (if it fires) doesn't explode.-globalThis.safeFetch = vi.fn(() =>+globalThis.safeFetchWithAuth = vi.fn(() =>Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) }));@@ -49,7 +49,7 @@ beforeAll(async () => {});beforeEach(() => {- globalThis.safeFetch.mockReset();+ globalThis.safeFetchWithAuth.mockReset();});describe('indexStatusMarkup', () => {@@ -147,7 +147,7 @@ describe('triggerReindex', () => {it('POSTs to the start endpoint, polls to completion, and refreshes counts', async () => {const btn = makeButton('coll-1');const calls = [];- globalThis.safeFetch.mockImplementation((url, opts) => {+ globalThis.safeFetchWithAuth.mockImplementation((url, opts) => {calls.push({ url, method: opts && opts.method });if (url.includes('/index/start')) {return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, task_id: 't1' }) });@@ -176,7 +176,7 @@ describe('triggerReindex', () => {it('keeps the button disabled while indexing is in flight', async () => {const btn = makeButton('coll-2');let resolveStatus;- globalThis.safeFetch.mockImplementation((url) => {+ globalThis.safeFetchWithAuth.mockImplementation((url) => {if (url.includes('/index/start')) {return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });}@@ -206,7 +206,7 @@ describe('triggerReindex', () => {container.appendChild(btn.closest('.ldr-collection-card-wrapper'));document.body.appendChild(container);- globalThis.safeFetch.mockImplementation((url) => {+ globalThis.safeFetchWithAuth.mockImplementation((url) => {if (url.includes('/index/start')) {return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });}@@ -229,7 +229,7 @@ describe('triggerReindex', () => {const btn = makeButton('coll-4');// showError() routes through alert(); spy on it.const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});- globalThis.safeFetch.mockImplementation((url) => {+ globalThis.safeFetchWithAuth.mockImplementation((url) => {if (url.includes('/index/start')) {return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });}@@ -263,7 +263,7 @@ describe('triggerReindex', () => {const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});const logSpy = vi.spyOn(globalThis.SafeLogger, 'error');const calls = [];- globalThis.safeFetch.mockImplementation((url) => {+ globalThis.safeFetchWithAuth.mockImplementation((url) => {calls.push({ url });if (url.includes('/index/start')) {// Non-OK, non-409 start: e.g. the worker is busy / a 500.@@ -296,7 +296,7 @@ describe('triggerReindex', () => {withCollectionsContainer(btn);const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});const calls = [];- globalThis.safeFetch.mockImplementation((url) => {+ globalThis.safeFetchWithAuth.mockImplementation((url) => {calls.push({ url });if (url.includes('/index/start')) {// 409 = indexing is already in flight for this collection.@@ -335,7 +335,7 @@ describe('triggerReindex', () => {const btn = makeButton('coll-poll-1');withCollectionsContainer(btn);let statusCalls = 0;- globalThis.safeFetch.mockImplementation((url) => {+ globalThis.safeFetchWithAuth.mockImplementation((url) => {if (url.includes('/index/start')) {return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });}@@ -369,7 +369,7 @@ describe('triggerReindex', () => {withCollectionsContainer(btn);const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});let statusCalls = 0;- globalThis.safeFetch.mockImplementation((url) => {+ globalThis.safeFetchWithAuth.mockImplementation((url) => {if (url.includes('/index/start')) {return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });}@@ -422,7 +422,7 @@ describe('triggerReindex', () => {withCollectionsContainer(btn);const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});let statusCalls = 0;- globalThis.safeFetch.mockImplementation((url) => {+ globalThis.safeFetchWithAuth.mockImplementation((url) => {if (url.includes('/index/start')) {return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });}@@ -457,7 +457,7 @@ describe('triggerReindex', () => {withCollectionsContainer(btn);const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});let statusCalls = 0;- globalThis.safeFetch.mockImplementation((url) => {+ globalThis.safeFetchWithAuth.mockImplementation((url) => {if (url.includes('/index/start')) {return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });}@@ -494,7 +494,7 @@ describe('triggerReindex', () => {withCollectionsContainer(btn);const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});let statusCalls = 0;- globalThis.safeFetch.mockImplementation((url) => {+ globalThis.safeFetchWithAuth.mockImplementation((url) => {if (url.includes('/index/start')) {return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });}@@ -543,14 +543,14 @@ describe('background-sweep toggle', () => {it('loads the toggle state from document_scheduler.sweep_library_collections', async () => {const toggle = makeToggle();- globalThis.safeFetch.mockResolvedValue({+ globalThis.safeFetchWithAuth.mockResolvedValue({ok: true,json: () => Promise.resolve({ value: true }),});await loadBackgroundSweepSetting();- expect(globalThis.safeFetch).toHaveBeenCalledWith(+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledWith('/settings/api/document_scheduler.sweep_library_collections');expect(toggle.checked).toBe(true);@@ -561,7 +561,7 @@ describe('background-sweep toggle', () => {it('leaves the toggle unchecked when the setting value is false', async () => {const toggle = makeToggle();toggle.checked = true; // start checked to prove it flips off- globalThis.safeFetch.mockResolvedValue({+ globalThis.safeFetchWithAuth.mockResolvedValue({ok: true,json: () => Promise.resolve({ value: false }),});@@ -574,7 +574,7 @@ describe('background-sweep toggle', () => {it('treats a stringified "true" value as checked', async () => {const toggle = makeToggle();- globalThis.safeFetch.mockResolvedValue({+ globalThis.safeFetchWithAuth.mockResolvedValue({ok: true,json: () => Promise.resolve({ value: 'true' }),});@@ -590,7 +590,7 @@ describe('background-sweep toggle', () => {// hidden rather than shown as a dead, always-unchecked control.makeToggle();getRow().style.display = 'flex'; // pretend it was visible- globalThis.safeFetch.mockResolvedValue({+ globalThis.safeFetchWithAuth.mockResolvedValue({ok: false,status: 404,json: () => Promise.resolve({ error: 'not found' }),@@ -604,14 +604,14 @@ describe('background-sweep toggle', () => {it('persists a toggle change via PUT to the same setting key', async () => {const toggle = makeToggle();toggle.checked = true;- globalThis.safeFetch.mockResolvedValue({+ globalThis.safeFetchWithAuth.mockResolvedValue({ok: true,json: () => Promise.resolve({ value: true }),});await saveBackgroundSweepSetting();- const [url, opts] = globalThis.safeFetch.mock.calls[0];+ const [url, opts] = globalThis.safeFetchWithAuth.mock.calls[0];expect(url).toBe('/settings/api/document_scheduler.sweep_library_collections');expect(opts.method).toBe('PUT');expect(JSON.parse(opts.body)).toEqual({ value: true });@@ -622,7 +622,7 @@ describe('background-sweep toggle', () => {it('reverts the toggle when the save fails', async () => {const toggle = makeToggle();toggle.checked = true;- globalThis.safeFetch.mockResolvedValue({+ globalThis.safeFetchWithAuth.mockResolvedValue({ok: false,json: () => Promise.resolve({ error: 'boom' }),});@@ -637,16 +637,16 @@ describe('background-sweep toggle', () => {// generate_rag=true, sweep=false must NOT see an OFF toggle while the// sweep is actively running every tick.const toggle = makeToggle();- globalThis.safeFetch+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // sweep.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: true }) }); // generate_ragawait loadBackgroundSweepSetting();- expect(globalThis.safeFetch).toHaveBeenNthCalledWith(+ expect(globalThis.safeFetchWithAuth).toHaveBeenNthCalledWith(1, '/settings/api/document_scheduler.sweep_library_collections');- expect(globalThis.safeFetch).toHaveBeenNthCalledWith(+ expect(globalThis.safeFetchWithAuth).toHaveBeenNthCalledWith(2, '/settings/api/document_scheduler.generate_rag');expect(toggle.checked).toBe(true);@@ -655,7 +655,7 @@ describe('background-sweep toggle', () => {it('does not read the legacy arm when sweep is already ON', async () => {const toggle = makeToggle();- globalThis.safeFetch.mockResolvedValue({+ globalThis.safeFetchWithAuth.mockResolvedValue({ok: true,json: () => Promise.resolve({ value: true }),});@@ -663,7 +663,7 @@ describe('background-sweep toggle', () => {await loadBackgroundSweepSetting();// Only the sweep key is read; the legacy arm is irrelevant when sweep is on.- expect(globalThis.safeFetch).toHaveBeenCalledTimes(1);+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(1);expect(toggle.checked).toBe(true);});@@ -671,14 +671,14 @@ describe('background-sweep toggle', () => {// Otherwise OFF would leave generate_rag armed and the sweep running.const toggle = makeToggle();toggle.checked = false; // user just turned it OFF- globalThis.safeFetch+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: true }) }) // GET generate_rag (set).mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }); // PUT generate_rag=falseawait saveBackgroundSweepSetting();- const calls = globalThis.safeFetch.mock.calls;+ const calls = globalThis.safeFetchWithAuth.mock.calls;expect(calls).toHaveLength(3);expect(calls[0][0]).toBe('/settings/api/document_scheduler.sweep_library_collections');expect(calls[0][1].method).toBe('PUT');@@ -695,13 +695,13 @@ describe('background-sweep toggle', () => {// extra reschedule) for the common default-install case.const toggle = makeToggle();toggle.checked = false;- globalThis.safeFetch+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }); // GET generate_rag (already off)await saveBackgroundSweepSetting();- const calls = globalThis.safeFetch.mock.calls;+ const calls = globalThis.safeFetchWithAuth.mock.calls;expect(calls).toHaveLength(2); // sweep PUT + generate_rag GET, no second PUTexpect(calls[1][1]).toBeUndefined(); // the generate_rag call was a GETexpect(toggle.checked).toBe(false);@@ -712,7 +712,7 @@ describe('background-sweep toggle', () => {// reconciler is still armed — the honest displayed state is ON, not OFF.const toggle = makeToggle();toggle.checked = false;- globalThis.safeFetch+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: true }) }) // GET generate_rag (set).mockResolvedValueOnce({ ok: false, json: () => Promise.resolve({ error: 'boom' }) }); // PUT generate_rag fails@@ -728,7 +728,7 @@ describe('background-sweep toggle', () => {// the template) and show the sweep-derived state.const toggle = makeToggle();expect(getRow().style.display).toBe('none'); // starts hidden per template- globalThis.safeFetch+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // sweep.mockRejectedValueOnce(new Error('network down')); // generate_rag GET rejects@@ -740,7 +740,7 @@ describe('background-sweep toggle', () => {it('treats a stringified "true" generate_rag value as ON (effective gate)', async () => {const toggle = makeToggle();- globalThis.safeFetch+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // sweep.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: 'true' }) }); // generate_rag (string)@@ -755,14 +755,14 @@ describe('background-sweep toggle', () => {// the clear so the reconciler can never stay silently armed.const toggle = makeToggle();toggle.checked = false;- globalThis.safeFetch+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false.mockRejectedValueOnce(new Error('network blip')) // GET generate_rag rejects -> null (unknown).mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }); // PUT generate_rag=falseawait saveBackgroundSweepSetting();- const calls = globalThis.safeFetch.mock.calls;+ const calls = globalThis.safeFetchWithAuth.mock.calls;expect(calls).toHaveLength(3);expect(calls[2][0]).toBe('/settings/api/document_scheduler.generate_rag');expect(calls[2][1].method).toBe('PUT'); // clear was still attempted@@ -773,14 +773,14 @@ describe('background-sweep toggle', () => {it('turning OFF clears generate_rag when the read returns not-ok (unknown, not just reject)', async () => {const toggle = makeToggle();toggle.checked = false;- globalThis.safeFetch+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false.mockResolvedValueOnce({ ok: false, status: 500, json: () => Promise.resolve({ error: 'x' }) }) // GET generate_rag !ok -> null.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }); // PUT generate_rag=falseawait saveBackgroundSweepSetting();- const calls = globalThis.safeFetch.mock.calls;+ const calls = globalThis.safeFetchWithAuth.mock.calls;expect(calls).toHaveLength(3);expect(calls[2][1].method).toBe('PUT'); // unknown -> still clearedexpect(toggle.checked).toBe(false);@@ -789,7 +789,7 @@ describe('background-sweep toggle', () => {it('OFF with unknown legacy read AND a failed clear stays ON (conservative)', async () => {const toggle = makeToggle();toggle.checked = false;- globalThis.safeFetch+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false.mockRejectedValueOnce(new Error('blip')) // GET generate_rag -> null.mockResolvedValueOnce({ ok: false, json: () => Promise.resolve({ error: 'boom' }) }); // PUT generate_rag fails@@ -806,7 +806,7 @@ describe('background-sweep toggle', () => {// the toggle honestly ON since generate_rag may still be armed.const toggle = makeToggle();toggle.checked = false;- globalThis.safeFetch+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: true }) }) // GET generate_rag (set).mockRejectedValueOnce(new Error('network down')); // PUT generate_rag rejects -> outer catch@@ -819,14 +819,14 @@ describe('background-sweep toggle', () => {it('turning ON writes only sweep=true (does not touch the legacy arm)', async () => {const toggle = makeToggle();toggle.checked = true; // user just turned it ON- globalThis.safeFetch.mockResolvedValue({+ globalThis.safeFetchWithAuth.mockResolvedValue({ok: true,json: () => Promise.resolve({ value: true }),});await saveBackgroundSweepSetting();- const calls = globalThis.safeFetch.mock.calls;+ const calls = globalThis.safeFetchWithAuth.mock.calls;expect(calls).toHaveLength(1);expect(calls[0][0]).toBe('/settings/api/document_scheduler.sweep_library_collections');expect(JSON.parse(calls[0][1].body)).toEqual({ value: true });diff --git a/tests/js/security/safe-fetch.test.js b/tests/js/security/safe-fetch.test.jsindex ea93569343..5b424cfa58 100644--- a/tests/js/security/safe-fetch.test.js+++ b/tests/js/security/safe-fetch.test.js@@ -8,6 +8,8 @@// Load url-validator first (safe-fetch depends on it)import '@js/security/url-validator.js';import '@js/security/safe-fetch.js';+// safeFetchWithAuth reuses the shared 401 helpers exposed on window.api+import '@js/services/api.js';describe('safeFetch', () => {const originalFetch = globalThis.fetch;@@ -65,3 +67,85 @@ describe('safeFetch', () => {expect(globalThis.fetch).not.toHaveBeenCalled();});});++describe('safeFetchWithAuth', () => {+ const originalFetch = globalThis.fetch;+ const originalLocation = window.location;++ beforeEach(() => {+ // Writable stub so the redirect assignment doesn't navigate the runner.+ delete window.location;+ window.location = {+ href: 'http://localhost/library/collections',+ pathname: '/library/collections',+ search: '',+ hash: '',+ };+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ window.location = originalLocation;+ });++ it('returns the Response unchanged on 200 (no redirect)', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response('{"ok":true}', { status: 200 }))+ );+ const response = await window.safeFetchWithAuth('/library/api/collections');+ expect(response.status).toBe(200);+ expect(window.location.href).toBe('http://localhost/library/collections');+ });++ it('redirects to /auth/login with next= on 401 for an internal URL', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response('{"error":"auth"}', { status: 401 }))+ );++ // On the redirect path the call returns a never-resolving Promise.+ const result = await Promise.race([+ window.safeFetchWithAuth('/library/api/collections'),+ new Promise((resolve) => setTimeout(() => resolve('timeout'), 50)),+ ]);++ expect(result).toBe('timeout'); // never resolved+ expect(window.location.href).toBe(+ `/auth/login?next=${encodeURIComponent('/library/collections')}`+ );+ });++ it('returns the Response unchanged on a non-401 error (no redirect)', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response('{"error":"boom"}', { status: 500 }))+ );+ const response = await window.safeFetchWithAuth('/library/api/collections');+ expect(response.status).toBe(500);+ expect(window.location.href).toBe('http://localhost/library/collections');+ });++ it('does not redirect on 401 from an external URL', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response('', { status: 401 }))+ );+ const response = await window.safeFetchWithAuth('https://api.example.com/foo');+ expect(response.status).toBe(401);+ expect(window.location.href).toBe('http://localhost/library/collections');+ });++ it('does not redirect on 401 while already on an /auth/* page', async () => {+ window.location.pathname = '/auth/login';+ window.location.href = 'http://localhost/auth/login';+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response('', { status: 401 }))+ );+ const response = await window.safeFetchWithAuth('/library/api/collections');+ expect(response.status).toBe(401);+ expect(window.location.href).toBe('http://localhost/auth/login');+ });++ it('still validates URLs (blocks javascript:)', async () => {+ await expect(+ window.safeFetchWithAuth('javascript:alert(1)')+ ).rejects.toThrow('Blocked unsafe URL');+ });+});