Skip to content

~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.

feat(js): redirect to login on 401 in fetchWithErrorHandling (core-API session-expiry, supersedes #3684) (#4940)

LearningCircuitcfa4cf186015
diff --git a/src/local_deep_research/web/static/js/services/api.js b/src/local_deep_research/web/static/js/services/api.js
index efb79ecc60..7356929a75 100644
--- a/src/local_deep_research/web/static/js/services/api.js
+++ b/src/local_deep_research/web/static/js/services/api.js
@@ -28,6 +28,45 @@ function getApiUrl(path) {
return `${API_BASE_URL}/${path}`;
}
+/**
+ * Decide whether a 401 from `url` should bounce the user to the login page.
+ *
+ * Only same-origin (leading-slash) API URLs qualify: a 401 from a third-party
+ * URL means that API rejected us, not that our own session expired. We also
+ * never redirect while already inside the /auth/* flow (that would loop), and
+ * we leave requests to /auth/* itself alone (the auth subsystem handles its
+ * own 401 states, e.g. failed login validation).
+ *
+ * @param {string} url - The request URL
+ * @returns {boolean}
+ */
+function shouldRedirectToLoginOn401(url) {
+ if (typeof window === 'undefined') return false;
+ if (!url.startsWith('/')) return false; // external URL
+ if (window.location.pathname.startsWith('/auth/')) return false; // already in login flow
+ if (url.startsWith('/auth/')) return false; // auth handles its own 401s
+ return true;
+}
+
+/**
+ * Send the user to the login page, preserving the current location as `next`
+ * so they land back where they were after re-authenticating.
+ *
+ * `next` is a same-origin relative path (pathname + query + hash): staying
+ * relative means it's trivially same-origin, and keeping the hash preserves
+ * in-page state (e.g. #logs) so the user lands exactly where they were. The
+ * server re-validates it via URLValidator.get_safe_redirect_path anyway.
+ */
+function redirectToLogin() {
+ const next = encodeURIComponent(
+ window.location.pathname + window.location.search + window.location.hash
+ );
+ // Hardcoded /auth/login target; `next` is a same-origin relative path that
+ // the server re-validates (get_safe_redirect_path) before redirecting.
+ // bearer:disable javascript_lang_open_redirect
+ window.location.href = `/auth/login?next=${next}`;
+}
+
/**
* Generic fetch with error handling and timeout support
* @param {string} url - The URL to fetch
@@ -52,6 +91,15 @@ async function fetchWithErrorHandling(url, options = {}) {
}
});
+ // Expired/invalid session on an internal API call: bounce the user to
+ // login (preserving where they were) instead of throwing an opaque
+ // "API Error: 401" that every caller would have to special-case. The
+ // returned Promise never resolves because the page is navigating away.
+ if (response.status === 401 && shouldRedirectToLoginOn401(url)) {
+ redirectToLogin();
+ return new Promise(() => {});
+ }
+
// Handle non-200 responses
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
@@ -243,6 +291,8 @@ if (typeof module !== 'undefined' && module.exports) {
module.exports = {
getCsrfToken,
fetchWithErrorHandling,
+ shouldRedirectToLoginOn401,
+ redirectToLogin,
getApiUrl,
postJSON,
startResearch,
@@ -288,6 +338,10 @@ if (typeof window !== 'undefined') {
postJSON,
getApiUrl,
getCsrfToken,
- fetchWithErrorHandling
+ fetchWithErrorHandling,
+ // Exposed so the direct-safeFetch call sites (library/settings/etc.)
+ // can adopt the same 401->login behavior without duplicating the logic.
+ shouldRedirectToLoginOn401,
+ redirectToLogin
};
}
diff --git a/tests/js/services/api.test.js b/tests/js/services/api.test.js
new file mode 100644
index 0000000000..c3faaec6ea
--- /dev/null
+++ b/tests/js/services/api.test.js
@@ -0,0 +1,143 @@
+/**
+ * Tests for services/api.js — fetchWithErrorHandling 401 -> login redirect.
+ *
+ * fetchWithErrorHandling is the shared entry point for the core API surface
+ * (research start/status/details/logs/history/report, config saves, deletes).
+ * It throws on any non-2xx, so callers never see a bare 401. These tests lock
+ * in the behavior that an expired session on an internal API call bounces the
+ * user to /auth/login (preserving where they were) instead of surfacing an
+ * opaque "API Error: 401", while the /auth/* flow and external URLs are left
+ * untouched to avoid redirect loops and false positives.
+ */
+
+import '@js/services/api.js';
+
+const { fetchWithErrorHandling, shouldRedirectToLoginOn401 } = window.api;
+
+describe('shouldRedirectToLoginOn401', () => {
+ const originalLocation = window.location;
+
+ beforeEach(() => {
+ delete window.location;
+ window.location = { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' };
+ });
+
+ afterEach(() => {
+ window.location = originalLocation;
+ });
+
+ it('redirects for an internal API URL', () => {
+ expect(shouldRedirectToLoginOn401('/api/history')).toBe(true);
+ });
+
+ it('does not redirect for an external URL', () => {
+ expect(shouldRedirectToLoginOn401('https://api.example.com/foo')).toBe(false);
+ });
+
+ it('does not redirect for a request to /auth/*', () => {
+ expect(shouldRedirectToLoginOn401('/auth/check')).toBe(false);
+ });
+
+ it('does not redirect while already on an /auth/* page', () => {
+ window.location.pathname = '/auth/login';
+ expect(shouldRedirectToLoginOn401('/api/history')).toBe(false);
+ });
+});
+
+describe('fetchWithErrorHandling — 401 handling', () => {
+ 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/dashboard',
+ pathname: '/dashboard',
+ search: '',
+ hash: '',
+ };
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ window.location = originalLocation;
+ });
+
+ it('returns parsed JSON on 200 without redirecting', async () => {
+ globalThis.fetch = vi.fn(() =>
+ Promise.resolve(new Response('{"ok":true}', { status: 200 }))
+ );
+ const data = await fetchWithErrorHandling('/api/history');
+ expect(data).toEqual({ ok: true });
+ expect(window.location.href).toBe('http://localhost/dashboard');
+ });
+
+ it('redirects to /auth/login with next= on 401 for an internal URL', async () => {
+ globalThis.fetch = vi.fn(() =>
+ Promise.resolve(
+ new Response('{"error":"Authentication required"}', { status: 401 })
+ )
+ );
+
+ // On the redirect path the call returns a never-resolving Promise, so
+ // race it against a short timeout to keep the test from hanging.
+ const result = await Promise.race([
+ fetchWithErrorHandling('/api/history'),
+ new Promise((resolve) => setTimeout(() => resolve('timeout'), 50)),
+ ]);
+
+ expect(result).toBe('timeout'); // never resolved
+ expect(window.location.href).toBe(
+ `/auth/login?next=${encodeURIComponent('/dashboard')}`
+ );
+ });
+
+ it('preserves the query string and hash in next= (so #logs-style state survives re-login)', async () => {
+ window.location.pathname = '/settings';
+ window.location.search = '?tab=embeddings';
+ window.location.hash = '#logs';
+ window.location.href = 'http://localhost/settings?tab=embeddings#logs';
+ globalThis.fetch = vi.fn(() =>
+ Promise.resolve(new Response('', { status: 401 }))
+ );
+
+ await Promise.race([
+ fetchWithErrorHandling('/api/history'),
+ new Promise((resolve) => setTimeout(() => resolve('timeout'), 50)),
+ ]);
+
+ expect(window.location.href).toBe(
+ `/auth/login?next=${encodeURIComponent('/settings?tab=embeddings#logs')}`
+ );
+ });
+
+ 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('{"error":"bad creds"}', { status: 401 }))
+ );
+
+ await expect(fetchWithErrorHandling('/api/history')).rejects.toThrow();
+ expect(window.location.href).toBe('http://localhost/auth/login');
+ });
+
+ it('does not redirect on 401 when the request itself targets /auth/*', async () => {
+ globalThis.fetch = vi.fn(() =>
+ Promise.resolve(new Response('{"error":"bad creds"}', { status: 401 }))
+ );
+
+ await expect(fetchWithErrorHandling('/auth/check')).rejects.toThrow();
+ expect(window.location.href).toBe('http://localhost/dashboard');
+ });
+
+ it('does not redirect on a non-401 error and throws the message', async () => {
+ globalThis.fetch = vi.fn(() =>
+ Promise.resolve(new Response('{"error":"boom"}', { status: 500 }))
+ );
+
+ await expect(fetchWithErrorHandling('/api/history')).rejects.toThrow('boom');
+ expect(window.location.href).toBe('http://localhost/dashboard');
+ });
+});