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.

fix(ui): handle expired sessions in history and library requests (#7654)

LearningCircuit085f7f908f91
diff --git a/src/local_deep_research/web/dependencies/csrf.py b/src/local_deep_research/web/dependencies/csrf.py
index 5a5a483b40..8d6fbeadf5 100644
--- a/src/local_deep_research/web/dependencies/csrf.py
+++ b/src/local_deep_research/web/dependencies/csrf.py
@@ -151,6 +151,11 @@ def generate_csrf_token(request: Request) -> str:
return token
+# Response header marking a 409 that means "the page's login was replaced"
+# (bound write or recovery fetch), as opposed to an endpoint's own conflict.
+AUTH_CHANGED_HEADER = "X-LDR-Auth-Changed"
+
+
def get_auth_context(session) -> str | None:
"""Fingerprint a login for retry fencing, without exposing its session ID.
@@ -326,6 +331,10 @@ class CSRFMiddleware:
else "Authentication required"
},
status_code=409 if context else 401,
+ # Stable marker so clients need not match on the prose
+ # (api.js isAuthContextChanged). A handler's own 409, e.g.
+ # an indexing conflict, never carries it.
+ headers={AUTH_CHANGED_HEADER: "1"} if context else None,
)
await response(scope, receive, send)
return
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index 44258d028e..656770fcd2 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -64,7 +64,11 @@ router = APIRouter(prefix="/auth", tags=["auth"])
@router.get("/csrf-token")
def get_csrf_token(request: Request):
"""Get CSRF token for API requests."""
- from ..dependencies.csrf import generate_csrf_token, get_auth_context
+ from ..dependencies.csrf import (
+ AUTH_CHANGED_HEADER,
+ generate_csrf_token,
+ get_auth_context,
+ )
context = get_auth_context(request.session)
expected_context = request.headers.get("X-LDR-Auth-Context")
@@ -78,7 +82,8 @@ def get_csrf_token(request: Request):
else "Authentication required"
},
status_code=409 if context else 401,
- headers={"Cache-Control": "no-store"},
+ headers={"Cache-Control": "no-store"}
+ | ({AUTH_CHANGED_HEADER: "1"} if context else {}),
)
token = generate_csrf_token(request)
return JSONResponse(
diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.js
index 50c25c15f1..0e33c0dc6e 100644
--- a/src/local_deep_research/web/static/js/collection_details.js
+++ b/src/local_deep_research/web/static/js/collection_details.js
@@ -545,6 +545,18 @@ function filterDocuments(filter) {
}
+/**
+ * index/start signals "already running" as 409 {success: false, error} from
+ * rag.py's _indexing_conflict. The CSRF layer's sign-in-changed 409 has no
+ * `success` field and carries X-LDR-Auth-Changed; it is shown as an error and
+ * must not resume polling.
+ */
+function isIndexingConflict(response, data) {
+ return response.status === 409
+ && data?.success === false
+ && !window.api?.isAuthContextChanged?.(response);
+}
+
/**
* Index collection documents (background indexing)
*/
@@ -575,7 +587,7 @@ async function indexCollection(forceReindex) {
const data = await response.json();
if (!data.success) {
- if (response.status === 409) {
+ if (isIndexingConflict(response, data)) {
// Already indexing
showCollectionError(data.error || 'Indexing is already in progress');
latestIndexingStatus = null;
@@ -1013,7 +1025,7 @@ async function removeDocumentFromCollection(documentId) {
try {
const csrfToken = window.api ? window.api.getCsrfToken() : '';
- const response = await fetch(`/library/api/collection/${COLLECTION_ID}/document/${documentId}`, {
+ const response = await safeFetchWithAuth(`/library/api/collection/${COLLECTION_ID}/document/${documentId}`, {
method: 'DELETE',
headers: {
'X-CSRFToken': csrfToken
@@ -1054,7 +1066,7 @@ async function deleteDocumentCompletely(documentId) {
try {
const csrfToken = window.api ? window.api.getCsrfToken() : '';
- const response = await fetch(`/library/api/document/${documentId}`, {
+ const response = await safeFetchWithAuth(`/library/api/document/${documentId}`, {
method: 'DELETE',
headers: {
'X-CSRFToken': csrfToken
diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.js
index 44680a9404..dfaa7ef808 100644
--- a/src/local_deep_research/web/static/js/components/details.js
+++ b/src/local_deep_research/web/static/js/components/details.js
@@ -61,7 +61,7 @@
try {
SafeLogger.log('Loading link analytics for research:', researchId);
- const response = await fetch(`/metrics/api/metrics/research/${researchId}/links`);
+ const response = await safeFetchWithAuth(`/metrics/api/metrics/research/${researchId}/links`);
if (!response.ok) {
SafeLogger.error('Failed to load link analytics:', response.status);
return;
@@ -297,7 +297,7 @@
// Load research metrics
SafeLogger.log('Fetching research metrics...');
- const metricsResponse = await fetch(URLBuilder.build(URLS.METRICS_API.RESEARCH, researchId));
+ const metricsResponse = await safeFetchWithAuth(URLBuilder.build(URLS.METRICS_API.RESEARCH, researchId));
SafeLogger.log('Metrics response status:', metricsResponse.status);
if (!metricsResponse.ok) {
@@ -321,7 +321,7 @@
// Load timeline metrics
SafeLogger.log('Fetching timeline metrics...');
- const timelineResponse = await fetch(URLBuilder.build(URLS.METRICS_API.RESEARCH_TIMELINE, researchId));
+ const timelineResponse = await safeFetchWithAuth(URLBuilder.build(URLS.METRICS_API.RESEARCH_TIMELINE, researchId));
SafeLogger.log('Timeline response status:', timelineResponse.status);
let timelineData = null;
@@ -335,7 +335,7 @@
// Load search metrics
SafeLogger.log('Fetching search metrics...');
- const searchResponse = await fetch(URLBuilder.build(URLS.METRICS_API.RESEARCH_SEARCH, researchId));
+ const searchResponse = await safeFetchWithAuth(URLBuilder.build(URLS.METRICS_API.RESEARCH_SEARCH, researchId));
SafeLogger.log('Search response status:', searchResponse.status);
let searchData = null;
@@ -1089,7 +1089,7 @@
try {
// /api/research/{id}/context-overflow — the router has no
// prefix; /metrics/api/... was a Flask-era guess and 404'd.
- const response = await fetch(`/api/research/${researchId}/context-overflow`);
+ const response = await safeFetchWithAuth(`/api/research/${researchId}/context-overflow`);
if (!response.ok) {
SafeLogger.error('Failed to load context overflow data');
return;
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index e11afdd31b..c07eb52d80 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -98,7 +98,7 @@
// Fallback implementation
try {
- const response = await fetch(URLS.API.HISTORY);
+ const response = await safeFetchWithAuth(URLS.API.HISTORY);
if (!response.ok) {
throw new Error(`API Error: ${response.status} ${response.statusText}`);
}
@@ -117,7 +117,7 @@
// Fallback implementation
try {
const csrfToken = window.api ? window.api.getCsrfToken() : '';
- const response = await fetch(URLBuilder.deleteResearch(researchId), {
+ const response = await safeFetchWithAuth(URLBuilder.deleteResearch(researchId), {
method: 'DELETE',
headers: {
...(csrfToken ? { 'X-CSRFToken': csrfToken } : {})
@@ -141,7 +141,7 @@
// Fallback implementation
try {
const csrfToken = window.api ? window.api.getCsrfToken() : '';
- const response = await fetch(URLS.API.CLEAR_HISTORY, {
+ const response = await safeFetchWithAuth(URLS.API.CLEAR_HISTORY, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -332,7 +332,7 @@
while (true) {
const url =
`/api/chat/sessions?status=all&limit=${PAGE_SIZE}&offset=${offset}`;
- const response = await fetch(url, {
+ const response = await safeFetchWithAuth(url, {
headers: {
...(csrfToken ? { 'X-CSRFToken': csrfToken } : {})
}
@@ -1141,7 +1141,7 @@
if (isChat) {
// Delete chat session via chat API
const csrfToken = window.api ? window.api.getCsrfToken() : '';
- const response = await fetch(`/api/chat/sessions/${encodeURIComponent(itemId)}`, {
+ const response = await safeFetchWithAuth(`/api/chat/sessions/${encodeURIComponent(itemId)}`, {
method: 'DELETE',
headers: {
...(csrfToken ? { 'X-CSRFToken': csrfToken } : {})
@@ -1224,7 +1224,7 @@
});
const csrfToken = window.api ? window.api.getCsrfToken() : '';
for (const session of chatSessions) {
- const response = await fetch(`/api/chat/sessions/${encodeURIComponent(session.id)}`, {
+ const response = await safeFetchWithAuth(`/api/chat/sessions/${encodeURIComponent(session.id)}`, {
method: 'DELETE',
headers: {
...(csrfToken ? { 'X-CSRFToken': csrfToken } : {})
diff --git a/src/local_deep_research/web/static/js/components/history_search.js b/src/local_deep_research/web/static/js/components/history_search.js
index a26790886b..1396163578 100644
--- a/src/local_deep_research/web/static/js/components/history_search.js
+++ b/src/local_deep_research/web/static/js/components/history_search.js
@@ -18,6 +18,17 @@ let cachedCollectionId = null;
let indexingPollInterval = null;
let pollErrorCount = 0;
+/**
+ * index/start signals "already running" as 409 {success: false, error} from
+ * rag.py's _indexing_conflict. The CSRF layer's sign-in-changed 409 has no
+ * `success` field and carries X-LDR-Auth-Changed; it is never a conflict.
+ */
+function isIndexingConflict(response, data) {
+ return response.status === 409
+ && data?.success === false
+ && !window.api?.isAuthContextChanged?.(response);
+}
+
/**
* Initialize the semantic search component
*/
@@ -53,7 +64,7 @@ function toggleSemanticPanel() {
*/
async function loadIndexingStatus() {
try {
- const response = await fetch(URLS.LIBRARY_API.RESEARCH_HISTORY_COLLECTION);
+ const response = await safeFetchWithAuth(URLS.LIBRARY_API.RESEARCH_HISTORY_COLLECTION);
if (!response.ok) {
throw new Error(`Server returned ${response.status}`);
}
@@ -130,7 +141,7 @@ async function triggerIndexing() {
try {
if (progressText) progressText.textContent = 'Converting research to documents...';
- const convertResp = await fetch(URLS.LIBRARY_API.RESEARCH_HISTORY_CONVERT_ALL, {
+ const convertResp = await safeFetchWithAuth(URLS.LIBRARY_API.RESEARCH_HISTORY_CONVERT_ALL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -156,7 +167,7 @@ async function triggerIndexing() {
if (progressText) progressText.textContent = 'Starting indexing...';
try {
- const startResp = await fetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_INDEX_START, cachedCollectionId), {
+ const startResp = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_INDEX_START, cachedCollectionId), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -176,12 +187,19 @@ async function triggerIndexing() {
throw new Error(`Server returned ${startResp.status}: unable to parse response`);
}
- if (!startData.success && startResp.status !== 409) {
+ if (startResp.status === 409) {
+ // Only index/start's own conflict ({success: false, error}) means
+ // "already running". A sign-in-changed 409 from the CSRF layer
+ // must surface as an error, not resume polling of an idle task.
+ if (!isIndexingConflict(startResp, startData)) {
+ throw new Error(startData?.error || startData?.detail || `Server returned ${startResp.status}`);
+ }
+ SafeLogger.log('Indexing already running, resuming polling');
+ } else if (!startData.success) {
throw new Error(startData.error || 'Failed to start indexing');
+ } else {
+ SafeLogger.log('Indexing started, beginning polling');
}
-
- // 409 means already running — just start polling
- SafeLogger.log('Indexing started, beginning polling');
} catch (startError) {
SafeLogger.error('Error starting indexing:', startError);
// Reset the in-progress flag we set synchronously at the top; the
@@ -222,7 +240,7 @@ function startPolling() {
indexingPollInterval = setInterval(async () => {
try {
- const response = await fetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_INDEX_STATUS, cachedCollectionId));
+ const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_INDEX_STATUS, cachedCollectionId));
if (!response.ok) {
throw new Error(`Status endpoint returned ${response.status}`);
}
@@ -295,7 +313,7 @@ async function checkAndResumeIndexing() {
if (!cachedCollectionId) return;
try {
- const response = await fetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_INDEX_STATUS, cachedCollectionId));
+ const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_INDEX_STATUS, cachedCollectionId));
if (!response.ok) {
SafeLogger.warn('Index status check returned ' + response.status);
return;
@@ -356,7 +374,7 @@ async function semanticSearchHistory(query) {
? window.api.getCsrfToken()
: (document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '');
- const response = await fetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_SEARCH, cachedCollectionId), {
+ const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_SEARCH, cachedCollectionId), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
diff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.js
index f4ade865f8..0efcc208eb 100644
--- a/src/local_deep_research/web/static/js/components/logpanel.js
+++ b/src/local_deep_research/web/static/js/components/logpanel.js
@@ -590,7 +590,7 @@
// hard cap (5000) so users still get the full tail.
const url = URLBuilder.researchLogs(researchId, limit);
const separator = url.includes('?') ? '&' : '?';
- const response = await fetch(`${url}${separator}priority=diagnostic`);
+ const response = await safeFetchWithAuth(`${url}${separator}priority=diagnostic`);
return await response.json();
}
@@ -1985,7 +1985,7 @@
try {
// Perform a fast HEAD pre-flight to verify endpoint status (e.g. catch 404/429/500)
// before creating the download anchor, preventing the browser from saving JSON errors as .jsonl files.
- const res = await fetch(exportUrl, { method: 'HEAD' });
+ const res = await safeFetchWithAuth(exportUrl, { method: 'HEAD' });
if (!res.ok) {
const errorMsg = res.status === 404
? 'Research logs not found.'
diff --git a/src/local_deep_research/web/static/js/components/save_to_collection.js b/src/local_deep_research/web/static/js/components/save_to_collection.js
index 41d902c132..51682f5143 100644
--- a/src/local_deep_research/web/static/js/components/save_to_collection.js
+++ b/src/local_deep_research/web/static/js/components/save_to_collection.js
@@ -70,7 +70,7 @@
*/
async function loadCollections() {
try {
- const response = await fetch(URLS.LIBRARY_API.COLLECTIONS);
+ const response = await safeFetchWithAuth(URLS.LIBRARY_API.COLLECTIONS);
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(
@@ -194,7 +194,7 @@
? window.api.getCsrfToken()
: (document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '');
- const response = await fetch(URLBuilder.build(URLS.LIBRARY_API.RESEARCH_ADD_TO_COLLECTION, researchId), {
+ const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.RESEARCH_ADD_TO_COLLECTION, researchId), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
diff --git a/src/local_deep_research/web/static/js/deletion/confirmation_modal.js b/src/local_deep_research/web/static/js/deletion/confirmation_modal.js
index e9c9135e8a..b2cae57c63 100644
--- a/src/local_deep_research/web/static/js/deletion/confirmation_modal.js
+++ b/src/local_deep_research/web/static/js/deletion/confirmation_modal.js
@@ -225,7 +225,7 @@ function getDeleteTooltip(action) {
*/
async function areConfirmationsEnabled() {
try {
- const response = await fetch('/settings/api/research_library.confirm_deletions');
+ const response = await safeFetchWithAuth('/settings/api/research_library.confirm_deletions');
if (response.ok) {
const data = await response.json();
return data.value !== false;
diff --git a/src/local_deep_research/web/static/js/pdf_upload_handler.js b/src/local_deep_research/web/static/js/pdf_upload_handler.js
index 226693487b..e09c4ab232 100644
--- a/src/local_deep_research/web/static/js/pdf_upload_handler.js
+++ b/src/local_deep_research/web/static/js/pdf_upload_handler.js
@@ -24,7 +24,7 @@ class PDFUploadHandler {
async fetchUploadLimits() {
try {
const limitsUrl = URLS?.API?.CONFIG_LIMITS || '/api/config/limits';
- const response = await fetch(limitsUrl);
+ const response = await safeFetchWithAuth(limitsUrl);
if (response.ok) {
const limits = await response.json();
this.maxFileSize = limits.max_file_size;
@@ -312,7 +312,7 @@ class PDFUploadHandler {
throw new Error('Invalid upload URL detected');
}
- const response = await fetch(uploadUrl, {
+ const response = await safeFetchWithAuth(uploadUrl, {
method: 'POST',
body: formData,
headers
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 76eaf0975f..27b47994b5 100644
--- a/src/local_deep_research/web/static/js/services/api.js
+++ b/src/local_deep_research/web/static/js/services/api.js
@@ -84,6 +84,21 @@ async function fetchWithCsrfRecovery(url, options = {}, send = fetch) {
return send(url, { ...initialOptions, headers });
}
+/**
+ * True when the server refused a request because this page's login was
+ * replaced (e.g. the user signed in again in another tab). CSRFMiddleware and
+ * /auth/csrf-token mark that 409 with X-LDR-Auth-Changed: 1; an endpoint's own
+ * 409 (such as "indexing already running") never carries it. The body's
+ * `error` holds the message to show; do not match on its prose.
+ *
+ * @param {Response} response
+ * @returns {boolean}
+ */
+function isAuthContextChanged(response) {
+ return response?.status === 409
+ && response.headers?.get?.('X-LDR-Auth-Changed') === '1';
+}
+
/**
* Get the full URL for an API endpoint
* @param {string} path - The API path (without leading slash)
@@ -552,6 +567,7 @@ if (typeof window !== 'undefined') {
getCsrfToken,
fetchWithErrorHandling,
fetchWithCsrfRecovery,
+ isAuthContextChanged,
// Exposed so the direct-safeFetch call sites (library/settings/etc.)
// can adopt the same 401->login behavior without duplicating the logic.
shouldRedirectToLoginOn401,
diff --git a/tests/js/components/context-overflow-details-caller.test.js b/tests/js/components/context-overflow-details-caller.test.js
index f056ecda55..48f6fffe3c 100644
--- a/tests/js/components/context-overflow-details-caller.test.js
+++ b/tests/js/components/context-overflow-details-caller.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Regression coverage for the details page's per-research context-overflow
* request. The page initializes through its production DOMContentLoaded path.
diff --git a/tests/js/components/details-metrics-runtime.test.js b/tests/js/components/details-metrics-runtime.test.js
index 07f729d876..e4a98e468d 100644
--- a/tests/js/components/details-metrics-runtime.test.js
+++ b/tests/js/components/details-metrics-runtime.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Runtime contract for the migrated research-details metrics loader.
*
diff --git a/tests/js/components/details-rich-metrics-runtime.test.js b/tests/js/components/details-rich-metrics-runtime.test.js
index 613b7ea813..98608d857e 100644
--- a/tests/js/components/details-rich-metrics-runtime.test.js
+++ b/tests/js/components/details-rich-metrics-runtime.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Rich runtime coverage for the migrated research-details page.
*
diff --git a/tests/js/components/history-json-client-migration.test.js b/tests/js/components/history-json-client-migration.test.js
index cc28c873ba..4aaa637d39 100644
--- a/tests/js/components/history-json-client-migration.test.js
+++ b/tests/js/components/history-json-client-migration.test.js
@@ -44,12 +44,11 @@ describe('history JSON client migration', () => {
expect(DETAILS_SOURCE)
.toContain('await window.api.fetchWithErrorHandling(detailsUrl)');
expect(DETAILS_SOURCE).not.toContain('fetch(detailsUrl)');
- // Exactly one call site migrated. The /metrics/* bare fetches in
- // the same loader are a different route family (the census flags
- // only /history/*), so they stay on fetch.
+ // The history route keeps its parsed-JSON client. Metrics use the
+ // Response-valued auth helper so their status handling stays local.
expect(handledCalls).toHaveLength(1);
expect(DETAILS_SOURCE).toContain(
- 'const metricsResponse = await fetch('
+ 'const metricsResponse = await safeFetchWithAuth('
+ 'URLBuilder.build(URLS.METRICS_API.RESEARCH, researchId));'
);
});
@@ -64,14 +63,14 @@ describe('history JSON client migration', () => {
.toContain('URLBuilder.historyLogCount(researchId)');
expect(LOGPANEL_SOURCE)
.not.toContain('fetch(URLBuilder.historyLogCount');
- // Only the log_count site migrated: the diagnostic /history/logs/
- // fetch is a sibling the gate's table left caller-less on purpose.
+ // The count keeps its parsed-JSON client; diagnostic logs use the
+ // Response-valued auth helper and retain their own body handling.
expect(handledCalls).toHaveLength(1);
// Regex literal (not a string) so the pin cannot itself trip
// no-template-curly-in-string or no-useless-concat. The backticks
// and ${...} placeholders are part of the matched source.
expect(LOGPANEL_SOURCE).toMatch(
- /await fetch\(`\$\{url\}\$\{separator\}priority=diagnostic`\)/
+ /await safeFetchWithAuth\(`\$\{url\}\$\{separator\}priority=diagnostic`\)/
);
});
});
diff --git a/tests/js/components/history-library-fetch-auth-integration.test.js b/tests/js/components/history-library-fetch-auth-integration.test.js
new file mode 100644
index 0000000000..d86decffff
--- /dev/null
+++ b/tests/js/components/history-library-fetch-auth-integration.test.js
@@ -0,0 +1,390 @@
+/**
+ * Shipped API/URL/auth wrappers and complete history/details/library consumers.
+ * This is a controlled browser-runtime contract, not a live application test.
+ * Private callbacks are reached through the fixture's fixed lexical probes;
+ * no production function is copied and transport-only unit doubles are absent.
+ */
+import {
+ AUTH_CONTEXT, CHAT_ID, COLLECTION_ID, CSRF_TOKEN, RESEARCH_ID,
+ createRuntime, response, settle,
+} from '../helpers/history-library-auth-runtime.js';
+
+let runtime;
+afterEach(() => {
+ runtime?.dispose(); runtime = null;
+ vi.restoreAllMocks();
+});
+
+const HISTORY_COLLECTION = '/library/api/research-history/collection';
+const CONVERT = '/library/api/research-history/convert-all';
+const INDEX_START = `/library/api/collections/${COLLECTION_ID}/index/start`;
+const INDEX_STATUS = `/library/api/collections/${COLLECTION_ID}/index/status`;
+const SAVE = `/library/api/research/${RESEARCH_ID}/add-to-collection`;
+const EXPORT = `/api/research/${RESEARCH_ID}/logs/export`;
+const CONFIRMATION = '/settings/api/research_library.confirm_deletions';
+const guards = { recovery: 'function', classify: 'function', redirect: 'function', auth: 'function' };
+// index/start's own conflict envelope (rag.py _indexing_conflict): no marker.
+const INDEX_CONFLICT = { success: false, error: 'Indexing is already in progress for this collection', task_id: 'synthetic-running-task' };
+const SIGN_IN_CHANGED = 'Your sign-in changed. Reload this page before trying again.';
+// CSRFMiddleware's replaced-login 409 is { error } plus X-LDR-Auth-Changed.
+// The 'marker-only' row adds success:false so only the header distinguishes
+// it from INDEX_CONFLICT; the 'middleware' row is the exact server reply.
+const signInChangedReplies = [
+ ['middleware', { error: SIGN_IN_CHANGED }],
+ ['marker-only', { success: false, error: SIGN_IN_CHANGED }],
+];
+
+// Each row reaches a different executable caller. In particular, the two chat
+// DELETE rows share an endpoint but exercise single-delete vs clear-all loops,
+// and the two indexing-status rows exercise polling vs startup resumption.
+const callers = [
+ ['history', 'history fallback GET', '/history/api', 'history-list-fallback', 'getResearchHistory'],
+ ['history', 'research fallback DELETE', `/api/delete/${RESEARCH_ID}`, 'history-delete-fallback', 'deleteResearch'],
+ ['history', 'history fallback clear', '/api/clear_history', 'history-clear-fallback', 'clearResearchHistory'],
+ ['history', 'chat session enumeration', '/api/chat/sessions?status=all&limit=100&offset=0', 'chat-list'],
+ ['history', 'single chat DELETE', `/api/chat/sessions/${CHAT_ID}`, 'chat-delete'],
+ ['history', 'clear-all chat DELETE loop', `/api/chat/sessions/${CHAT_ID}`, 'chat-clear'],
+ ['details', 'link analytics GET', `/metrics/api/metrics/research/${RESEARCH_ID}/links`, 'links'],
+ ['details', 'primary metrics GET', `/metrics/api/metrics/research/${RESEARCH_ID}`, 'metrics'],
+ ['details', 'timeline metrics GET', `/metrics/api/metrics/research/${RESEARCH_ID}/timeline`, 'timeline'],
+ ['details', 'search metrics GET', `/metrics/api/metrics/research/${RESEARCH_ID}/search`, 'search-metrics'],
+ ['details', 'context overflow GET', `/api/research/${RESEARCH_ID}/context-overflow`, 'overflow'],
+ ['history-search', 'history indexing counts GET', HISTORY_COLLECTION, 'index-count'],
+ ['history-search', 'convert-all POST', CONVERT, 'convert'],
+ ['history-search', 'start indexing POST', INDEX_START, 'index-start'],
+ ['history-search', 'indexing polling GET', INDEX_STATUS, 'index-poll'],
+ ['history-search', 'indexing resume GET', INDEX_STATUS, 'index-resume'],
+ ['history-search', 'semantic search POST', `/library/api/collections/${COLLECTION_ID}/search`, 'history-semantic'],
+ ['logs', 'diagnostic logs GET', `/api/research/${RESEARCH_ID}/logs?limit=500&priority=diagnostic`, 'logs'],
+ ['logs', 'native log export HEAD', EXPORT, 'logs-export'],
+ ['save', 'collection list GET', '/library/api/collections', 'collections'],
+ ['save', 'save research POST', SAVE, 'save'],
+ ['collection', 'remove document fallback DELETE', `/library/api/collection/${COLLECTION_ID}/document/synthetic-document`, 'document-remove'],
+ ['collection', 'delete document fallback DELETE', '/library/api/document/synthetic-document', 'document-delete'],
+ ['pdf', 'upload limits GET', '/api/config/limits', 'pdf-limits'],
+ ['pdf', 'PDF multipart POST', '/api/upload/pdf', 'pdf-upload'],
+ ['confirmation', 'deletion preference GET', CONFIRMATION, 'confirmation'],
+];
+
+it.each(callers)('%s: %s observes 401 then redirects without response continuation', async (component, _label, target, kind, missingMethod) => {
+ let armed = false;
+ let rejected;
+ runtime = createRuntime(component, input => {
+ if (armed && input === target) return response({ detail: 'Authentication required' }, 401)
+ .then(value => { rejected = value; return value; });
+ return undefined;
+ });
+ await runtime.boot();
+ expect(runtime.guardState()).toEqual(guards);
+ if (typeof missingMethod === 'string') {
+ // The precondition is verified inside the same VM, not by deleting an
+ // outer copy of its globals. Real CSRF/classifier/redirect code stays.
+ expect(runtime.dropHighLevel(missingMethod)).toBe('undefined');
+ expect(runtime.guardState()).toEqual(guards);
+ }
+ if (component === 'collection') expect(runtime.sandbox.DeleteManager).toBeUndefined();
+ if (kind === 'logs') expect(document.getElementById('log-panel-content').dataset.loading).toBeUndefined();
+ if (component === 'pdf') {
+ expect(runtime.sandbox.pdfUploadHandler.limitsLoaded).toBe(true);
+ expect(runtime.sandbox.pdfUploadHandler.getUploadedPDFs()).toEqual([]);
+ }
+ runtime.fetchMock.mockClear();
+ runtime.sandbox.ui.showMessage.mockClear();
+ const queryBefore = document.getElementById('query').value;
+ armed = true;
+ let settled = false;
+ const operation = runtime.trigger(kind);
+ expect(operation?.then).toBeTypeOf('function');
+ operation.then(() => { settled = true; }, () => { settled = true; });
+ await settle();
+
+ // The receipt assertion deliberately precedes the navigation assertion so
+ // a broken bootstrap or unexercised branch cannot look like a valid mutant.
+ expect(rejected?.status).toBe(401);
+ const next = runtime.original.pathname + runtime.original.search + runtime.original.hash;
+ expect(runtime.navigations).toEqual([`/auth/login?next=${encodeURIComponent(next)}`]);
+ expect(settled).toBe(false);
+ expect(runtime.fetchMock.mock.calls.filter(([input]) => input === target)).toHaveLength(1);
+ expect(runtime.fetchMock.mock.calls.at(-1)[0]).toBe(target);
+ expect(rejected.json).not.toHaveBeenCalled();
+ expect(rejected.blob).not.toHaveBeenCalled();
+ expect(runtime.anchorClicks).toEqual([]);
+ expect(runtime.action).not.toHaveBeenCalled();
+ expect(runtime.sandbox.URL.createObjectURL).not.toHaveBeenCalled();
+ expect(document.getElementById('query').value).toBe(queryBefore);
+ expect(runtime.sandbox.ui.showMessage).not.toHaveBeenCalled();
+ if (kind === 'convert' || kind === 'index-start') expect(runtime.intervals.size).toBe(0);
+ if (kind === 'pdf-upload') expect(runtime.sandbox.pdfUploadHandler.getUploadedPDFs()).toEqual([]);
+ if (kind === 'save') expect(document.getElementById('collection-success').textContent).toBe('');
+ if (kind === 'confirmation') expect(runtime.modalInstance.show).not.toHaveBeenCalled();
+});
+
+// Positive control for the history sign-in-changed pair. Reverts caught: an
+// over-tight fix that shows every index/start 409 as an error.
+it('keeps conversion 500 nonfatal and resumes polling after an already-running 409', async () => {
+ let armed = false;
+ let conversionReply;
+ let startReply;
+ runtime = createRuntime('history-search', input => {
+ if (!armed) return undefined;
+ if (input === CONVERT) return response({ error: 'Optional conversion unavailable' }, 500)
+ .then(value => { conversionReply = value; return value; });
+ if (input === INDEX_START) return response(INDEX_CONFLICT, 409)
+ .then(value => { startReply = value; return value; });
+ return undefined;
+ });
+ await runtime.boot(); runtime.fetchMock.mockClear(); armed = true;
+ await runtime.trigger('convert');
+ expect(runtime.fetchMock.mock.calls.map(([input]) => input)).toEqual([CONVERT, INDEX_START]);
+ expect(conversionReply.json).not.toHaveBeenCalled();
+ expect(startReply.json).toHaveBeenCalledOnce();
+ expect(runtime.intervals.size).toBe(1);
+ await runtime.pollOnce();
+ expect(runtime.fetchMock.mock.calls.at(-1)[0]).toBe(INDEX_STATUS);
+ expect(runtime.intervals.size).toBe(0); // The controlled status is idle.
+ expect(runtime.navigations).toEqual([]);
+});
+
+// Reverts caught: 'middleware' fails if triggerIndexing goes back to treating
+// any 409 as "already running" (the shipped bug: silent idle teardown);
+// 'marker-only' fails if isIndexingConflict drops its isAuthContextChanged
+// clause or api.js stops exporting isAuthContextChanged.
+it.each(signInChangedReplies)('history Index All shows a sign-in-changed 409 (%s) and never polls', async (_label, body) => {
+ let armed = false;
+ let startReply;
+ runtime = createRuntime('history-search', input => {
+ if (!armed || input !== INDEX_START) return undefined;
+ return response(body, 409, { 'X-LDR-Auth-Changed': '1' })
+ .then(value => { startReply = value; return value; });
+ });
+ await runtime.boot(); runtime.fetchMock.mockClear(); armed = true;
+ await runtime.trigger('index-start');
+ expect(startReply?.status).toBe(409);
+ expect(runtime.fetchMock.mock.calls.map(([input]) => input)).toEqual([CONVERT, INDEX_START]);
+ expect(runtime.intervals.size).toBe(0);
+ const progress = document.getElementById('indexing-progress-text');
+ expect(progress.textContent).toBe(`Error: ${SIGN_IN_CHANGED}`);
+ expect(progress.style.color).toBe('var(--error-color)');
+ expect(document.getElementById('index-all-btn').disabled).toBe(false);
+ expect(runtime.navigations).toEqual([]);
+});
+
+// Positive control for the pair above. Reverts caught: an over-tight fix that
+// shows every index/start 409 as an error (or requires the marker to poll).
+it('collection Index resumes polling for the real already-running 409', async () => {
+ let armed = false;
+ let startReply;
+ runtime = createRuntime('collection', input => {
+ if (!armed || input !== INDEX_START) return undefined;
+ return response(INDEX_CONFLICT, 409).then(value => { startReply = value; return value; });
+ });
+ await runtime.boot(); runtime.fetchMock.mockClear(); armed = true;
+ await runtime.trigger('collection-index');
+ expect(startReply?.status).toBe(409);
+ expect(runtime.sandbox.alert).toHaveBeenCalledWith(`Error: ${INDEX_CONFLICT.error}`);
+ expect(runtime.intervals.size).toBe(1);
+ const before = runtime.fetchMock.mock.calls.length;
+ await runtime.pollOnce();
+ expect(runtime.fetchMock.mock.calls[before][0]).toBe(INDEX_STATUS);
+ expect(runtime.navigations).toEqual([]);
+});
+
+// Reverts caught: 'middleware' fails if indexCollection goes back to
+// `response.status === 409` alone; 'marker-only' fails if isIndexingConflict
+// drops its isAuthContextChanged clause.
+it.each(signInChangedReplies)('collection Index shows a sign-in-changed 409 (%s) and never polls', async (_label, body) => {
+ let armed = false;
+ let startReply;
+ runtime = createRuntime('collection', input => {
+ if (!armed || input !== INDEX_START) return undefined;
+ return response(body, 409, { 'X-LDR-Auth-Changed': '1' })
+ .then(value => { startReply = value; return value; });
+ });
+ await runtime.boot(); runtime.fetchMock.mockClear(); armed = true;
+ await runtime.trigger('collection-index');
+ expect(startReply?.status).toBe(409);
+ expect(runtime.fetchMock.mock.calls.map(([input]) => input)).toEqual([INDEX_START]);
+ expect(runtime.sandbox.alert).toHaveBeenCalledWith(`Error: ${SIGN_IN_CHANGED}`);
+ expect(runtime.intervals.size).toBe(0);
+ expect(runtime.navigations).toEqual([]);
+});
+
+it('isAuthContextChanged keys on the marker header, not the status or prose alone', async () => {
+ runtime = createRuntime('save');
+ const { isAuthContextChanged } = runtime.sandbox.api;
+ expect(isAuthContextChanged(await response({ error: SIGN_IN_CHANGED }, 409, { 'X-LDR-Auth-Changed': '1' }))).toBe(true);
+ expect(isAuthContextChanged(await response({ error: SIGN_IN_CHANGED }, 409))).toBe(false);
+ expect(isAuthContextChanged(await response(INDEX_CONFLICT, 409))).toBe(false);
+ expect(isAuthContextChanged(await response({}, 403, { 'X-LDR-Auth-Changed': '1' }))).toBe(false);
+});
+
+it('keeps network-failed confirmation preferences conservative and executes a confirmed action once', async () => {
+ runtime = createRuntime('confirmation', input => (input === CONFIRMATION
+ ? Promise.reject(new Error('Preference network unavailable')) : undefined));
+ await runtime.boot();
+ const pending = runtime.trigger('confirmation');
+ await settle();
+ expect(runtime.modalInstance.show).toHaveBeenCalledOnce();
+ expect(runtime.action).not.toHaveBeenCalled();
+ document.getElementById('deleteConfirmBtn').click();
+ document.getElementById('deleteConfirmBtn').click();
+ await expect(pending).resolves.toBe('action completed');
+ expect(runtime.action).toHaveBeenCalledOnce();
+ expect(runtime.navigations).toEqual([]);
+});
+
+it('honors an explicit disabled-confirmation preference exactly once', async () => {
+ runtime = createRuntime('confirmation', input => (input === CONFIRMATION ? response({ value: false }) : undefined));
+ await runtime.boot();
+ await expect(runtime.trigger('confirmation')).resolves.toBe('action completed');
+ expect(runtime.action).toHaveBeenCalledOnce();
+ expect(runtime.modalInstance.show).not.toHaveBeenCalled();
+ expect(runtime.navigations).toEqual([]);
+});
+
+it.each(['success', 'network-failure'])('native export preserves HEAD and direct download for %s', async outcome => {
+ let reply;
+ runtime = createRuntime('logs', input => {
+ if (input !== EXPORT) return undefined;
+ if (outcome === 'network-failure') return Promise.reject(new Error('Preflight unavailable'));
+ return response().then(value => { reply = value; return value; });
+ });
+ await runtime.boot(); runtime.fetchMock.mockClear();
+ await runtime.trigger('logs-export');
+ expect(runtime.fetchMock.mock.calls).toEqual([[EXPORT, { method: 'HEAD' }]]);
+ expect(runtime.anchorClicks).toEqual([{ href: EXPORT, download: `research_logs_${RESEARCH_ID}.jsonl`, attached: true }]);
+ expect(document.querySelector('a[download]')).toBeNull();
+ expect(runtime.sandbox.URL.createObjectURL).not.toHaveBeenCalled();
+ expect(runtime.sandbox.URL.revokeObjectURL).not.toHaveBeenCalled();
+ if (reply) {
+ expect(reply.json).not.toHaveBeenCalled();
+ expect(reply.blob).not.toHaveBeenCalled();
+ }
+ expect(runtime.navigations).toEqual([]);
+});
+
+it.each([
+ [404, 'Research logs not found.'],
+ [429, 'Log export rate limit exceeded. Please wait a moment.'],
+ [500, 'Failed to export logs (HTTP 500).'],
+])('native export HTTP %i keeps specific feedback and does not download', async (status, message) => {
+ let reply;
+ runtime = createRuntime('logs', input => (input === EXPORT
+ ? response({}, status).then(value => { reply = value; return value; }) : undefined));
+ await runtime.boot(); runtime.fetchMock.mockClear();
+ await runtime.trigger('logs-export');
+ expect(runtime.fetchMock.mock.calls).toEqual([[EXPORT, { method: 'HEAD' }]]);
+ expect(runtime.sandbox.ui.showAlert).toHaveBeenCalledWith(message, 'error');
+ expect(runtime.anchorClicks).toEqual([]);
+ expect(reply.json).not.toHaveBeenCalled();
+ expect(reply.blob).not.toHaveBeenCalled();
+ expect(runtime.navigations).toEqual([]);
+});
+
+it.each(['success', 'marked-csrf-rejection'])('multipart upload preserves its body and is never replayed for %s', async outcome => {
+ let reply;
+ let bodyAtSend;
+ runtime = createRuntime('pdf', (input, options) => {
+ if (input !== '/api/upload/pdf') return undefined;
+ bodyAtSend = options.body;
+ return response(outcome === 'success' ? {
+ status: 'success', processed_files: 1,
+ extracted_texts: [{ filename: 'synthetic.pdf', text: 'Controlled PDF content', size: 4, pages: 1 }],
+ combined_text: 'Controlled PDF content', errors: [],
+ } : { detail: 'Rejected multipart CSRF' }, outcome === 'success' ? 200 : 403,
+ outcome === 'success' ? {} : { 'X-LDR-CSRF-Rejected': '1' })
+ .then(value => { reply = value; return value; });
+ });
+ await runtime.boot(); runtime.fetchMock.mockClear();
+ // A forwarding spy records the actual service input; the original CSRF
+ // implementation still executes. This checks body identity across it.
+ const recovery = vi.spyOn(runtime.sandbox.api, 'fetchWithCsrfRecovery');
+ const originalQuery = document.getElementById('query').value;
+ await runtime.trigger('pdf-upload');
+ expect(runtime.fetchMock).toHaveBeenCalledOnce();
+ const [url, options] = runtime.fetchMock.mock.calls[0];
+ expect(url).toBe('/api/upload/pdf');
+ expect(options.method).toBe('POST');
+ expect(bodyAtSend).toBeInstanceOf(window.FormData);
+ expect(bodyAtSend).toBe(recovery.mock.calls[0][1].body);
+ expect(bodyAtSend.getAll('files')).toHaveLength(1);
+ expect(bodyAtSend.get('files').name).toBe('synthetic.pdf');
+ const headers = new globalThis.Headers(options.headers);
+ expect(headers.get('X-CSRFToken')).toBe(CSRF_TOKEN);
+ expect(headers.has('Content-Type')).toBe(false);
+ expect(headers.has('X-LDR-Auth-Context')).toBe(false); // Nonrepeatable body.
+ if (outcome === 'success') {
+ expect(reply.json).toHaveBeenCalledOnce();
+ expect(document.getElementById('query').value).toContain('Controlled PDF content');
+ expect(runtime.sandbox.pdfUploadHandler.getUploadedPDFs()).toHaveLength(1);
+ } else {
+ expect(reply.json).not.toHaveBeenCalled();
+ expect(document.getElementById('query').value).toBe(originalQuery);
+ expect(runtime.sandbox.pdfUploadHandler.getUploadedPDFs()).toEqual([]);
+ }
+ expect(runtime.navigations).toEqual([]);
+});
+
+it.each(['success', 'refresh-401', 'replacement-409', 'replacement-body'])('actual save CSRF recovery handles %s with one original login', async outcome => {
+ let armed = false;
+ let writes = 0;
+ let rejectedRefresh;
+ runtime = createRuntime('save', input => {
+ if (!armed) return undefined;
+ if (input === SAVE && ++writes === 1) return response({ detail: 'CSRF rejected' }, 403, { 'X-LDR-CSRF-Rejected': '1' });
+ if (input === '/auth/csrf-token') {
+ const status = outcome === 'refresh-401' ? 401 : outcome === 'replacement-409' ? 409 : 200;
+ const body = status === 200
+ ? { auth_context: outcome === 'replacement-body' ? 'd'.repeat(64) : AUTH_CONTEXT, csrf_token: 'fresh-area3-csrf' }
+ : { detail: status === 401 ? 'Authentication required' : 'Sign-in changed' };
+ return response(body, status).then(value => { rejectedRefresh = value; return value; });
+ }
+ return undefined;
+ });
+ await runtime.boot(); runtime.fetchMock.mockClear(); armed = true;
+ let settled = false;
+ const pending = runtime.trigger('save');
+ pending.then(() => { settled = true; }, () => { settled = true; });
+ await settle();
+ const originals = runtime.fetchMock.mock.calls.filter(([input]) => input === SAVE);
+ const refreshes = runtime.fetchMock.mock.calls.filter(([input]) => input === '/auth/csrf-token');
+ expect(refreshes).toHaveLength(1);
+ expect(refreshes[0][1]).toMatchObject({ method: 'GET', credentials: 'same-origin', cache: 'no-store', redirect: 'error' });
+ expect(new globalThis.Headers(refreshes[0][1].headers).get('X-LDR-Auth-Context')).toBe(AUTH_CONTEXT);
+ expect(originals[0][1].body).toBe(JSON.stringify({ collection_id: COLLECTION_ID }));
+ expect(originals[0][1].method).toBe('POST');
+ expect(new globalThis.Headers(originals[0][1].headers).get('X-LDR-Auth-Context')).toBe(AUTH_CONTEXT);
+ if (outcome === 'success') {
+ await pending;
+ expect(originals).toHaveLength(2);
+ expect(originals[1][1].body).toBe(originals[0][1].body);
+ expect(originals[1][1].method).toBe(originals[0][1].method);
+ expect(new globalThis.Headers(originals[0][1].headers).get('X-CSRFToken')).toBe(CSRF_TOKEN);
+ expect(new globalThis.Headers(originals[1][1].headers).get('X-CSRFToken')).toBe('fresh-area3-csrf');
+ expect(new globalThis.Headers(originals[1][1].headers).get('X-LDR-Auth-Context')).toBe(AUTH_CONTEXT);
+ expect(document.getElementById('collection-success').textContent).toContain('2 documents added.');
+ expect(document.querySelector('meta[name="csrf-token"]').content).toBe('fresh-area3-csrf');
+ } else {
+ expect(originals).toHaveLength(1);
+ expect(document.getElementById('collection-success').textContent).toBe('');
+ if (outcome === 'refresh-401') {
+ expect(rejectedRefresh?.status).toBe(401);
+ expect(settled).toBe(false);
+ expect(rejectedRefresh.json).not.toHaveBeenCalled();
+ const next = runtime.original.pathname + runtime.original.search + runtime.original.hash;
+ expect(runtime.navigations).toEqual([`/auth/login?next=${encodeURIComponent(next)}`]);
+ } else {
+ await pending;
+ expect(document.getElementById('collection-error').textContent).toMatch(/[Ss]ign-in changed/);
+ }
+ }
+ if (outcome !== 'refresh-401') expect(runtime.navigations).toEqual([]);
+});
+
+it('leaves an auth endpoint own 401 observable without a login loop', async () => {
+ runtime = createRuntime('save', input => (input === '/auth/login' ? response({ detail: 'Invalid sign-in' }, 401) : undefined));
+ const result = await runtime.sandbox.safeFetchWithAuth('/auth/login');
+ expect(result.status).toBe(401);
+ expect(result.json).not.toHaveBeenCalled();
+ expect(runtime.navigations).toEqual([]);
+});
diff --git a/tests/js/components/history-migration-contract.test.js b/tests/js/components/history-migration-contract.test.js
index fa5b53497f..3b3e3e833c 100644
--- a/tests/js/components/history-migration-contract.test.js
+++ b/tests/js/components/history-migration-contract.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Browser-side contract for the history endpoints migrated in #3299.
*
diff --git a/tests/js/components/history-search-polling-runtime.test.js b/tests/js/components/history-search-polling-runtime.test.js
index 59457c2e78..a766de03d2 100644
--- a/tests/js/components/history-search-polling-runtime.test.js
+++ b/tests/js/components/history-search-polling-runtime.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/** Direct runtime coverage for history indexing polling and cache recovery. */
const COLLECTION_URL = '/library/api/research-history/collection';
diff --git a/tests/js/components/history-search.test.js b/tests/js/components/history-search.test.js
index 54d05193b4..3a21119dcb 100644
--- a/tests/js/components/history-search.test.js
+++ b/tests/js/components/history-search.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Tests for components/history_search.js
*
diff --git a/tests/js/components/logpanel-error-indicator.test.js b/tests/js/components/logpanel-error-indicator.test.js
index 4db6d92acc..ec6f6b2085 100644
--- a/tests/js/components/logpanel-error-indicator.test.js
+++ b/tests/js/components/logpanel-error-indicator.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Tests for the log-panel header badge's ERROR severity signal
* (`.ldr-log-indicator--has-error`), added by PR #5648 and corrected in
diff --git a/tests/js/components/logpanel.test.js b/tests/js/components/logpanel.test.js
index b75cd325f2..c313594c2d 100644
--- a/tests/js/components/logpanel.test.js
+++ b/tests/js/components/logpanel.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Tests for components/logpanel.js
*
diff --git a/tests/js/components/save-to-collection-runtime.test.js b/tests/js/components/save-to-collection-runtime.test.js
index 8df743438f..ffeccf11bf 100644
--- a/tests/js/components/save-to-collection-runtime.test.js
+++ b/tests/js/components/save-to-collection-runtime.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* End-to-end browser contract for the results-page collection picker.
* It binds both migrated FastAPI calls and the response envelopes consumed
diff --git a/tests/js/deletion/delete-modules.test.js b/tests/js/deletion/delete-modules.test.js
index 597556459a..527839a6ac 100644
--- a/tests/js/deletion/delete-modules.test.js
+++ b/tests/js/deletion/delete-modules.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Tests for deletion modules — confirmation_modal.js and delete_manager.js
*
diff --git a/tests/js/helpers/history-library-auth-runtime.js b/tests/js/helpers/history-library-auth-runtime.js
new file mode 100644
index 0000000000..c43f368789
--- /dev/null
+++ b/tests/js/helpers/history-library-auth-runtime.js
@@ -0,0 +1,290 @@
+/**
+ * Complete shipped consumers and authentication transports in an isolated VM.
+ * The DOM, server, widgets and clock are controlled. Fixed lexical probes expose
+ * private callbacks without copying or rewriting any production function body.
+ * No real timers, application server, database or provider is started here.
+ */
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import vm from 'node:vm';
+
+const JS_ROOT = resolve(__dirname, '../../../src/local_deep_research/web/static/js');
+export const AUTH_CONTEXT = 'c'.repeat(64);
+export const RESEARCH_ID = 'research-area3';
+export const COLLECTION_ID = 'collection-area3';
+export const CHAT_ID = 'chat-area3';
+export const CSRF_TOKEN = 'area3-csrf';
+
+export function response(body = {}, status = 200, headers = {}) {
+ return Promise.resolve({
+ ok: status >= 200 && status < 300,
+ status, statusText: String(status), redirected: false,
+ headers: new globalThis.Headers(headers),
+ json: vi.fn().mockResolvedValue(body),
+ blob: vi.fn().mockResolvedValue(new Blob(['synthetic export'])),
+ });
+}
+
+export async function settle() {
+ for (let turn = 0; turn < 80; turn++) await Promise.resolve();
+}
+
+const FIXTURE = `
+ <div id="history-items"></div><input id="history-search">
+ <button id="clear-history-btn"></button><div id="history-empty-message"></div>
+ <div id="semantic-panel-header"></div><i id="semantic-panel-toggle"></i>
+ <div id="semantic-panel-content"></div><span id="indexed-count"></span><span id="total-count"></span>
+ <button id="index-all-btn">Index All</button><div id="indexing-progress">
+ <div id="indexing-progress-bar"></div><div id="indexing-progress-text"></div>
+ <div id="progress-fill"></div><div id="progress-text"></div><div id="progress-log"></div>
+ <div id="indexing-progress-title"></div><div id="indexing-spinner"></div>
+ </div>
+ <div id="loading"></div><div id="error"></div><main id="details-content"></main>
+ <div id="total-tokens"></div><div id="prompt-tokens"></div><div id="completion-tokens"></div>
+ <div id="llm-calls"></div><div id="avg-response-time"></div><div id="model-used"></div>
+ <div id="research-query"></div><div id="research-mode"></div><div id="research-date"></div>
+ <div id="research-strategy"></div><div id="total-cost"></div><div id="phase-breakdown"></div>
+ <div id="search-engine-breakdown"></div><div id="search-engine-performance"></div><div id="search-timeline"></div>
+ <div id="token-metrics-section"></div><div id="search-metrics-section"></div><div id="token-usage-top-chart"></div>
+ <canvas id="timeline-chart"></canvas><canvas id="search-chart"></canvas>
+ <div id="source-distribution-section"><div class="ldr-card-content"><canvas id="source-type-chart"></canvas></div></div>
+ <div id="link-analytics-section"></div><div id="total-links"></div><div id="unique-domains"></div>
+ <label>Academic</label><span id="academic-sources"></span><label>News</label><span id="news-sources"></span>
+ <div id="domain-list"></div><div id="resource-sample"></div>
+ <section id="context-overflow-section"><div id="co-total-tokens"></div><div id="co-context-limit"></div>
+ <div id="co-max-tokens"></div><div id="co-truncation-status"></div><div id="co-phase-breakdown"></div>
+ <table><tbody id="co-requests-table"></tbody></table><div id="co-performance-warning"></div>
+ </section>
+ <div class="ldr-collapsible-log-panel"><div id="log-panel-toggle"><i class="ldr-toggle-icon"></i>
+ <span class="ldr-log-indicator"></span></div><div id="log-panel-content" class="collapsed">
+ <div id="console-log-container"></div><button id="log-download-button"></button>
+ </div></div>
+ <button id="save-to-collection-btn"></button><div id="saveToCollectionModal"></div>
+ <div id="collection-list-loading"></div><div id="collection-list"><div id="collection-items"></div></div>
+ <div id="collection-error"></div><div id="collection-success"></div>
+ <button id="index-collection-btn"></button><button id="reindex-collection-btn"></button>
+ <button id="delete-collection-btn"></button><button id="cancel-indexing-btn"></button>
+ <input id="collection-is-public" type="checkbox"><input id="collection-agent-enabled" type="checkbox">
+ <h1 id="collection-name"></h1><p id="collection-description"></p><div id="collection-rebuild-notice"></div>
+ <span id="stat-total-docs"></span><span id="stat-indexed-docs"></span>
+ <span id="stat-unindexed-docs"></span><span id="stat-total-chunks"></span>
+ <div id="collection-embedding-info"></div><div id="documents-list"></div><div id="no-documents-message"></div>
+ <section id="notes-section"><div id="notes-list"></div></section><div id="collection-search-section"></div>
+ <div><textarea id="query">Existing research question</textarea>
+ <div class="ldr-search-hints"><div class="ldr-hint-row"></div></div></div>
+ <div id="deleteConfirmModal"><h2 id="deleteModalTitle"></h2><p id="deleteModalMessage"></p>
+ <div id="deleteModalDetails"><ul id="deleteDetailsList"></ul></div>
+ <div id="deleteModalWarning"><span id="deleteWarningText"></span></div>
+ <button id="deleteConfirmBtn"><span id="deleteConfirmBtnText"></span></button>
+ </div>`;
+
+const CONSUMERS = {
+ history: ['components/history.js', ['apiUtils', 'fetchChatSessions', 'handleDeleteItem', 'handleClearHistory']],
+ details: ['components/details.js', ['loadLinkAnalytics', 'loadResearchMetrics', 'loadContextOverflowData']],
+ 'history-search': ['components/history_search.js', ['loadIndexingStatus', 'triggerIndexing', 'startPolling', 'checkAndResumeIndexing']],
+ logs: ['components/logpanel.js', ['downloadLogs']],
+ save: ['components/save_to_collection.js', ['loadCollections', 'saveToCollection']],
+ collection: ['collection_details.js', []],
+ pdf: ['pdf_upload_handler.js', []],
+ confirmation: ['deletion/confirmation_modal.js', []],
+};
+
+export function createRuntime(component, override = null) {
+ if (!Object.hasOwn(CONSUMERS, component)) throw new Error('Unknown consumer fixture');
+ const page = component === 'details' ? `/details/${RESEARCH_ID}`
+ : component === 'history' || component === 'history-search' ? '/history/'
+ : component === 'collection' ? `/library/collections/${COLLECTION_ID}`
+ : component === 'pdf' ? '/' : `/results/${RESEARCH_ID}`;
+ const original = new URL(`${page}?tab=retained#logs`, 'https://app.test');
+ let current = original;
+ const navigations = [];
+ const location = {
+ get href() { return current.href; },
+ set href(value) { navigations.push(value); current = new URL(value, current); },
+ get origin() { return current.origin; },
+ get pathname() { return current.pathname; },
+ get search() { return current.search; },
+ get hash() { return current.hash; },
+ };
+ // eslint-disable-next-line no-unsanitized/property -- Repository-owned fixture with a fixed non-secret authentication fingerprint.
+ document.head.innerHTML = `<meta name="csrf-token" content="${CSRF_TOKEN}"><meta name="auth-context" content="${AUTH_CONTEXT}">`;
+ // eslint-disable-next-line no-unsanitized/property -- Entire markup is the repository-owned constant above.
+ document.body.innerHTML = FIXTURE;
+ const documentListeners = [];
+ const windowListeners = [];
+ const bodyListeners = [];
+ const addBodyListener = document.body.addEventListener.bind(document.body);
+ const bodyListenerSpy = vi.spyOn(document.body, 'addEventListener').mockImplementation((type, listener, options) => {
+ bodyListeners.push([type, listener, options]);
+ addBodyListener(type, listener, options);
+ });
+ let readyState = 'loading';
+ const fixtureDocument = new Proxy(document, {
+ get(target, key) {
+ if (key === 'readyState') return readyState;
+ if (key === 'addEventListener') return (type, listener, options) => {
+ documentListeners.push([type, listener, options]);
+ if (type !== 'DOMContentLoaded') target.addEventListener(type, listener, options);
+ };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ let nextTimer = 1;
+ const timeouts = new Map();
+ const intervals = new Map();
+ const anchorClicks = [];
+ const anchorClick = vi.spyOn(window.HTMLAnchorElement.prototype, 'click').mockImplementation(function() {
+ anchorClicks.push({ href: this.getAttribute('href'), download: this.download, attached: document.body.contains(this) });
+ });
+ class FixtureURL extends URL {}
+ FixtureURL.createObjectURL = vi.fn(() => 'blob:unexpected-area3-buffer');
+ FixtureURL.revokeObjectURL = vi.fn();
+ const modalInstance = {
+ show: vi.fn(),
+ hide: vi.fn(() => document.getElementById('deleteConfirmModal').dispatchEvent(new Event('hidden.bs.modal'))),
+ };
+ function Modal() { return modalInstance; }
+ Modal.getInstance = () => modalInstance;
+ Modal.getOrCreateInstance = () => modalInstance;
+ const action = vi.fn(async () => 'action completed');
+ const sandbox = {
+ document: fixtureDocument, location, URL: FixtureURL, URLSearchParams,
+ Headers: globalThis.Headers, Blob, File: window.File, FormData: window.FormData,
+ AbortController, DOMException: globalThis.DOMException, Element: window.Element, Event: window.Event,
+ localStorage: window.localStorage, sessionStorage: window.sessionStorage,
+ setTimeout: (callback, delay) => { const id = nextTimer++; timeouts.set(id, { callback, delay }); return id; },
+ clearTimeout: id => timeouts.delete(id),
+ setInterval: (callback, delay) => { const id = nextTimer++; intervals.set(id, { callback, delay }); return id; },
+ clearInterval: id => intervals.delete(id),
+ requestAnimationFrame: vi.fn(),
+ addEventListener: (type, listener) => windowListeners.push([type, listener]),
+ getComputedStyle: window.getComputedStyle.bind(window),
+ SafeLogger: { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), info: vi.fn() },
+ formatting: {
+ formatNumber: value => Number(value).toLocaleString('en-US'),
+ formatCurrency: value => String(value), generateChartColors: () => ({ background: [], border: [] }),
+ },
+ ui: { showMessage: vi.fn(), showAlert: vi.fn() },
+ bootstrap: { Modal }, alert: vi.fn(), confirm: vi.fn(() => true),
+ COLLECTION_ID,
+ RESEARCH_STATUS: { IN_PROGRESS: 'in_progress', COMPLETED: 'completed', FAILED: 'failed', ERROR: 'error', CANCELLED: 'cancelled', SUSPENDED: 'suspended', QUEUED: 'queued', PENDING: 'pending' },
+ RESEARCH_TERMINAL_STATES: new Set(['completed', 'failed', 'error', 'cancelled', 'suspended']),
+ formatBytes: value => `${value} bytes`,
+ };
+ sandbox.window = sandbox;
+ sandbox.globalThis = sandbox;
+ const baseRoute = (input, options = {}) => {
+ const url = new URL(input, original);
+ const path = url.pathname;
+ if (path === '/history/api') return response({ items: [{ id: RESEARCH_ID, title: 'Synthetic research', query: 'Synthetic query', mode: 'quick', status: 'completed', created_at: '2026-10-01T12:00:00Z' }] });
+ if (path === '/api/chat/sessions' && !options.method) return response({ success: true, sessions: [{ id: CHAT_ID, title: 'Synthetic chat', status: 'active', created_at: '2026-10-01T12:00:00Z' }] });
+ if (path.startsWith('/api/chat/sessions/') || path.startsWith('/api/delete/') || path === '/api/clear_history') return response({ status: 'success', success: true });
+ if (path.startsWith('/history/details/')) return response({ query: 'Synthetic query', mode: 'quick', strategy: 'source-based' });
+ if (path.endsWith('/log_count/' + RESEARCH_ID)) return response({ status: 'success', total_logs: 0 });
+ if (path.endsWith('/logs/export')) return response();
+ if (path.endsWith('/logs')) return response([]);
+ if (path.startsWith('/metrics/api/metrics/research/')) return path.endsWith('/links')
+ ? response({ status: 'success', data: { total_links: 0, unique_domains: 0, domain_categories: {}, domains: [], resources: [] } })
+ : response({ status: 'success', metrics: {} });
+ if (path.endsWith('/context-overflow')) return response({ status: 'success', data: { overview: { total_tokens: 0, context_limit: 4096, max_tokens_used: 0, truncation_occurred: false }, phase_stats: {}, requests: [] } });
+ if (path === '/library/api/research-history/collection') return response({ success: true, collection_id: COLLECTION_ID, indexed_documents: 0, total_documents: 2 });
+ if (path.endsWith('/convert-all')) return response({ success: true, converted: 2 });
+ if (path.endsWith('/index/status')) return response({ status: 'idle' });
+ if (path.endsWith('/index/start')) return response({ success: true, task_id: 'synthetic-index-task' });
+ if (path.endsWith('/search')) return response({ success: true, results: [] });
+ if (path === '/library/api/collections') return response({ success: true, collections: [{ id: COLLECTION_ID, name: 'Synthetic collection', description: 'Synthetic fixture' }] });
+ if (path.endsWith('/add-to-collection')) return response({ success: true, documents_added: 2 });
+ if (path.endsWith('/documents')) return response({ success: true, collection: { name: 'Synthetic collection', is_public: false, agent_enabled: true }, documents: [], notes: [] });
+ if (path.startsWith('/library/api/collection/') || path.startsWith('/library/api/document/')) return response({ success: true, document_deleted: true });
+ if (path === '/api/config/limits') return response({ max_file_size: 1048576, max_files: 3 });
+ if (path === '/api/upload/pdf') return response({ status: 'success', processed_files: 1, extracted_texts: [{ filename: 'synthetic.pdf', text: 'Synthetic extracted text', size: 4, pages: 1 }], combined_text: 'Synthetic extracted text', errors: [] });
+ if (path === '/settings/api/research_library.confirm_deletions') return response({ value: true });
+ throw new Error(`Unexpected fixture request: ${input}`);
+ };
+ const fetchMock = vi.fn((input, options) => {
+ const controlled = override?.(input, options || {}, sandbox);
+ return controlled === undefined ? baseRoute(input, options) : controlled;
+ });
+ sandbox.fetch = fetchMock;
+ const context = vm.createContext(sandbox);
+ const run = (path, probes = []) => {
+ let source = readFileSync(resolve(JS_ROOT, path), 'utf8');
+ if (probes.length) {
+ const close = source.lastIndexOf('\n})();');
+ if (close < 0 || source.slice(close).trim() !== '})();') throw new Error('Expected complete consumer IIFE');
+ source = `${source.slice(0, close)}\nwindow.__historyLibraryProbe = { ${probes.join(', ')} };${source.slice(close)}`;
+ }
+ vm.runInContext(source, context, { filename: path, timeout: 1000 });
+ };
+ run('config/urls.js');
+ run('config/constants.js');
+ run('services/api.js');
+ run('security/url-validator.js');
+ run('security/safe-fetch.js');
+ run('utils/log-helpers.js');
+ run('components/context-overflow-shared.js');
+ run(...CONSUMERS[component]);
+ const probe = sandbox.__historyLibraryProbe;
+ return {
+ sandbox, probe, action, fetchMock, original, navigations, anchorClicks, modalInstance, timeouts, intervals,
+ async boot() {
+ readyState = 'interactive';
+ for (const [type, listener] of [...documentListeners]) if (type === 'DOMContentLoaded') listener(new Event(type));
+ await settle();
+ },
+ guardState() {
+ return vm.runInContext('({ recovery: typeof window.api.fetchWithCsrfRecovery, classify: typeof window.api.shouldRedirectToLoginOn401, redirect: typeof window.api.redirectToLogin, auth: typeof window.safeFetchWithAuth })', context, { timeout: 1000 });
+ },
+ dropHighLevel(method) {
+ const operations = {
+ getResearchHistory: 'delete window.api.getResearchHistory; typeof window.api.getResearchHistory;',
+ deleteResearch: 'delete window.api.deleteResearch; typeof window.api.deleteResearch;',
+ clearResearchHistory: 'delete window.api.clearResearchHistory; typeof window.api.clearResearchHistory;',
+ };
+ if (!Object.hasOwn(operations, method)) throw new Error('Unknown high-level API fixture');
+ return vm.runInContext(operations[method], context, { timeout: 1000 });
+ },
+ pollOnce() {
+ const callbacks = [...intervals.values()];
+ if (callbacks.length !== 1 || callbacks[0].delay !== 2000) throw new Error('Expected one actual two-second indexing poll');
+ return callbacks[0].callback();
+ },
+ trigger(kind) {
+ switch (kind) {
+ case 'history-list-fallback': return probe.apiUtils.getResearchHistory();
+ case 'history-delete-fallback': return probe.apiUtils.deleteResearch(RESEARCH_ID);
+ case 'history-clear-fallback': return probe.handleClearHistory();
+ case 'chat-list': return probe.fetchChatSessions({ all: true, throwOnError: true });
+ case 'chat-delete': return probe.handleDeleteItem(CHAT_ID, true);
+ case 'chat-clear': return probe.handleClearHistory();
+ case 'links': return probe.loadLinkAnalytics();
+ case 'metrics': case 'timeline': case 'search-metrics': return probe.loadResearchMetrics();
+ case 'overflow': return probe.loadContextOverflowData();
+ case 'index-count': return probe.loadIndexingStatus();
+ case 'convert': case 'index-start': return probe.triggerIndexing();
+ case 'index-poll': probe.startPolling(); return this.pollOnce();
+ case 'index-resume': return probe.checkAndResumeIndexing();
+ case 'history-semantic': return sandbox.HistorySearch.semanticSearchHistory('Synthetic query');
+ case 'logs': return sandbox.logPanel.loadLogs(RESEARCH_ID);
+ case 'logs-export': return probe.downloadLogs();
+ case 'collections': return probe.loadCollections();
+ case 'save': return probe.saveToCollection(COLLECTION_ID, 'Synthetic collection');
+ case 'collection-index': return sandbox.indexCollection(false);
+ case 'document-remove': return sandbox.removeDocumentFromCollection('synthetic-document');
+ case 'document-delete': return sandbox.deleteDocumentCompletely('synthetic-document');
+ case 'pdf-limits': return sandbox.pdfUploadHandler.fetchUploadLimits();
+ case 'pdf-upload': return sandbox.pdfUploadHandler.uploadAndExtractPDFs([new window.File(['%PDF'], 'synthetic.pdf', { type: 'application/pdf' })]);
+ case 'confirmation': return sandbox.DeleteConfirmation.confirmAndRun({ action: 'deleteDocument' }, action);
+ default: throw new Error('Unknown consumer callback fixture');
+ }
+ },
+ dispose() {
+ for (const [type, listener, options] of documentListeners) if (type !== 'DOMContentLoaded') document.removeEventListener(type, listener, options);
+ for (const [type, listener, options] of bodyListeners) document.body.removeEventListener(type, listener, options);
+ for (const [type, listener] of windowListeners) if (type === 'beforeunload') listener(new Event(type));
+ timeouts.clear(); intervals.clear(); anchorClick.mockRestore(); bodyListenerSpy.mockRestore();
+ document.head.replaceChildren(); document.body.replaceChildren();
+ },
+ };
+}
diff --git a/tests/js/helpers/safe-fetch-with-auth-to-fetch.js b/tests/js/helpers/safe-fetch-with-auth-to-fetch.js
new file mode 100644
index 0000000000..d1a1ee4f81
--- /dev/null
+++ b/tests/js/helpers/safe-fetch-with-auth-to-fetch.js
@@ -0,0 +1,11 @@
+/**
+ * Route safeFetchWithAuth straight to the test's `fetch` double.
+ *
+ * tests/js/setup.js defines safeFetchWithAuth as a passthrough to
+ * `globalThis.safeFetch`, which suits suites that mock safeFetch. The suites
+ * that import this file mock `fetch` instead (their callers used bare fetch
+ * before switching to safeFetchWithAuth), so this override keeps their doubles
+ * in the path. Real 401/CSRF wrapper behavior is covered separately by
+ * history-library-fetch-auth-integration.test.js.
+ */
+globalThis.safeFetchWithAuth = (...args) => globalThis.fetch(...args);
diff --git a/tests/js/pdf-upload-handler-migration-contract.test.js b/tests/js/pdf-upload-handler-migration-contract.test.js
index 90f44d0a32..8736123090 100644
--- a/tests/js/pdf-upload-handler-migration-contract.test.js
+++ b/tests/js/pdf-upload-handler-migration-contract.test.js
@@ -1,3 +1,5 @@
+import './helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Browser contract for the unchanged research-page PDF consumer after the
* FastAPI migration. The collection uploader is a separate component; this
diff --git a/tests/js/security/details-render-xss.test.js b/tests/js/security/details-render-xss.test.js
index d15efdbe78..03017338ac 100644
--- a/tests/js/security/details-render-xss.test.js
+++ b/tests/js/security/details-render-xss.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Exercise real research-details rendering with API payloads, including
* numeric strings in HTML sinks and resource links when the sanitizer is
diff --git a/tests/js/security/library-search-xss.test.js b/tests/js/security/library-search-xss.test.js
index 0bff2f97e2..90745c8164 100644
--- a/tests/js/security/library-search-xss.test.js
+++ b/tests/js/security/library-search-xss.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* XSS regression coverage for the library/search/history render surfaces.
*
diff --git a/tests/js/security/logpanel-events-xss.test.js b/tests/js/security/logpanel-events-xss.test.js
index 88bb3036ed..e29d241411 100644
--- a/tests/js/security/logpanel-events-xss.test.js
+++ b/tests/js/security/logpanel-events-xss.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Security tests for components/logpanel.js — research-log -> DOM surface.
*
diff --git a/tests/js/security/url-source-flows-xss.test.js b/tests/js/security/url-source-flows-xss.test.js
index 9a1424298e..6ba1e9d95f 100644
--- a/tests/js/security/url-source-flows-xss.test.js
+++ b/tests/js/security/url-source-flows-xss.test.js
@@ -1,3 +1,5 @@
+import '../helpers/safe-fetch-with-auth-to-fetch.js';
+
/**
* Defensive output-encoding coverage for browser URL/storage sources.
*
diff --git a/tests/web/test_csrf_recovery.py b/tests/web/test_csrf_recovery.py
index d2c400293d..025bdb9619 100644
--- a/tests/web/test_csrf_recovery.py
+++ b/tests/web/test_csrf_recovery.py
@@ -41,6 +41,13 @@ def _client():
calls.append("mutate")
return {"ok": True}
+ @app.post("/conflict")
+ def conflict():
+ calls.append("conflict")
+ return JSONResponse(
+ {"success": False, "error": "Already running"}, status_code=409
+ )
+
@app.post("/forbidden")
def forbidden():
calls.append("forbidden")
@@ -100,6 +107,7 @@ def test_changed_login_cannot_receive_a_replayed_write_even_with_its_csrf_token(
},
)
assert response.status_code == 409
+ assert response.headers.get("X-LDR-Auth-Changed") == "1"
assert "X-LDR-CSRF-Rejected" not in response.headers
assert calls == []
accepted = client.post(
@@ -127,10 +135,38 @@ def test_replaced_login_is_rejected_even_before_it_has_a_csrf_token():
)
assert response.status_code == 409
assert "sign-in changed" in response.json()["error"]
+ assert response.headers.get("X-LDR-Auth-Changed") == "1"
assert "X-LDR-CSRF-Rejected" not in response.headers
assert calls == []
+def test_only_the_replaced_login_409_carries_the_auth_changed_marker():
+ """Clients key on the header to tell a login change from a handler 409."""
+ client, calls = _client()
+ current = client.get("/seed/owner-a").json()
+ own = client.post(
+ "/conflict",
+ headers={
+ "X-CSRFToken": current["csrf_token"],
+ "X-LDR-Auth-Context": current["auth_context"],
+ },
+ )
+ assert own.status_code == 409
+ assert "X-LDR-Auth-Changed" not in own.headers
+ assert calls == ["conflict"]
+ client.get("/seed/owner-b")
+ replaced = client.post(
+ "/conflict",
+ headers={
+ "X-CSRFToken": current["csrf_token"],
+ "X-LDR-Auth-Context": current["auth_context"],
+ },
+ )
+ assert replaced.status_code == 409
+ assert replaced.headers.get("X-LDR-Auth-Changed") == "1"
+ assert calls == ["conflict"]
+
+
@pytest.mark.parametrize("anonymous_token", [False, True])
def test_bound_write_requires_login_after_the_cookie_is_cleared(
anonymous_token,
@@ -145,6 +181,7 @@ def test_bound_write_requires_login_after_the_cookie_is_cleared(
)
assert response.status_code == 401
assert "X-LDR-CSRF-Rejected" not in response.headers
+ assert "X-LDR-Auth-Changed" not in response.headers
assert calls == []
@@ -155,6 +192,7 @@ def test_recovery_fetch_rejects_anonymous_or_replaced_login_without_minting_toke
)
assert anonymous.status_code == 401
assert anonymous.headers["Cache-Control"] == "no-store"
+ assert "X-LDR-Auth-Changed" not in anonymous.headers
assert "csrf_token" not in anonymous.json()
old = client.get("/seed/owner-a").json()
current = client.get("/seed/owner-b").json()
@@ -162,6 +200,8 @@ def test_recovery_fetch_rejects_anonymous_or_replaced_login_without_minting_toke
"/auth/csrf-token", headers={"X-LDR-Auth-Context": old["auth_context"]}
)
assert changed.status_code == 409
+ assert changed.headers.get("X-LDR-Auth-Changed") == "1"
+ assert changed.headers["Cache-Control"] == "no-store"
assert "csrf_token" not in changed.json()
accepted = client.get(
"/auth/csrf-token",