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(security): stop subscription API values from becoming markup (#7146)

LearningCircuit12d560cff87f
diff --git a/changelog.d/+subscription-xss-main-port.security.md b/changelog.d/+subscription-xss-main-port.security.md
new file mode 100644
index 0000000000..d9020aa45f
--- /dev/null
+++ b/changelog.d/+subscription-xss-main-port.security.md
@@ -0,0 +1 @@
+Subscription pages no longer turn malformed API values into markup. Refresh intervals, run counts, folder item counts and run durations only reach a subscription card, a folder tab or the history modal as numbers. The shared number formatter only formats a finite number or a string that `Number()` converts to one, and shows 0 for anything else. Alerts on the subscriptions page escape the subscription query, folder names and server error text, so these show as text, never as links or headings. Alert text that contains template-like syntax such as `{{`, `${` or `%>` is no longer partly blanked out. Subscription IDs are percent-encoded in API request paths on the subscriptions and news pages. Links on a subscription card now only navigate: the Edit link no longer carries an inline handler, and the View original research link no longer also opens the card's history. History links that open in a new tab carry `rel="noopener noreferrer"`.
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 0b4a082471..bd0efc1a69 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
@@ -153,6 +153,8 @@ class SubscriptionManager {
const createBtn = tabsContainer.querySelector('#create-folder-btn').parentElement;
this.folders.forEach(folder => {
+ const parsedItemCount = Number.parseInt(folder.item_count, 10);
+ const itemCount = Number.isFinite(parsedItemCount) ? parsedItemCount : 0;
const li = document.createElement('li');
li.className = 'nav-item';
// bearer:disable javascript_lang_dangerous_insert_html
@@ -160,7 +162,7 @@ class SubscriptionManager {
li.innerHTML = `
<button class="nav-link" data-folder="${window.escapeHtml(folder.name)}" type="button">
${window.escapeHtml(folder.icon || '📁')} ${window.escapeHtml(folder.name)}
- <span class="ldr-badge ldr-badge-secondary ms-1">${folder.item_count || 0}</span>
+ <span class="ldr-badge ldr-badge-secondary ms-1">${itemCount}</span>
</button>
`;
tabsContainer.insertBefore(li, createBtn);
@@ -212,6 +214,8 @@ class SubscriptionManager {
const nextRefresh = new Date(subscription.next_refresh);
const now = new Date();
const timeUntil = this.formatTimeUntil(nextRefresh - now);
+ const parsedRefreshInterval = Number.parseInt(subscription.refresh_interval_minutes, 10);
+ const refreshIntervalMinutes = Number.isFinite(parsedRefreshInterval) ? parsedRefreshInterval : 0;
return `
<div class="ldr-subscription-card mb-3" data-subscription-id="${window.escapeHtml(subscription.id)}">
@@ -219,7 +223,7 @@ class SubscriptionManager {
<div class="flex-grow-1">
<h6 class="mb-1">${window.escapeHtml(subscription.query_or_topic)}</h6>
<div class="text-muted small">
- <span><i class="bi bi-clock"></i> Every ${subscription.refresh_interval_minutes} min</span>
+ <span><i class="bi bi-clock"></i> Every ${refreshIntervalMinutes} min</span>
<span class="ms-3"><i class="bi bi-arrow-clockwise"></i> Next: ${timeUntil}</span>
${subscription.folder ? `<span class="ms-3"><i class="bi bi-folder"></i> ${window.escapeHtml(subscription.folder)}</span>` : ''}
</div>
@@ -342,7 +346,7 @@ class SubscriptionManager {
async updateSubscription(subscriptionId, updates) {
try {
- const response = await fetch(`/news/api/subscription/subscriptions/${subscriptionId}`, {
+ const response = await fetch(`/news/api/subscription/subscriptions/${encodeURIComponent(subscriptionId)}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
@@ -374,7 +378,7 @@ class SubscriptionManager {
// /news/api/subscription/subscriptions/{id} path only accepts
// PUT, so this button always 405'd ("Failed to delete
// subscription").
- const response = await fetch(`/news/api/subscriptions/${subscriptionId}`, {
+ const response = await fetch(`/news/api/subscriptions/${encodeURIComponent(subscriptionId)}`, {
method: 'DELETE',
headers: {
'X-CSRFToken': this.getCSRFToken()
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 fe35420cc6..d570221585 100644
--- a/src/local_deep_research/web/static/js/pages/news.js
+++ b/src/local_deep_research/web/static/js/pages/news.js
@@ -2086,7 +2086,7 @@ function renderSourceLinks(links) {
// Show subscription history
async function showSubscriptionHistory(subscriptionId) {
try {
- const response = await fetch(`/news/api/subscriptions/${subscriptionId}/history`);
+ const response = await fetch(`/news/api/subscriptions/${encodeURIComponent(subscriptionId)}/history`);
if (!response.ok) throw new Error('Failed to load history');
const data = await response.json();
@@ -4214,7 +4214,7 @@ async function handleNewsSubscriptionSubmit(e) {
if (runNow && data.subscription_id) {
// Call the run endpoint for this subscription
try {
- const runResponse = await fetch(`/news/api/subscriptions/${data.subscription_id}/run`, {
+ const runResponse = await fetch(`/news/api/subscriptions/${encodeURIComponent(data.subscription_id)}/run`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
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 3d9d63c174..a1bf8b08db 100644
--- a/src/local_deep_research/web/static/js/pages/subscriptions.js
+++ b/src/local_deep_research/web/static/js/pages/subscriptions.js
@@ -108,6 +108,12 @@ function setupEventListeners() {
// Dispatch a click on a subscription card or on one of its action buttons
function handleSubscriptionCardAction(event) {
const grid = event.currentTarget;
+ // A click inside a link on a card (Edit, View original research) is left
+ // to the link: it navigates and does not also open the card's history.
+ // So the Edit link needs no inline handler to keep the click off the card.
+ const link = event.target.closest('a');
+ if (link && grid.contains(link)) return;
+
const actionElement = event.target.closest('[data-subscription-action]');
if (!actionElement || !grid.contains(actionElement)) return;
const card = actionElement.closest('.ldr-subscription-card');
@@ -232,10 +238,14 @@ function createSubscriptionCard(subscription) {
const lastUpdated = subscription.last_refreshed ?
new Date(subscription.last_refreshed).toLocaleString() : 'Never';
- // Use refresh_minutes directly
- const refreshMinutes = subscription.refresh_minutes;
+ // Coerce the raw API value to an integer before any of it can reach
+ // markup: non-numeric refresh_minutes values fall back to a safe label.
+ const parsedRefreshMinutes = Number.parseInt(subscription.refresh_minutes, 10);
+ const refreshMinutes = Number.isFinite(parsedRefreshMinutes) ? parsedRefreshMinutes : null;
let refreshInterval;
- if (refreshMinutes === 1) {
+ if (refreshMinutes === null) {
+ refreshInterval = 'Custom schedule';
+ } else if (refreshMinutes === 1) {
refreshInterval = 'Every minute';
} else if (refreshMinutes < 60) {
refreshInterval = `Every ${refreshMinutes} minutes`;
@@ -264,6 +274,11 @@ function createSubscriptionCard(subscription) {
const safeTruncatedQuery = escapeHtml(truncatedQuery);
const safeQuery = escapeHtml(subscription.query);
+ // Coerce to an integer so a hostile total_runs value can never become
+ // markup when interpolated into the card stats below.
+ const parsedTotalRuns = Number.parseInt(subscription.total_runs, 10);
+ const totalRuns = Number.isFinite(parsedTotalRuns) ? parsedTotalRuns : 0;
+
return `
<div class="ldr-subscription-card" data-subscription-id="${escapeHtml(subscription.id)}" data-subscription-action="history" style="cursor: pointer;">
<div class="ldr-card-header">
@@ -278,7 +293,7 @@ function createSubscriptionCard(subscription) {
<button class="btn btn-sm ldr-btn-icon" data-subscription-action="history" title="View history">
<i class="bi bi-clock-history"></i>
</button>
- <a href="/news/subscriptions/${encodeURIComponent(subscription.id)}/edit" class="btn btn-sm ldr-btn-icon" onclick="event.stopPropagation();" title="Edit">
+ <a href="/news/subscriptions/${encodeURIComponent(subscription.id)}/edit" class="btn btn-sm ldr-btn-icon" title="Edit">
<i class="bi bi-pencil"></i>
</a>
<button class="btn btn-sm ldr-btn-icon btn-danger" data-subscription-action="delete" title="Delete">
@@ -296,7 +311,7 @@ function createSubscriptionCard(subscription) {
<div class="ldr-subscription-stats">
<div class="ldr-stat-item">
<i class="bi bi-file-text"></i>
- <span>${subscription.total_runs || 0} research runs</span>
+ <span>${totalRuns} research runs</span>
</div>
${subscription.source_id ? `
<div class="ldr-stat-item">
@@ -363,7 +378,9 @@ async function runSubscriptionNow(subscriptionId) {
try {
const query = subscription.query || subscription.query_or_topic || '';
SafeLogger.log('Running subscription:', subscriptionId, 'with query:', query);
- showAlert('Starting research for: ' + query, 'info');
+ // showAlert renders HTML, so the query is escaped to show as text.
+ const safeQuery = escapeHtml(query);
+ showAlert('Starting research for: ' + safeQuery, 'info');
const requestData = {
query,
@@ -416,19 +433,20 @@ async function runSubscriptionNow(subscriptionId) {
// window.open('/news', '_blank');
} else {
SafeLogger.error('Unexpected response:', data);
- // Safe: showAlert escapes internally
- showAlert('Failed to start research: ' + (data.message || 'Unknown error'), 'error');
+ // showAlert renders HTML, so the server's text is escaped.
+ const safeMessage = escapeHtml(data.message || 'Unknown error');
+ showAlert('Failed to start research: ' + safeMessage, 'error');
}
} else {
SafeLogger.error('Research API error:', response.status, response.statusText);
const errorData = await response.json().catch(() => ({}));
SafeLogger.error('Error data:', errorData);
- // Safe: showAlert escapes internally
- showAlert(
+ // showAlert renders HTML, so the server's text is escaped.
+ const safeError = escapeHtml(
errorData.message || errorData.error || errorData.detail ||
- 'Failed to start research',
- 'error'
+ 'Failed to start research'
);
+ showAlert(safeError, 'error');
}
} catch (error) {
SafeLogger.error('Error running subscription:', error);
@@ -447,7 +465,7 @@ async function toggleSubscription(subscriptionId) {
subscriptionToggleIntents.set(subscriptionId, intendedActiveState);
try {
- const response = await fetch(`/news/api/subscriptions/${subscriptionId}`, {
+ const response = await fetch(`/news/api/subscriptions/${encodeURIComponent(subscriptionId)}`, {
...fetchOptions,
method: 'PUT',
headers: {
@@ -487,7 +505,7 @@ async function viewSubscriptionHistory(subscriptionId) {
try {
// Fetch subscription history
- const response = await fetch(`/news/api/subscriptions/${subscriptionId}/history`, fetchOptions);
+ const response = await fetch(`/news/api/subscriptions/${encodeURIComponent(subscriptionId)}/history`, fetchOptions);
if (response.ok) {
const data = await response.json();
showSubscriptionHistoryModal(subscription, data);
@@ -505,6 +523,11 @@ function showSubscriptionHistoryModal(subscription, historyData) {
// Escape user-controlled values for XSS prevention
const safeTitle = escapeHtml(subscription.name || subscription.query);
+ // Coerce to an integer: historyData.total_runs is an API value that
+ // must never be interpolated into the modal as raw markup.
+ const parsedHistoryRuns = Number.parseInt(historyData.total_runs, 10);
+ const totalHistoryRuns = Number.isFinite(parsedHistoryRuns) ? parsedHistoryRuns : 0;
+
// Create modal content
const modalContent = `
<div class="modal fade" id="historyModal" tabindex="-1">
@@ -518,11 +541,11 @@ function showSubscriptionHistoryModal(subscription, historyData) {
</div>
<div class="modal-body">
<div class="ldr-history-summary">
- <p><strong>Total research runs:</strong> ${historyData.total_runs || 0}</p>
+ <p><strong>Total research runs:</strong> ${totalHistoryRuns}</p>
<p><strong>Created:</strong> ${new Date(subscription.created_at).toLocaleString()}</p>
${subscription.source_id ? `
<p><strong>Created from:</strong>
- <a href="/progress/${encodeURIComponent(subscription.source_id)}" target="_blank">
+ <a href="/progress/${encodeURIComponent(subscription.source_id)}" target="_blank" rel="noopener noreferrer">
Original research <i class="bi bi-box-arrow-up-right"></i>
</a>
</p>
@@ -538,17 +561,25 @@ function showSubscriptionHistoryModal(subscription, historyData) {
// Sanitize status to alphanumeric for safe CSS class usage
const safeStatusClass = (item.status || 'unknown').replace(/[^\w-]/g, '');
const safeStatus = escapeHtml(item.status || 'unknown');
+ const rawDurationSeconds = item.duration_seconds;
+ const hasDurationValue =
+ (typeof rawDurationSeconds === 'number' || typeof rawDurationSeconds === 'string') &&
+ !(typeof rawDurationSeconds === 'string' && rawDurationSeconds.trim() === '');
+ const durationSeconds = hasDurationValue ? Number(rawDurationSeconds) : NaN;
+ const safeDurationSeconds = Number.isFinite(durationSeconds) && durationSeconds >= 0
+ ? durationSeconds
+ : null;
return `
<div class="ldr-history-item">
<div class="ldr-history-item-header">
- <a href="/progress/${encodeURIComponent(item.research_id)}" target="_blank">
+ <a href="/progress/${encodeURIComponent(item.research_id)}" target="_blank" rel="noopener noreferrer">
${safeHeadline} <i class="bi bi-box-arrow-up-right"></i>
</a>
<span class="ldr-history-date">${new Date(item.created_at).toLocaleString()}</span>
</div>
<div class="ldr-history-item-meta">
<span class="ldr-status-badge ldr-status-${safeStatusClass}">${safeStatus}</span>
- ${item.duration_seconds ? `<span class="ldr-duration">${item.duration_seconds}s</span>` : ''}
+ ${safeDurationSeconds !== null ? `<span class="ldr-duration">${safeDurationSeconds}s</span>` : ''}
${item.topics && item.topics.length > 0 ?
`<div class="ldr-topics-list">${item.topics.slice(0, 3).map(topic =>
`<span class="ldr-topic-badge">${escapeHtml(topic)}</span>`
@@ -598,7 +629,7 @@ async function deleteSubscriptionDirect(subscriptionId) {
}
try {
- const response = await fetch(`/news/api/subscriptions/${subscriptionId}`, {
+ const response = await fetch(`/news/api/subscriptions/${encodeURIComponent(subscriptionId)}`, {
...fetchOptions,
method: 'DELETE',
headers: {
@@ -616,8 +647,10 @@ async function deleteSubscriptionDirect(subscriptionId) {
await loadSubscriptions();
} else {
const error = await response.json();
- // Safe: showAlert escapes internally
- showAlert(error.error || 'Failed to delete subscription', 'error');
+ // showAlert renders HTML, so the server's text is escaped. A
+ // not-found error repeats the subscription ID back.
+ const safeError = escapeHtml(error.error || 'Failed to delete subscription');
+ showAlert(safeError, 'error');
}
} catch (error) {
SafeLogger.error('Error deleting subscription:', error);
@@ -708,8 +741,10 @@ async function createNewFolder() {
if (response.ok) {
const folder = await response.json();
- // Safe: showAlert escapes internally
- showAlert(`Folder "${folder.name}" created successfully!`, 'success');
+ // showAlert renders HTML, so the folder name is escaped to show
+ // as text.
+ const safeFolderName = escapeHtml(folder.name);
+ showAlert(`Folder "${safeFolderName}" created successfully!`, 'success');
// Reload folders
await loadFolders();
@@ -721,8 +756,9 @@ async function createNewFolder() {
if (response.status === 409) {
showAlert('A folder with that name already exists', 'warning');
} else {
- // Safe: showAlert escapes internally
- showAlert(error.error || 'Failed to create folder', 'error');
+ // showAlert renders HTML, so the server's text is escaped.
+ const safeError = escapeHtml(error.error || 'Failed to create folder');
+ showAlert(safeError, 'error');
}
}
} catch (error) {
@@ -750,11 +786,25 @@ function showAlert(message, type) {
const alertDiv = document.createElement('div');
const alertType = window.LdrAlertHelpers.mapAlertType(type);
alertDiv.className = `alert alert-${alertType} alert-dismissible fade show`;
- // Sanitize message: allows safe HTML tags (links, lists) while stripping dangerous ones
+ // The message is HTML. Sanitizing keeps safe tags (links, lists) and
+ // strips dangerous ones. Unlike the showAlert in services/ui.js, this one
+ // does not escape. Callers therefore escape every value that comes from
+ // the API (subscription fields, folder names, server error text) or reduce
+ // it to safe characters (the research ID in the progress link), so no API
+ // value adds markup of its own. They escape into a variable first: the
+ // check-double-escaping hook assumes every showAlert escapes and flags
+ // escapeHtml() written inside the call.
+ // SAFE_FOR_TEMPLATES: false overrides SANITIZE_CONFIG's default of true.
+ // With it on, DOMPurify blanks a text node from any `{{`, `<%` or `${` to
+ // its end, and from its start through any `}}` or `%>`. Escaped server
+ // error text often contains these (nested JSON error bodies, shell-style
+ // examples). The option only matters when a client-side template engine
+ // reads the page, and none does. SANITIZE_CONFIG's ALLOW_DATA_ATTR: false
+ // still strips data-* attributes from the message.
// bearer:disable javascript_lang_dangerous_insert_html
- /* eslint-disable no-unsanitized/property -- audited 2026-03-28: plugin bug — LogicalExpression callee (github.com/mozilla/eslint-plugin-no-unsanitized/issues/263) */
+ /* eslint-disable no-unsanitized/property -- window.sanitizeHtml is an allowlisted escape method in eslint.config.js; the plugin does not special-case a ConditionalExpression callee, so this stays suppressed the same way the LogicalExpression form it replaces was (audited 2026-03-28; github.com/mozilla/eslint-plugin-no-unsanitized/issues/263) */
alertDiv.innerHTML = `
- ${(window.sanitizeHtml || escapeHtml)(message)}
+ ${window.sanitizeHtml ? window.sanitizeHtml(message, { SAFE_FOR_TEMPLATES: false }) : escapeHtml(message)}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
`;
/* eslint-enable no-unsanitized/property */
@@ -831,11 +881,12 @@ function showSchedulerInfo() {
`, 'info');
}
-// The card actions are dispatched by handleSubscriptionCardAction. The
-// scheduler notice's constant inline "Learn more" handler still resolves
-// showSchedulerInfo through window. Assign them all explicitly so that
-// contract remains intact if this file is later loaded as a module (and so
-// tests can drive the real page runtime).
+// handleSubscriptionCardAction calls the card actions directly, so nothing
+// on the page reaches them through window. Only the scheduler notice's
+// constant inline "Learn more" handler still resolves a function through
+// window: showSchedulerInfo. Assigning it explicitly keeps that handler
+// working if this file is later loaded as a module. The card actions stay on
+// window so tests can drive the real page runtime.
window.runSubscriptionNow = runSubscriptionNow;
window.toggleSubscription = toggleSubscription;
window.viewSubscriptionHistory = viewSubscriptionHistory;
diff --git a/tests/js/components/subscription-manager-delete-url.test.js b/tests/js/components/subscription-manager-delete-url.test.js
index 7e174a3d14..58257b41e6 100644
--- a/tests/js/components/subscription-manager-delete-url.test.js
+++ b/tests/js/components/subscription-manager-delete-url.test.js
@@ -55,6 +55,22 @@ describe('subscriptionManager.deleteSubscription', () => {
expect(manager.loadSubscriptionData).toHaveBeenCalledOnce();
});
+ it('percent-encodes the ID into one segment of the DELETE path', async () => {
+ await manager.deleteSubscription('../../api/v1/settings?reset=1#top');
+
+ const [url, options] = fetchMock.mock.calls[0];
+ expect(url).toBe(
+ '/news/api/subscriptions/..%2F..%2Fapi%2Fv1%2Fsettings%3Freset%3D1%23top'
+ );
+ expect(options.method).toBe('DELETE');
+ // The ID can neither climb out of /news/api/subscriptions/ nor add a
+ // query string or fragment.
+ const parsed = new URL(url, 'http://localhost');
+ expect(parsed.pathname).toBe(url);
+ expect(parsed.search).toBe('');
+ expect(parsed.hash).toBe('');
+ });
+
it('does not fetch when the confirm dialog is declined', async () => {
window.confirm.mockReturnValue(false);
await manager.deleteSubscription('sub-123');
@@ -125,6 +141,22 @@ describe('subscriptionManager.updateSubscription', () => {
expect(manager.showError).not.toHaveBeenCalled();
});
+ it('percent-encodes the ID into one segment of the PUT path', async () => {
+ await manager.updateSubscription('../../api/v1/settings?reset=1#top', {
+ status: 'paused',
+ });
+
+ const [url, options] = fetchMock.mock.calls[0];
+ expect(url).toBe(
+ '/news/api/subscription/subscriptions/..%2F..%2Fapi%2Fv1%2Fsettings%3Freset%3D1%23top'
+ );
+ expect(options.method).toBe('PUT');
+ const parsed = new URL(url, 'http://localhost');
+ expect(parsed.pathname).toBe(url);
+ expect(parsed.search).toBe('');
+ expect(parsed.hash).toBe('');
+ });
+
it('does not report success or refresh after a rejected update', async () => {
fetchMock.mockResolvedValue({ ok: false, status: 422 });
diff --git a/tests/js/components/subscription-manager-render-card.test.js b/tests/js/components/subscription-manager-render-card.test.js
index a49fc77c29..2a5fbc9b57 100644
--- a/tests/js/components/subscription-manager-render-card.test.js
+++ b/tests/js/components/subscription-manager-render-card.test.js
@@ -127,4 +127,31 @@ describe('subscriptionManager.renderSubscriptionCard', () => {
const html = manager.renderSubscriptionCard(makeSubscription());
expect(html).toMatch(/Next:\s*\d+[mhd]/);
});
+
+ it('does not turn a hostile refresh interval into markup', () => {
+ const html = manager.renderSubscriptionCard(makeSubscription({
+ refresh_interval_minutes: '<img src=x onerror=alert(1)>',
+ }));
+ const host = document.createElement('div');
+ // eslint-disable-next-line no-unsanitized/property -- the rendered card is intentionally parsed to verify that untrusted API data stays inert.
+ host.innerHTML = html;
+
+ expect(host.querySelector('img')).toBeNull();
+ expect(host.textContent).toContain('Every 0 min');
+ });
+
+ it('does not turn a hostile folder count into markup', () => {
+ document.body.innerHTML = '<ul id="folderTabs"><li><button id="create-folder-btn"></button></li></ul>';
+ manager.folders = [{
+ name: 'Research',
+ icon: '📁',
+ item_count: '<img src=x onerror=alert(1)>',
+ }];
+
+ manager.renderFolderTabs();
+
+ const folderTab = document.querySelector('#folderTabs [data-folder="Research"]');
+ expect(folderTab.querySelector('img')).toBeNull();
+ expect(folderTab.querySelector('.ldr-badge').textContent).toBe('0');
+ });
});
diff --git a/tests/js/pages/news-subscription-submit-runtime.test.js b/tests/js/pages/news-subscription-submit-runtime.test.js
index e0b586e4df..b710f2926c 100644
--- a/tests/js/pages/news-subscription-submit-runtime.test.js
+++ b/tests/js/pages/news-subscription-submit-runtime.test.js
@@ -397,6 +397,36 @@ it('reports an immediate-run failure without starting a status poll', async () =
expect(runtime.loadSubscriptions).toHaveBeenCalledOnce();
});
+it('percent-encodes the returned subscription ID into one segment of the run path', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({
+ status: 'success',
+ subscription_id: '../../api/v1/settings?reset=1#top',
+ }))
+ .mockResolvedValueOnce(response(
+ { error: 'research queue full' },
+ false,
+ 409,
+ ));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileSubscriptionRuntime();
+
+ await runtime.handleNewsSubscriptionSubmit({ preventDefault: vi.fn() });
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ const [runUrl, runOptions] = fetchMock.mock.calls[1];
+ expect(runUrl).toBe(
+ '/news/api/subscriptions/..%2F..%2Fapi%2Fv1%2Fsettings%3Freset%3D1%23top/run',
+ );
+ expect(runOptions.method).toBe('POST');
+ // The ID can neither climb out of /news/api/subscriptions/ nor add a
+ // query string or fragment.
+ const parsed = new URL(runUrl, 'http://localhost');
+ expect(parsed.pathname).toBe(runUrl);
+ expect(parsed.search).toBe('');
+ expect(parsed.hash).toBe('');
+});
+
it('retires a superseded status request before it can contradict the newer run', async () => {
const staleStatus = deferred();
const fetchMock = vi.fn()
diff --git a/tests/js/pages/subscriptions-card-actions-runtime.test.js b/tests/js/pages/subscriptions-card-actions-runtime.test.js
index bf1cb5945e..c142b24982 100644
--- a/tests/js/pages/subscriptions-card-actions-runtime.test.js
+++ b/tests/js/pages/subscriptions-card-actions-runtime.test.js
@@ -10,7 +10,15 @@
*/
const HOSTILE_ID = "sub\"&<');window.__subscriptionCardActionXss=true;//";
-const ACTION_URL = `/news/api/subscriptions/${HOSTILE_ID}`;
+// The page percent-encodes the ID into the request path, so its quote, "&"
+// and "/" characters stay inside one path segment.
+const ACTION_URL = `/news/api/subscriptions/${encodeURIComponent(HOSTILE_ID)}`;
+// The page makes these requests when it boots, before any click.
+const BOOT_URLS = new Set([
+ '/news/api/subscriptions/current',
+ '/news/api/subscription/folders',
+ '/news/api/scheduler/status',
+]);
function jsonResponse(payload, status = 200) {
return {
@@ -47,11 +55,24 @@ function installDom() {
let fetchMock;
let registeredDocumentListeners;
+let registeredGridListeners;
+let linkClickDefaultPrevented;
+
+// happy-dom follows a clicked link by navigating the test window. This
+// listener runs after every page listener: it records whether the page left
+// the link's navigation alone, then cancels the navigation.
+function cancelLinkNavigation(event) {
+ if (!event.target.closest('a')) return;
+ linkClickDefaultPrevented.push(event.defaultPrevented);
+ event.preventDefault();
+}
beforeEach(async () => {
vi.resetModules();
vi.useFakeTimers();
registeredDocumentListeners = [];
+ registeredGridListeners = [];
+ linkClickDefaultPrevented = [];
installDom();
await import('@js/security/xss-protection.js');
await import('@js/utils/alert-helpers.js');
@@ -71,6 +92,7 @@ beforeEach(async () => {
refresh_minutes: 60,
created_at: '2026-10-01T10:00:00.000Z',
total_runs: 0,
+ source_id: 'source-3299',
}],
});
}
@@ -93,6 +115,13 @@ beforeEach(async () => {
registeredDocumentListeners.push([type, listener, options]);
originalDocumentAdd(type, listener, options);
});
+ const grid = document.getElementById('subscriptions-grid');
+ const originalGridAdd = grid.addEventListener.bind(grid);
+ const gridAddSpy = vi.spyOn(grid, 'addEventListener')
+ .mockImplementation((type, listener, options) => {
+ registeredGridListeners.push([type, listener, options]);
+ originalGridAdd(type, listener, options);
+ });
try {
await import('@js/pages/subscriptions.js');
document.dispatchEvent(new Event('DOMContentLoaded'));
@@ -102,10 +131,13 @@ beforeEach(async () => {
});
} finally {
documentAddSpy.mockRestore();
+ gridAddSpy.mockRestore();
}
+ document.addEventListener('click', cancelLinkNavigation);
});
afterEach(() => {
+ document.removeEventListener('click', cancelLinkNavigation);
registeredDocumentListeners.forEach(([type, listener, options]) => {
document.removeEventListener(type, listener, options);
});
@@ -134,7 +166,23 @@ function cardButtonIcon(action) {
.querySelector(`button[data-subscription-action="${action}"] i`);
}
-it('keeps the subscription ID out of every inline handler on the card', () => {
+// Requests made after the first `start` fetch calls, without boot requests.
+function requestsSince(start) {
+ return fetchMock.mock.calls.slice(start)
+ .map(([url, options = {}]) => [String(url), options.method || 'GET'])
+ .filter(([url]) => !BOOT_URLS.has(url));
+}
+
+/**
+ * The card carries no inline handler at all.
+ *
+ * This used to allow exactly one: the Edit link's constant
+ * onclick="event.stopPropagation();", which kept a click on the link from
+ * also opening the card's history. That premise changed. The grid listener
+ * now ignores any click inside a link, so the Edit link needs no handler
+ * and the card has none.
+ */
+it('keeps every inline handler off the card', () => {
const card = subscriptionCard();
expect(card.dataset.subscriptionId).toBe(HOSTILE_ID);
@@ -142,8 +190,68 @@ it('keeps the subscription ID out of every inline handler on the card', () => {
.flatMap(element => [...element.attributes]
.filter(attribute => attribute.name.startsWith('on'))
.map(attribute => [element.tagName, attribute.name, attribute.value]));
- // Only the Edit link keeps a constant handler, and it carries no ID.
- expect(inlineHandlers).toEqual([['A', 'onclick', 'event.stopPropagation();']]);
+ expect(inlineHandlers).toEqual([]);
+});
+
+it.each([
+ ['the card body', '.ldr-query-text', [[`${ACTION_URL}/history`, 'GET']]],
+ ['Run now', 'button[data-subscription-action="run"] i', [['/api/start_research', 'POST']]],
+ ['Pause', 'button[data-subscription-action="toggle"] i', [[ACTION_URL, 'PUT']]],
+ ['View history', 'button[data-subscription-action="history"] i', [[`${ACTION_URL}/history`, 'GET']]],
+ ['Delete', 'button[data-subscription-action="delete"] i', [[ACTION_URL, 'DELETE']]],
+])('a click on %s runs exactly one action, once', async (_label, selector, expected) => {
+ const start = fetchMock.mock.calls.length;
+
+ subscriptionCard().querySelector(selector).click();
+
+ // Each handler sends its request during the click. A second dispatch of
+ // the same click (a button also opening history, or a card-body click
+ // opening it twice) would add a request here.
+ expect(requestsSince(start)).toEqual(expected);
+ // Every action fails against the 503 stub. Its error alert shows that
+ // the handler has finished, and still no other request was made.
+ await vi.waitFor(() => {
+ expect(document.querySelector('.alert-danger')).not.toBeNull();
+ });
+ expect(requestsSince(start)).toEqual(expected);
+});
+
+it.each([
+ ['the Edit link', 'a[title="Edit"] i'],
+ ['the View original research link', 'a.ldr-source-link'],
+])('a click on %s only follows the link', (_label, selector) => {
+ const start = fetchMock.mock.calls.length;
+
+ subscriptionCard().querySelector(selector).click();
+
+ expect(requestsSince(start)).toEqual([]);
+ // The page did not cancel the navigation.
+ expect(linkClickDefaultPrevented).toEqual([false]);
+});
+
+/**
+ * The grid listener is the only listener that acts on a card click.
+ *
+ * A second card listener, such as one on document, would run again for any
+ * click the grid listener lets bubble: a click on the card body would open
+ * its history twice. With the grid listener removed, no click anywhere on
+ * the card may make a request.
+ */
+it('dispatches card clicks through the grid listener alone', () => {
+ const grid = document.getElementById('subscriptions-grid');
+ const gridClickListeners = registeredGridListeners
+ .filter(([type]) => type === 'click');
+ gridClickListeners.forEach(([type, listener, options]) => {
+ grid.removeEventListener(type, listener, options);
+ });
+ const start = fetchMock.mock.calls.length;
+
+ const card = subscriptionCard();
+ [card, ...card.querySelectorAll('*')].forEach(element => element.click());
+
+ expect(requestsSince(start)).toEqual([]);
+ // The listener removed above is the page's card dispatcher.
+ expect(gridClickListeners).toHaveLength(1);
});
it('dispatches each card action with the exact subscription ID', async () => {
diff --git a/tests/js/pages/subscriptions-migration-runtime.test.js b/tests/js/pages/subscriptions-migration-runtime.test.js
index 39b7f4239f..9429307edf 100644
--- a/tests/js/pages/subscriptions-migration-runtime.test.js
+++ b/tests/js/pages/subscriptions-migration-runtime.test.js
@@ -7,6 +7,11 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
+// The handlers escape API text with the global escapeHtml before showing it
+// in an alert. Production loads xss-protection.js on every page first; the
+// extracted handlers below resolve escapeHtml from the same global.
+import '@js/security/xss-protection.js';
+
const SOURCE_PATH = resolve(
__dirname,
'../../../src/local_deep_research/web/static/js/pages/subscriptions.js',
diff --git a/tests/js/pages/subscriptions-xss.test.js b/tests/js/pages/subscriptions-xss.test.js
new file mode 100644
index 0000000000..a63a13b193
--- /dev/null
+++ b/tests/js/pages/subscriptions-xss.test.js
@@ -0,0 +1,542 @@
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const pageMarkup = `
+ <div class="ldr-page-header"></div>
+ <input id="subscription-search" />
+ <select id="status-filter"></select>
+ <select id="frequency-filter"></select>
+ <button id="add-folder-btn"></button>
+ <button id="create-subscription-btn"></button>
+ <div id="subscriptions-grid"></div>
+ <span id="total-subscriptions"></span>
+ <span id="active-subscriptions"></span>
+ <span id="paused-subscriptions"></span>
+ <span id="updates-today"></span>
+ <span id="status-indicator"></span>
+ <span id="status-text"></span>
+ <div id="scheduler-details"></div>
+ <nav class="ldr-folder-list">
+ <div class="ldr-folder-item" data-folder="all">All <span class="ldr-folder-count">0</span></div>
+ <div class="ldr-folder-item" data-folder="uncategorized">Uncategorized <span class="ldr-folder-count">0</span></div>
+ </nav>
+`;
+
+function subscription(overrides = {}) {
+ return {
+ id: 'subscription-1',
+ name: 'AI news',
+ query: 'latest AI research',
+ is_active: true,
+ refresh_minutes: 60,
+ total_runs: 5,
+ last_refreshed: null,
+ next_refresh: null,
+ folder_id: null,
+ source_id: null,
+ ...overrides,
+ };
+}
+
+function response(data) {
+ return Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve(data),
+ });
+}
+
+async function renderThroughLoadPath(subscriptions, folders = []) {
+ // eslint-disable-next-line no-unsanitized/property -- test fixture: pageMarkup is a hardcoded static template with no interpolated values.
+ document.body.innerHTML = pageMarkup;
+ globalThis.fetch = vi.fn((url) => {
+ switch (url) {
+ case '/news/api/subscriptions/current':
+ return response({ subscriptions });
+ case '/news/api/subscription/folders':
+ return response(folders);
+ case '/news/api/scheduler/status':
+ return response({ scheduler_available: false });
+ default:
+ return Promise.reject(new Error(`Unexpected fetch: ${url}`));
+ }
+ });
+
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ const grid = document.getElementById('subscriptions-grid');
+ await vi.waitFor(() => {
+ expect(grid.querySelectorAll('.ldr-subscription-card')).toHaveLength(subscriptions.length);
+ });
+ if (folders.length > 0) {
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll(`.ldr-folder-item[data-folder="${folders[0].id}"]`)).toHaveLength(1);
+ });
+ document.getElementById('subscription-search').dispatchEvent(new Event('input'));
+ }
+ return grid;
+}
+
+async function renderHistoryModal(historyData, subscriptionOverrides = {}) {
+ const historySubscription = subscription({ source_id: 'source-1', ...subscriptionOverrides });
+ // eslint-disable-next-line no-unsanitized/property -- test fixture: pageMarkup is a hardcoded static template with no interpolated values.
+ document.body.innerHTML = pageMarkup;
+ globalThis.fetch = vi.fn((url) => {
+ switch (url) {
+ case '/news/api/subscriptions/current':
+ return response({ subscriptions: [historySubscription] });
+ case '/news/api/subscription/folders':
+ return response([]);
+ case '/news/api/scheduler/status':
+ return response({ scheduler_available: false });
+ case `/news/api/subscriptions/${encodeURIComponent(historySubscription.id)}/history`:
+ return response(historyData);
+ default:
+ return Promise.reject(new Error(`Unexpected fetch: ${url}`));
+ }
+ });
+
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ const grid = document.getElementById('subscriptions-grid');
+ await vi.waitFor(() => {
+ expect(grid.querySelectorAll('.ldr-subscription-card')).toHaveLength(1);
+ });
+
+ grid.querySelector('.ldr-subscription-card').click();
+ await vi.waitFor(() => {
+ expect(document.getElementById('historyModal')).not.toBeNull();
+ });
+ return document.getElementById('historyModal');
+}
+
+function historyRunsText(modal) {
+ const line = Array.from(modal.querySelectorAll('.ldr-history-summary p'))
+ .find((p) => p.querySelector('strong')?.textContent === 'Total research runs:');
+ return line?.textContent;
+}
+
+beforeAll(async () => {
+ window.LdrAlertHelpers = { mapAlertType: (type) => type };
+ globalThis.bootstrap = {
+ Modal: vi.fn(function() {
+ this.show = () => {};
+ }),
+ };
+ await import('@js/security/xss-protection.js');
+ await import('@js/pages/subscriptions.js');
+});
+
+describe('subscriptions adversarial rendering', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('renders benign subscription fields through the real load path', async () => {
+ const grid = await renderThroughLoadPath([subscription()]);
+ const card = grid.querySelector('.ldr-subscription-card');
+
+ expect(card.dataset.subscriptionId).toBe('subscription-1');
+ expect(card.querySelector('h4').textContent).toBe('AI news');
+ expect(card.querySelector('.ldr-frequency-badge').textContent).toBe('Hourly');
+ expect(card.querySelector('.ldr-subscription-stats').textContent).toContain('5 research runs');
+ });
+
+ it('escapes hostile names instead of creating header markup', async () => {
+ const name = '<img src=x onerror=alert(1)><script>alert(2)</script>';
+ const grid = await renderThroughLoadPath([subscription({ name })]);
+ const heading = grid.querySelector('.ldr-card-header h4');
+
+ expect(heading.querySelector('img, script')).toBeNull();
+ expect(heading.textContent).toBe(`${name.substring(0, 50)}...`);
+ expect(heading.getAttribute('title')).toBe(name);
+ });
+
+ it('escapes hostile queries instead of creating query markup', async () => {
+ const query = '<img src=x onerror=alert(1)><script>alert(2)</script>';
+ const grid = await renderThroughLoadPath([subscription({ query })]);
+ const queryElement = grid.querySelector('.ldr-query-text');
+
+ expect(queryElement.querySelector('img, script')).toBeNull();
+ expect(queryElement.textContent).toBe(query);
+ expect(queryElement.getAttribute('title')).toBe(query);
+ });
+
+ it('escapes hostile folder names in both the card badge and sidebar', async () => {
+ const folder = { id: 'folder-1', name: '<img src=x onerror=alert(1)>' };
+ const grid = await renderThroughLoadPath([subscription({ folder_id: folder.id })], [folder]);
+ const badge = grid.querySelector('.ldr-folder-badge');
+ const sidebarFolder = document.querySelector('.ldr-folder-item[data-folder="folder-1"]');
+
+ expect(badge.querySelector('img')).toBeNull();
+ expect(badge.textContent).toBe(folder.name);
+ expect(sidebarFolder.querySelector('img')).toBeNull();
+ expect(sidebarFolder.textContent).toContain(folder.name);
+ });
+
+ it('percent-encodes hostile source IDs in progress links', async () => {
+ const sourceId = '"><script>alert(1)</script>';
+ const grid = await renderThroughLoadPath([subscription({ source_id: sourceId })]);
+ const link = grid.querySelector('.ldr-source-link');
+
+ expect(link.getAttribute('href')).toBe(`/progress/${encodeURIComponent(sourceId)}`);
+ expect(grid.innerHTML).not.toContain('<script>');
+ });
+
+ it('keeps hostile IDs within the data attribute HTML context', async () => {
+ const id = '"><img src=x onerror=alert(1)>';
+ const grid = await renderThroughLoadPath([subscription({ id })]);
+ const card = grid.querySelector('.ldr-subscription-card');
+
+ expect(card.dataset.subscriptionId).toBe(id);
+ expect(card.querySelectorAll('img')).toHaveLength(0);
+ });
+
+ // FIXED (was subscriptions.js:210,214,217,220,226): card actions no
+ // longer interpolate IDs into inline onclick JavaScript strings. The
+ // card and its buttons name their action in data-subscription-action,
+ // and one listener on the grid reads the ID from data-subscription-id,
+ // so there is no handler string for a hostile ID to break out of.
+ // happy-dom never runs inline handlers, so the [onclick] count and the
+ // request below carry this test.
+ it('blocks hostile IDs from executing through card action handlers', async () => {
+ const id = "subscription-');window.__subscription_onclick_xss=1;//";
+ const grid = await renderThroughLoadPath([subscription({ id })]);
+ const card = grid.querySelector('.ldr-subscription-card');
+
+ expect(card.getAttribute('onclick')).toBeNull();
+ expect(grid.querySelectorAll('[onclick]')).toHaveLength(0);
+ expect(card.dataset.subscriptionId).toBe(id);
+
+ card.click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/news/api/subscriptions/${encodeURIComponent(id)}/history`,
+ expect.anything()
+ );
+ });
+ });
+
+ it('percent-encodes a hostile ID into one segment of each request path', async () => {
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ const id = '../../api/v1/settings?reset=1#top';
+ const grid = await renderThroughLoadPath([subscription({ id })]);
+ const encodedPath = '/news/api/subscriptions/..%2F..%2Fapi%2Fv1%2Fsettings%3Freset%3D1%23top';
+
+ for (const action of ['toggle', 'history', 'delete']) {
+ grid.querySelector(`button[data-subscription-action="${action}"]`).click();
+ }
+
+ const requests = globalThis.fetch.mock.calls
+ .map(([url, options = {}]) => [url, options.method || 'GET'])
+ .filter(([url]) => url.startsWith('/news/api/subscriptions/..'));
+ expect(requests).toEqual([
+ [encodedPath, 'PUT'],
+ [`${encodedPath}/history`, 'GET'],
+ [encodedPath, 'DELETE'],
+ ]);
+ // The ID can neither climb out of /news/api/subscriptions/ nor add a
+ // query string or fragment.
+ for (const [url] of requests) {
+ const parsed = new URL(url, 'http://localhost');
+ expect(parsed.pathname.startsWith(encodedPath)).toBe(true);
+ expect(parsed.search).toBe('');
+ expect(parsed.hash).toBe('');
+ }
+ });
+
+ // FIXED (was subscriptions.js:178-196,235): refresh_minutes is coerced
+ // to an integer before innerHTML interpolation; hostile values render
+ // as a safe fallback label instead of markup.
+ it('does not materialize markup from hostile refresh_minutes values', async () => {
+ const refreshMinutes = '<img src=x onerror=alert(1)>';
+ const grid = await renderThroughLoadPath([subscription({ refresh_minutes: refreshMinutes })]);
+ const badge = grid.querySelector('.ldr-frequency-badge');
+
+ expect(badge.querySelector('img')).toBeNull();
+ expect(badge.textContent).toBe('Custom schedule');
+ });
+
+ // FIXED (was subscriptions.js:241): total_runs is coerced to an
+ // integer (default 0) everywhere it is interpolated, so a hostile API
+ // value can never become live DOM.
+ it('does not materialize markup from hostile total_runs values', async () => {
+ const totalRuns = '<img src=x onerror=alert(1)>';
+ const grid = await renderThroughLoadPath([subscription({ total_runs: totalRuns })]);
+ const stats = grid.querySelector('.ldr-subscription-stats');
+
+ expect(stats.querySelector('img')).toBeNull();
+ expect(stats.textContent).toContain('0 research runs');
+ });
+
+ // Guard: the secure structure keeps benign controls functional:
+ // data-subscription-action buttons exist, no inline onclick remains, the
+ // edit link stays a real navigable anchor, and delegated clicks still act.
+ it('keeps benign cards functional through delegated data-subscription-action controls', async () => {
+ const grid = await renderThroughLoadPath([subscription()]);
+ const card = grid.querySelector('.ldr-subscription-card');
+
+ expect(grid.querySelectorAll('[onclick]')).toHaveLength(0);
+ const actions = Array.from(
+ card.querySelectorAll('[data-subscription-action]'),
+ (el) => el.dataset.subscriptionAction,
+ );
+ expect(actions).toEqual(expect.arrayContaining(['run', 'toggle', 'history', 'delete']));
+
+ const edit = card.querySelector('a[href="/news/subscriptions/subscription-1/edit"]');
+ expect(edit).not.toBeNull();
+
+ // Edit is a normal anchor: delegation must ignore a click on its
+ // icon (no fetch).
+ globalThis.fetch.mockClear();
+ edit.querySelector('i').click();
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+
+ // Action buttons route through delegation using data-subscription-id.
+ card.querySelector('[data-subscription-action="run"]').click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith('/api/start_research', expect.anything());
+ });
+ });
+
+ // happy-dom never loads images, so no onerror handler could run here
+ // either way; the img/script counts carry this test.
+ it('keeps hostile history data inert through the real history-modal path', async () => {
+ const researchId = '"><script>alert(1)</script>';
+ const modal = await renderHistoryModal({
+ total_runs: 1,
+ history: [{
+ headline: '<img src=x onerror=alert(1)>',
+ status: '<img src=x onerror=alert(1)>',
+ duration_seconds: '<img src=x onerror=alert(1)>',
+ topics: ['<img src=x onerror=alert(1)>'],
+ research_id: researchId,
+ created_at: '2026-01-01T00:00:00Z',
+ }],
+ });
+
+ expect(globalThis.bootstrap.Modal).toHaveBeenCalled();
+ expect(modal.querySelectorAll('img, script')).toHaveLength(0);
+ expect(modal.querySelector('.ldr-duration')).toBeNull();
+
+ const historyLink = modal.querySelector('.ldr-history-item-header a');
+ expect(historyLink.getAttribute('href')).toBe(`/progress/${encodeURIComponent(researchId)}`);
+ expect(historyLink.getAttribute('rel')).toContain('noopener');
+ expect(historyLink.getAttribute('rel')).toContain('noreferrer');
+
+ const sourceLink = modal.querySelector('.ldr-history-summary a');
+ expect(sourceLink.getAttribute('rel')).toContain('noopener');
+ expect(sourceLink.getAttribute('rel')).toContain('noreferrer');
+ expect(modal.querySelector('.ldr-status-badge').querySelector('img')).toBeNull();
+ expect(modal.querySelector('.ldr-topic-badge').querySelector('img')).toBeNull();
+ });
+
+ // FIXED: the history modal coerces total_runs to an integer (default 0),
+ // as the card does, so a hostile API value can never become live DOM.
+ it('does not materialize markup from a hostile history total_runs value', async () => {
+ const modal = await renderHistoryModal({
+ total_runs: '<img src=x onerror=alert(1)>',
+ history: [],
+ });
+
+ expect(modal.querySelectorAll('img, script')).toHaveLength(0);
+ expect(historyRunsText(modal)).toBe('Total research runs: 0');
+ });
+
+ it.each([
+ ['number', 7, 'Total research runs: 7'],
+ ['numeric string', '12', 'Total research runs: 12'],
+ ])('shows a %s history total_runs value as the count', async (_label, totalRuns, expected) => {
+ const modal = await renderHistoryModal({ total_runs: totalRuns, history: [] });
+
+ expect(historyRunsText(modal)).toBe(expected);
+ });
+
+ it('renders benign numeric history durations', async () => {
+ const modal = await renderHistoryModal({
+ total_runs: 1,
+ history: [{
+ headline: 'Benign headline',
+ status: 'completed',
+ duration_seconds: 42,
+ topics: [],
+ research_id: 'research-1',
+ created_at: '2026-01-01T00:00:00Z',
+ }],
+ });
+
+ expect(modal.querySelector('.ldr-duration').textContent).toBe('42s');
+ });
+
+ it.each([
+ ['null', null],
+ ['empty string', ''],
+ ['whitespace string', ' '],
+ ['NaN', NaN],
+ ['positive infinity', Infinity],
+ ['negative infinity', -Infinity],
+ ['undefined', undefined],
+ ])('omits %s history durations', async (_label, durationSeconds) => {
+ const modal = await renderHistoryModal({
+ total_runs: 1,
+ history: [{
+ headline: 'No duration yet',
+ status: 'running',
+ duration_seconds: durationSeconds,
+ topics: [],
+ research_id: 'research-no-duration',
+ created_at: '2026-01-01T00:00:00Z',
+ }],
+ });
+
+ expect(modal.querySelector('.ldr-duration')).toBeNull();
+ });
+
+ it.each([
+ ['numeric zero', 0],
+ ['numeric-string zero', '0'],
+ ])('renders intentional %s history durations', async (_label, durationSeconds) => {
+ const modal = await renderHistoryModal({
+ total_runs: 1,
+ history: [{
+ headline: 'Immediate result',
+ status: 'completed',
+ duration_seconds: durationSeconds,
+ topics: [],
+ research_id: 'research-zero-duration',
+ created_at: '2026-01-01T00:00:00Z',
+ }],
+ });
+
+ expect(modal.querySelector('.ldr-duration').textContent).toBe('0s');
+ });
+});
+
+// showAlert renders its message as sanitized HTML, which keeps links and
+// headings. The page escapes the subscription query, folder names and server
+// error text before it composes a message, so they show as text.
+describe('subscription alerts', () => {
+ const HOSTILE_MARKUP =
+ '<a href="https://attacker.example/">Claim your reward</a><h1>Account locked</h1>';
+ let purify;
+
+ beforeEach(() => {
+ // DOMPurify's DOM walk does not run under happy-dom (see
+ // xss-protection-dompurify-runtime.test.js), so this stand-in returns
+ // the message unchanged. For the markup used here, the real sanitizer
+ // returns it unchanged too: links (a href) and headings are on
+ // SANITIZE_CONFIG's allowlist.
+ purify = {
+ isSupported: true,
+ addHook: vi.fn(),
+ sanitize: vi.fn((dirty) => String(dirty)),
+ };
+ globalThis.DOMPurify = purify;
+ window.RESEARCH_STATUS = { QUEUED: 'queued' };
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ vi.stubGlobal('prompt', vi.fn(() => 'Reading list'));
+ });
+
+ afterEach(() => {
+ delete globalThis.DOMPurify;
+ delete window.RESEARCH_STATUS;
+ vi.unstubAllGlobals();
+ });
+
+ function stubResponse(payload, ok = true, status = ok ? 200 : 500) {
+ return {
+ ok,
+ status,
+ statusText: ok ? 'OK' : 'Request failed',
+ json: () => Promise.resolve(payload),
+ };
+ }
+
+ // Answer one request with a stub; every other request keeps the load
+ // path's responses.
+ function overrideFetch(matches, stub) {
+ const loadPathFetch = globalThis.fetch;
+ globalThis.fetch = vi.fn((url, options = {}) => (
+ matches(url, options) ? Promise.resolve(stub) : loadPathFetch(url, options)
+ ));
+ }
+
+ async function alertOfType(type) {
+ await vi.waitFor(() => {
+ expect(document.querySelector(`.alert-${type}`)).not.toBeNull();
+ });
+ return document.querySelector(`.alert-${type}`);
+ }
+
+ it('asks DOMPurify to keep template-like text and still strip data-* attributes', async () => {
+ await renderThroughLoadPath([subscription()]);
+
+ window.showSchedulerInfo();
+
+ expect(purify.sanitize).toHaveBeenCalled();
+ const [, config] = purify.sanitize.mock.calls.at(-1);
+ expect(config.SAFE_FOR_TEMPLATES).toBe(false);
+ expect(config.ALLOW_DATA_ATTR).toBe(false);
+ expect(config.FORBID_TAGS).toEqual(expect.arrayContaining(['script', 'button']));
+ // The page's own HTML message still renders as markup.
+ const alert = await alertOfType('info');
+ expect(alert.querySelector('h6').textContent).toBe('About the Subscription Scheduler');
+ expect(alert.querySelectorAll('li')).toHaveLength(5);
+ });
+
+ it('shows a hostile query in the Run alert as text', async () => {
+ const grid = await renderThroughLoadPath([subscription({ query: HOSTILE_MARKUP })]);
+
+ grid.querySelector('[data-subscription-action="run"]').click();
+
+ const alert = await alertOfType('info');
+ expect(alert.querySelector('a, h1')).toBeNull();
+ expect(alert.textContent).toContain(`Starting research for: ${HOSTILE_MARKUP}`);
+ });
+
+ it('shows a hostile folder name in the created-folder alert as text', async () => {
+ await renderThroughLoadPath([subscription()]);
+ overrideFetch(
+ (url, options) => url === '/news/api/subscription/folders' && options.method === 'POST',
+ stubResponse({ id: 'folder-hostile', name: HOSTILE_MARKUP }),
+ );
+
+ document.getElementById('add-folder-btn').click();
+
+ const alert = await alertOfType('success');
+ expect(alert.querySelector('a, h1')).toBeNull();
+ expect(alert.textContent).toContain(`Folder "${HOSTILE_MARKUP}" created successfully!`);
+ });
+
+ it.each([
+ [
+ 'a rejected Run',
+ (grid) => grid.querySelector('[data-subscription-action="run"]'),
+ (url) => url === '/api/start_research',
+ stubResponse({ detail: HOSTILE_MARKUP }, false, 503),
+ ],
+ [
+ 'a Run the server did not start',
+ (grid) => grid.querySelector('[data-subscription-action="run"]'),
+ (url) => url === '/api/start_research',
+ stubResponse({ status: 'error', message: HOSTILE_MARKUP }),
+ ],
+ [
+ 'a failed Delete',
+ (grid) => grid.querySelector('[data-subscription-action="delete"]'),
+ (_url, options) => options.method === 'DELETE',
+ stubResponse({ error: `Subscription not found: ${HOSTILE_MARKUP}` }, false, 404),
+ ],
+ [
+ 'a failed folder create',
+ () => document.getElementById('add-folder-btn'),
+ (url, options) => url === '/news/api/subscription/folders' && options.method === 'POST',
+ stubResponse({ error: HOSTILE_MARKUP }, false, 500),
+ ],
+ ])('shows the server text of %s as text', async (_label, control, matches, stub) => {
+ const grid = await renderThroughLoadPath([subscription()]);
+ overrideFetch(matches, stub);
+
+ control(grid).click();
+
+ const alert = await alertOfType('error');
+ expect(alert.querySelector('a, h1')).toBeNull();
+ expect(alert.textContent).toContain(HOSTILE_MARKUP);
+ });
+});
diff --git a/tests/js/services/formatting.test.js b/tests/js/services/formatting.test.js
index 3c8e47bb60..70cede1433 100644
--- a/tests/js/services/formatting.test.js
+++ b/tests/js/services/formatting.test.js
@@ -139,6 +139,21 @@ describe('formatting', () => {
it('handles zero', () => {
expect(fmt.formatNumber(0)).toBe('0');
});
+
+ it('coerces API values before they can become markup in callers', () => {
+ expect(fmt.formatNumber('1234')).toBe('1,234');
+ expect(fmt.formatNumber('<img src=x onerror=alert(1)>')).toBe('0');
+ expect(fmt.formatNumber(Infinity)).toBe('0');
+ });
+
+ it('returns "0" for values that are neither a number nor a string', () => {
+ // JSON can give an object its own toString and valueOf keys. With
+ // neither callable, Number() throws on it instead of returning NaN.
+ const unconvertible = JSON.parse('{"toString":null,"valueOf":null}');
+ expect(fmt.formatNumber(unconvertible)).toBe('0');
+ expect(fmt.formatNumber(true)).toBe('0');
+ expect(fmt.formatNumber([1234])).toBe('0');
+ });
});
describe('formatStatus', () => {