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.

refactor(csrf): complete CSRF token deduplication across all JS files (#2453)

LearningCircuitbcb2afc91653
diff --git a/.github/scripts/file-whitelist-check.sh b/.github/scripts/file-whitelist-check.sh
index c9f166a3b4..aff1e84e3e 100755
--- a/.github/scripts/file-whitelist-check.sh
+++ b/.github/scripts/file-whitelist-check.sh
@@ -142,6 +142,7 @@ SAFE_FILENAME_PATTERNS=(
".*session_passwords\.py$"
".*change_password\.html$"
"tests/ui_tests/.*password.*\.js$"
+"tests/infrastructure_tests/.*token.*\.js$"
)
# Check if filename looks suspicious
diff --git a/src/local_deep_research/web/static/js/collection_create.js b/src/local_deep_research/web/static/js/collection_create.js
index 3085296fa7..2d83c9c0ee 100644
--- a/src/local_deep_research/web/static/js/collection_create.js
+++ b/src/local_deep_research/web/static/js/collection_create.js
@@ -70,7 +70,7 @@ async function handleCreateCollection(e) {
createBtn.disabled = true;
createBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Creating Collection...';
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Prepare JSON data
const jsonData = {
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 9983a860c9..04e499cdf2 100644
--- a/src/local_deep_research/web/static/js/collection_details.js
+++ b/src/local_deep_research/web/static/js/collection_details.js
@@ -259,7 +259,7 @@ async function indexCollection(forceReindex) {
}
try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Start background indexing
const response = await safeFetch(`/library/api/collections/${COLLECTION_ID}/index/start`, {
@@ -417,7 +417,7 @@ async function cancelIndexing() {
}
try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await safeFetch(`/library/api/collections/${COLLECTION_ID}/index/cancel`, {
method: 'POST',
@@ -460,7 +460,7 @@ async function deleteCollection() {
if (!confirm(`Are you sure you want to delete "${collectionData.name}"? This action cannot be undone.`)) return;
try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await safeFetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {
method: 'DELETE',
headers: {
@@ -535,7 +535,7 @@ async function removeDocumentFromCollection(documentId) {
}
try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await fetch(`/library/api/collection/${COLLECTION_ID}/document/${documentId}`, {
method: 'DELETE',
headers: {
@@ -576,7 +576,7 @@ async function deleteDocumentCompletely(documentId) {
}
try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await fetch(`/library/api/document/${documentId}`, {
method: 'DELETE',
headers: {
diff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.js
index 5ae99efd10..004447cb75 100644
--- a/src/local_deep_research/web/static/js/collection_upload.js
+++ b/src/local_deep_research/web/static/js/collection_upload.js
@@ -304,7 +304,7 @@ async function handleUploadFiles(e) {
const pdfStorageMode = document.querySelector('input[name="pdf_storage"]:checked')?.value || 'none';
const submitBtn = e.target.querySelector('button[type="submit"]');
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const uploadUrl = URLBuilder.build(URLS.LIBRARY_API.COLLECTION_UPLOAD, COLLECTION_ID);
// Decide: batch upload for large sets, single upload for small sets
diff --git a/src/local_deep_research/web/static/js/collections_manager.js b/src/local_deep_research/web/static/js/collections_manager.js
index 74246d041b..b460cfeb15 100644
--- a/src/local_deep_research/web/static/js/collections_manager.js
+++ b/src/local_deep_research/web/static/js/collections_manager.js
@@ -193,7 +193,7 @@ async function handleCreateCollection(event) {
}
try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await safeFetch(URLS.LIBRARY_API.COLLECTIONS, {
method: 'POST',
headers: {
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 ebc1e0b266..f7e346e1f5 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -435,13 +435,6 @@
// Subscription creation removed - handled by dedicated form page
- /**
- * Get CSRF token
- */
- function getCSRFToken() {
- return document.querySelector('meta[name="csrf-token"]')?.content || '';
- }
-
// Subscription status update removed - handled by dedicated form page
/**
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index c631c23027..92e1168d78 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -2064,7 +2064,7 @@
method: 'PUT',
headers: {
'Content-Type': 'application/json',
- 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
+ 'X-CSRFToken': window.api ? window.api.getCsrfToken() : ''
},
body: JSON.stringify({ value: modelValue })
})
@@ -2102,7 +2102,7 @@
method: 'PUT',
headers: {
'Content-Type': 'application/json',
- 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
+ 'X-CSRFToken': window.api ? window.api.getCsrfToken() : ''
},
body: JSON.stringify({ value: engineValue })
})
@@ -2134,7 +2134,7 @@
method: 'POST',
headers: {
'Content-Type': 'application/json',
- 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
+ 'X-CSRFToken': window.api ? window.api.getCsrfToken() : ''
},
body: JSON.stringify({ engine_id: engineId })
})
@@ -2199,7 +2199,7 @@
method: 'PUT',
headers: {
'Content-Type': 'application/json',
- 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
+ 'X-CSRFToken': window.api ? window.api.getCsrfToken() : ''
},
body: JSON.stringify({ value: providerValue.toLowerCase() })
})
@@ -2237,7 +2237,7 @@
method: 'PUT',
headers: {
'Content-Type': 'application/json',
- 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
+ 'X-CSRFToken': window.api ? window.api.getCsrfToken() : ''
},
body: JSON.stringify({ value: value })
})
@@ -2358,8 +2358,8 @@
SafeLogger.log('Submitting research with data:', formData);
- // Get CSRF token from meta tag
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
+ // Get CSRF token
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Submit the form data to the backend
fetch(URLS.API.START_RESEARCH, {
diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.js
index 94ce5e1344..19e808b31f 100644
--- a/src/local_deep_research/web/static/js/components/results.js
+++ b/src/local_deep_research/web/static/js/components/results.js
@@ -789,7 +789,7 @@
SafeLogger.log(`Exporting to ${formatName}...`);
// Get CSRF token
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Call API to export the report
const response = await fetch(`/api/v1/research/${researchId}/export/${format}`, {
@@ -846,9 +846,8 @@
pdfBtn.disabled = true;
pdfBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
- // Get CSRF token from meta tag or cookie
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ||
- document.cookie.split('; ').find(row => row.startsWith('csrf_token='))?.split('=')[1];
+ // Get CSRF token
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Call the backend API to generate PDF using WeasyPrint
fetch(`/api/v1/research/${researchId}/export/pdf`, {
@@ -980,8 +979,8 @@
try {
SafeLogger.log('Attempting to save rating:', rating);
- // Get CSRF token from meta tag
- const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ // Get CSRF token
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
SafeLogger.log('CSRF token:', csrfToken ? 'found' : 'missing');
const headers = {
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index d4dcebd77e..7cfc8a468d 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -3107,7 +3107,7 @@
* Get CSRF token from meta tag
*/
function getCsrfToken() {
- return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
+ return window.api ? window.api.getCsrfToken() : '';
}
/**
@@ -4581,14 +4581,6 @@
}, 5000);
}
- /**
- * Get CSRF token from meta tag
- */
- function getCsrfToken() {
- const token = document.querySelector('meta[name="csrf-token"]');
- return token ? token.getAttribute('content') : '';
- }
-
/**
* Create a refresh button for a dropdown input
* @param {string} inputId - The ID of the input to create a refresh button for
diff --git a/src/local_deep_research/web/static/js/components/settings_sync.js b/src/local_deep_research/web/static/js/components/settings_sync.js
index d401376c78..56fc47f1e9 100644
--- a/src/local_deep_research/web/static/js/components/settings_sync.js
+++ b/src/local_deep_research/web/static/js/components/settings_sync.js
@@ -4,7 +4,7 @@ function saveMenuSettings(settingKey, settingValue) {
SafeLogger.log('Saving setting:', settingKey, '=', settingValue);
// Get CSRF token
- const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Use the individual settings API endpoint that uses the settings manager
fetch(`/settings/api/${settingKey}`, {
diff --git a/src/local_deep_research/web/static/js/components/subscription-manager.js b/src/local_deep_research/web/static/js/components/subscription-manager.js
index cc64856605..c5bad644c1 100644
--- a/src/local_deep_research/web/static/js/components/subscription-manager.js
+++ b/src/local_deep_research/web/static/js/components/subscription-manager.js
@@ -401,7 +401,7 @@ class SubscriptionManager {
}
getCSRFToken() {
- return document.querySelector('meta[name="csrf-token"]')?.content || '';
+ return window.api ? window.api.getCsrfToken() : '';
}
showLoading() {
diff --git a/src/local_deep_research/web/static/js/deletion/delete_manager.js b/src/local_deep_research/web/static/js/deletion/delete_manager.js
index 41ab692ade..23347becf0 100644
--- a/src/local_deep_research/web/static/js/deletion/delete_manager.js
+++ b/src/local_deep_research/web/static/js/deletion/delete_manager.js
@@ -33,8 +33,7 @@ const DELETE_API = {
* Get CSRF token from meta tag
*/
function getCsrfToken() {
- const meta = document.querySelector('meta[name="csrf-token"]');
- return meta ? meta.getAttribute('content') : '';
+ return window.api ? window.api.getCsrfToken() : '';
}
/**
diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.js
index cc57144fbf..db428ea473 100644
--- a/src/local_deep_research/web/static/js/embedding_settings.js
+++ b/src/local_deep_research/web/static/js/embedding_settings.js
@@ -252,7 +252,7 @@ async function saveSetting(key, value, displayName, oldValue) {
}
try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await safeFetch('/settings/api/' + key, {
method: 'PUT',
headers: {
@@ -735,7 +735,7 @@ async function handleConfigSubmit(event) {
SafeLogger.log('✅ Form validation passed');
try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
SafeLogger.log('🔐 CSRF Token:', csrfToken ? 'Found' : 'Not found');
const response = await safeFetch('/library/api/rag/configure', {
@@ -816,7 +816,7 @@ async function testConfiguration() {
testResult.innerHTML = '<div class="ldr-alert ldr-alert-info"><i class="fas fa-spinner fa-spin"></i> Testing embedding model... For local providers this may take a moment while the model is loaded into memory.</div>';
try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Send test embedding request with selected configuration
const response = await safeFetch('/library/api/rag/test-embedding', {
@@ -994,7 +994,7 @@ async function saveOllamaUrl() {
const ollamaUrl = document.getElementById('ollama-url').value.trim();
try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await safeFetch('/settings/api/embeddings.ollama.url', {
method: 'PUT',
diff --git a/src/local_deep_research/web/static/js/followup.js b/src/local_deep_research/web/static/js/followup.js
index 23fa3efc2f..e36ec80b37 100644
--- a/src/local_deep_research/web/static/js/followup.js
+++ b/src/local_deep_research/web/static/js/followup.js
@@ -233,22 +233,8 @@ class FollowUpResearch {
*/
async loadParentContext() {
try {
- // Get CSRF token from meta tag or cookie
- let csrfToken = '';
- const csrfMeta = document.querySelector('meta[name="csrf-token"]');
- if (csrfMeta) {
- csrfToken = csrfMeta.content;
- } else {
- // Try to get from cookie
- const cookies = document.cookie.split(';');
- for (let cookie of cookies) {
- const [name, value] = cookie.trim().split('=');
- if (name === 'csrf_token') {
- csrfToken = decodeURIComponent(value);
- break;
- }
- }
- }
+ // Get CSRF token
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await fetch('/api/followup/prepare', {
method: 'POST',
@@ -296,22 +282,8 @@ class FollowUpResearch {
});
try {
- // Get CSRF token from meta tag or cookie
- let csrfToken = '';
- const csrfMeta = document.querySelector('meta[name="csrf-token"]');
- if (csrfMeta) {
- csrfToken = csrfMeta.content;
- } else {
- // Try to get from cookie
- const cookies = document.cookie.split(';');
- for (let cookie of cookies) {
- const [name, value] = cookie.trim().split('=');
- if (name === 'csrf_token') {
- csrfToken = decodeURIComponent(value);
- break;
- }
- }
- }
+ // Get CSRF token
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Start follow-up research
const response = await fetch('/api/followup/start', {
diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.js
index 877a8ad81b..af5faae4ac 100644
--- a/src/local_deep_research/web/static/js/pages/news.js
+++ b/src/local_deep_research/web/static/js/pages/news.js
@@ -2015,17 +2015,7 @@ function showAlert(message, type = 'info') {
}
function getCSRFToken() {
- // Try to get from meta tag first
- const csrfMeta = document.querySelector('meta[name="csrf-token"]');
- if (csrfMeta) return csrfMeta.content;
-
- // Try to get from cookie
- const cookies = document.cookie.split(';');
- for (let cookie of cookies) {
- const [name, value] = cookie.trim().split('=');
- if (name === 'csrf_token') return decodeURIComponent(value);
- }
- return '';
+ return window.api ? window.api.getCsrfToken() : '';
}
// Refresh feed
diff --git a/src/local_deep_research/web/static/js/pages/subscriptions.js b/src/local_deep_research/web/static/js/pages/subscriptions.js
index 1e72f78772..9f4504da15 100644
--- a/src/local_deep_research/web/static/js/pages/subscriptions.js
+++ b/src/local_deep_research/web/static/js/pages/subscriptions.js
@@ -651,7 +651,7 @@ function getCurrentUserId() {
}
function getCSRFToken() {
- return document.querySelector('meta[name="csrf-token"]')?.content || '';
+ return window.api ? window.api.getCsrfToken() : '';
}
function getFolderName(folderId) {
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 bfbee68079..34cad6a3ca 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
@@ -288,7 +288,7 @@ class PDFUploadHandler {
});
// Get CSRF token
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
const headers = {};
if (csrfToken) {
diff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.js
index 90caf93fea..dff98bb669 100644
--- a/src/local_deep_research/web/static/js/research_form.js
+++ b/src/local_deep_research/web/static/js/research_form.js
@@ -92,7 +92,7 @@ function saveResearchSettings() {
const questions = questionsInput.value;
// Get CSRF token
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
if (!csrfToken) {
SafeLogger.warn('CSRF token not found, skipping settings save');
@@ -327,7 +327,7 @@ function displayWarnings(warnings) {
function dismissWarning(dismissKey) {
// Get CSRF token
- const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Update dismissal setting
fetch(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {
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 59f6f51a5c..1450e00a18 100644
--- a/src/local_deep_research/web/static/js/services/api.js
+++ b/src/local_deep_research/web/static/js/services/api.js
@@ -152,12 +152,8 @@ async function terminateResearch(researchId) {
* @returns {Promise<Object>} The deletion response
*/
async function deleteResearch(researchId) {
- const csrfToken = getCsrfToken();
return fetchWithErrorHandling(URLBuilder.deleteResearch(researchId), {
- method: 'DELETE',
- headers: {
- 'X-CSRFToken': csrfToken
- }
+ method: 'DELETE'
});
}
@@ -261,5 +257,6 @@ window.api = {
saveApiKeysConfig,
saveLlmConfig,
postJSON,
- getApiUrl
+ getApiUrl,
+ getCsrfToken
};
diff --git a/src/local_deep_research/web/static/js/services/help.js b/src/local_deep_research/web/static/js/services/help.js
index 886528991d..b4f2230f16 100644
--- a/src/local_deep_research/web/static/js/services/help.js
+++ b/src/local_deep_research/web/static/js/services/help.js
@@ -60,12 +60,7 @@ const HelpService = (function() {
try {
// Get CSRF token
- const csrfMeta = document.querySelector('meta[name="csrf-token"]');
- const csrfToken = csrfMeta ? csrfMeta.getAttribute('content') : '';
-
- if (!csrfToken) {
- SafeLogger.warn('CSRF token not found, dismissal may fail');
- }
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Save to settings via internal API (relative URL only)
const apiUrl = SETTINGS_API_BASE + encodeURIComponent(settingKey);
@@ -198,8 +193,7 @@ const HelpService = (function() {
const panels = document.querySelectorAll('.ldr-help-panel');
// Get CSRF token
- const csrfMeta = document.querySelector('meta[name="csrf-token"]');
- const csrfToken = csrfMeta ? csrfMeta.getAttribute('content') : '';
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
for (const panel of panels) {
const panelId = panel.getAttribute('data-panel-id');
diff --git a/src/local_deep_research/web/static/js/services/theme.js b/src/local_deep_research/web/static/js/services/theme.js
index ee2d792fed..11c489a5f1 100644
--- a/src/local_deep_research/web/static/js/services/theme.js
+++ b/src/local_deep_research/web/static/js/services/theme.js
@@ -111,7 +111,7 @@
* Save theme to user account via settings API
*/
function saveThemeToServer(theme) {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
if (!csrfToken) {
SafeLogger.warn('CSRF token not found, cannot save theme to server');
return Promise.resolve();
diff --git a/tests/infrastructure_tests/test_csrf_token.test.js b/tests/infrastructure_tests/test_csrf_token.test.js
new file mode 100644
index 0000000000..92e5a004f1
--- /dev/null
+++ b/tests/infrastructure_tests/test_csrf_token.test.js
@@ -0,0 +1,104 @@
+/**
+ * JavaScript tests for CSRF token retrieval
+ * Run with: npm test tests/infrastructure_tests/test_csrf_token.test.js
+ *
+ * Tests the getCsrfToken function exported via window.api and the
+ * delegation pattern used across files.
+ */
+
+// Mock SafeLogger
+global.SafeLogger = {
+ warn: jest.fn(),
+ error: jest.fn(),
+ info: jest.fn(),
+ log: jest.fn(),
+ debug: jest.fn()
+};
+
+// Mock fetch
+global.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({}) }));
+
+// Mock document with a csrf-token meta tag
+global.document = {
+ querySelector: jest.fn()
+};
+
+// Mock window
+global.window = {};
+
+// Mock URLS and URLBuilder (required by api.js)
+global.URLS = { API: {} };
+global.URLBuilder = {};
+
+// Load api.js — this sets window.api
+require('../../src/local_deep_research/web/static/js/services/api.js');
+
+describe('getCsrfToken (via window.api)', () => {
+ beforeEach(() => {
+ jest.resetAllMocks();
+ });
+
+ test('should be exported on window.api', () => {
+ expect(global.window.api).toBeDefined();
+ expect(typeof global.window.api.getCsrfToken).toBe('function');
+ });
+
+ test('should return token content when meta tag exists', () => {
+ global.document.querySelector.mockReturnValue({
+ getAttribute: jest.fn().mockReturnValue('test-csrf-token-123')
+ });
+
+ const token = global.window.api.getCsrfToken();
+ expect(token).toBe('test-csrf-token-123');
+ expect(global.document.querySelector).toHaveBeenCalledWith('meta[name="csrf-token"]');
+ });
+
+ test('should return empty string when meta tag is missing', () => {
+ global.document.querySelector.mockReturnValue(null);
+
+ const token = global.window.api.getCsrfToken();
+ expect(token).toBe('');
+ });
+
+ test('should handle whitespace-only content', () => {
+ global.document.querySelector.mockReturnValue({
+ getAttribute: jest.fn().mockReturnValue(' ')
+ });
+
+ const token = global.window.api.getCsrfToken();
+ expect(token).toBe(' ');
+ });
+});
+
+describe('Delegation pattern', () => {
+ beforeEach(() => {
+ jest.resetAllMocks();
+ });
+
+ test('delegate should return token when window.api is available', () => {
+ // Simulate the delegate pattern used across files
+ global.document.querySelector.mockReturnValue({
+ getAttribute: jest.fn().mockReturnValue('delegated-token')
+ });
+
+ function getCsrfToken() {
+ return window.api ? window.api.getCsrfToken() : '';
+ }
+
+ expect(getCsrfToken()).toBe('delegated-token');
+ });
+
+ test('delegate should return empty string when window.api is unavailable', () => {
+ const savedApi = global.window.api;
+ global.window.api = undefined;
+
+ function getCsrfToken() {
+ return window.api ? window.api.getCsrfToken() : '';
+ }
+
+ expect(getCsrfToken()).toBe('');
+
+ // Restore
+ global.window.api = savedApi;
+ });
+});