Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: block remote images and CSS in synced email bodies until loaded (#8358)

[._.]/ Adam Eivyfd34d0293589
diff --git a/client/src/components/messages/MessageDetail.jsx b/client/src/components/messages/MessageDetail.jsx
index 38065aeb57..26a54d14ca 100644
--- a/client/src/components/messages/MessageDetail.jsx
+++ b/client/src/components/messages/MessageDetail.jsx
@@ -1,15 +1,32 @@
-import { useState, useEffect, useRef, useCallback } from 'react';
-import { ArrowLeft, Reply, Sparkles, Send, RefreshCw, Archive, Trash2, User } from 'lucide-react';
+import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
+import { ArrowLeft, Reply, Sparkles, Send, RefreshCw, Archive, Trash2, User, ImageOff } from 'lucide-react';
import toast from '../ui/Toast';
import { formatCount, formatDateTime } from '../../utils/formatters';
import * as api from '../../services/api';
+// Any src/href/poster/url()/@import that points at a remote http(s) resource —
+// the load vectors a tracking pixel or remote stylesheet rides in on. Used
+// only to decide whether to show the "remote images blocked" notice; the CSP
+// meta below is what actually blocks the fetch, regardless of this matching.
+const REMOTE_REF_RE = /(?:<(?:img|source|video)\b[^>]*\bsrc\s*=\s*["']?https?:)|(?:<link\b[^>]*\bhref\s*=\s*["']?https?:)|(?:\burl\(\s*["']?https?:)|(?:@import\s+(?:url\()?["']?https?:)|(?:\bposter\s*=\s*["']?https?:)/i;
+
+// `default-src 'none'` blocks every fetch the sanitizer regex above doesn't
+// catch (background-image, @import, <link>, <source>, <video poster>, …);
+// img-src only widens to https: once the user opts in for this message, and
+// stays data:/cid: (inline + attachment-referenced) otherwise.
+const buildContentSecurityPolicy = (allowRemote) =>
+ `default-src 'none'; img-src data: cid:${allowRemote ? ' https:' : ''}; style-src 'unsafe-inline'; font-src data:`;
+
/**
* Renders HTML email content in a sandboxed iframe.
- * Strips scripts, sets sandbox restrictions, and auto-resizes to content height.
+ * Strips scripts, sets sandbox restrictions, blocks remote loads (images,
+ * stylesheets, @import) behind a CSP until the user opts in per message, and
+ * auto-resizes to content height.
*/
function SafeHtmlBody({ html }) {
const iframeRef = useRef(null);
+ const [allowRemote, setAllowRemote] = useState(false);
+ const hasRemoteRefs = useMemo(() => REMOTE_REF_RE.test(html || ''), [html]);
const writeContent = useCallback(() => {
const iframe = iframeRef.current;
@@ -33,7 +50,7 @@ function SafeHtmlBody({ html }) {
if (!doc) return;
doc.open();
- doc.write(`<!DOCTYPE html><html><head><style>
+ doc.write(`<!DOCTYPE html><html><head><meta http-equiv="Content-Security-Policy" content="${buildContentSecurityPolicy(allowRemote)}"><style>
body { margin: 0; padding: 8px; font-family: -apple-system, sans-serif; font-size: 14px; color: #d1d5db; background: transparent; word-wrap: break-word; overflow-wrap: break-word; }
a { color: #3b82f6; }
img { max-width: 100%; height: auto; }
@@ -49,23 +66,40 @@ function SafeHtmlBody({ html }) {
resize();
// Resize again after images load
doc.querySelectorAll('img').forEach(img => img.addEventListener('load', resize, { once: true }));
- }, [html]);
+ }, [html, allowRemote]);
useEffect(() => {
writeContent();
}, [writeContent]);
return (
- <iframe
- ref={iframeRef}
- // allow-same-origin is required to write/resize via contentDocument;
- // scripts remain blocked (no allow-scripts), and we sanitize HTML upstream
- // before injecting so the email body cannot execute JS.
- sandbox="allow-same-origin"
- className="w-full border-0 min-h-[100px]"
- style={{ background: 'transparent' }}
- title="Email content"
- />
+ <div>
+ <iframe
+ ref={iframeRef}
+ // allow-same-origin is required to write/resize via contentDocument;
+ // scripts remain blocked (no allow-scripts), and we sanitize HTML upstream
+ // before injecting so the email body cannot execute JS. The written
+ // document's own CSP meta blocks remote image/stylesheet loads until
+ // allowRemote is set.
+ sandbox="allow-same-origin"
+ className="w-full border-0 min-h-[100px]"
+ style={{ background: 'transparent' }}
+ title="Email content"
+ />
+ {hasRemoteRefs && !allowRemote && (
+ <div className="mt-2 flex items-center gap-2 text-xs text-gray-500">
+ <ImageOff size={14} className="shrink-0" />
+ <span>Remote images blocked</span>
+ <button
+ type="button"
+ onClick={() => setAllowRemote(true)}
+ className="text-port-accent hover:underline"
+ >
+ Load remote images
+ </button>
+ </div>
+ )}
+ </div>
);
}
diff --git a/client/src/components/messages/MessageDetail.test.jsx b/client/src/components/messages/MessageDetail.test.jsx
new file mode 100644
index 0000000000..2b987f7bba
--- /dev/null
+++ b/client/src/components/messages/MessageDetail.test.jsx
@@ -0,0 +1,95 @@
+import { describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+const api = vi.hoisted(() => ({
+ createMessageDraft: vi.fn(),
+ executeMessageAction: vi.fn(),
+ generateMessageDraft: vi.fn(),
+ getMessageThread: vi.fn().mockResolvedValue({ messages: [] }),
+ getSettings: vi.fn().mockResolvedValue({}),
+ refreshMessage: vi.fn(),
+ updateMessageDraft: vi.fn(),
+}));
+const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }));
+
+vi.mock('../../services/api', () => api);
+vi.mock('../ui/Toast', () => ({ default: toast }));
+
+const MessageDetail = (await import('./MessageDetail')).default;
+
+const baseMessage = {
+ id: 'msg-1',
+ accountId: 'acct-1',
+ subject: 'Hello',
+ from: { name: 'Alice', email: '[email protected]' },
+ to: [{ email: '[email protected]' }],
+ date: '2026-09-25T12:00:00.000Z',
+ bodyFull: true,
+};
+
+function renderMessage(message) {
+ return render(
+ <MessageDetail
+ message={message}
+ accounts={[{ id: 'acct-1', name: 'Personal' }]}
+ onBack={() => {}}
+ />,
+ );
+}
+
+// Reads the CSP directive string the iframe's own document head carries —
+// the mechanism that actually blocks the fetch, independent of whether the
+// sanitizer regex also caught the source markup.
+function iframeCsp() {
+ const iframe = document.querySelector('iframe[title="Email content"]');
+ const meta = iframe.contentDocument.querySelector('meta[http-equiv="Content-Security-Policy"]');
+ return meta?.getAttribute('content') || '';
+}
+
+describe('MessageDetail SafeHtmlBody remote content blocking', () => {
+ it('blocks remote images by default via a restrictive CSP and shows the opt-in notice', async () => {
+ renderMessage({
+ ...baseMessage,
+ bodyHtml: '<p>Hi</p><img src="https://example.com/pixel.gif" alt="">',
+ });
+
+ await waitFor(() => expect(iframeCsp()).toContain("default-src 'none'"));
+ expect(iframeCsp()).not.toMatch(/img-src[^;]*https:/);
+ expect(iframeCsp()).toMatch(/img-src\s+data:\s+cid:/);
+ expect(await screen.findByText('Remote images blocked')).toBeInTheDocument();
+ });
+
+ it('blocks a remote background-image and @import in inline/style content', async () => {
+ renderMessage({
+ ...baseMessage,
+ bodyHtml: '<style>@import url(https://evil.example/track.css);</style>'
+ + '<div style="background:url(https://evil.example/pixel.gif)">hi</div>',
+ });
+
+ await waitFor(() => expect(iframeCsp()).toContain("default-src 'none'"));
+ expect(screen.getByText('Remote images blocked')).toBeInTheDocument();
+ });
+
+ it('widens img-src to https: only for this message after "Load remote images" is clicked', async () => {
+ renderMessage({
+ ...baseMessage,
+ bodyHtml: '<img src="https://example.com/pixel.gif" alt="">',
+ });
+
+ await waitFor(() => expect(iframeCsp()).toContain("default-src 'none'"));
+ fireEvent.click(await screen.findByRole('button', { name: 'Load remote images' }));
+
+ await waitFor(() => expect(iframeCsp()).toMatch(/img-src[^;]*https:/));
+ expect(screen.queryByText('Remote images blocked')).not.toBeInTheDocument();
+ });
+
+ it('shows no remote-content notice for a body with only inline data: images and plain formatting', async () => {
+ renderMessage({
+ ...baseMessage,
+ bodyHtml: '<p>Hi <b>Bob</b></p><img src="data:image/png;base64,AAAA" alt="">',
+ });
+
+ await waitFor(() => expect(iframeCsp()).toContain("default-src 'none'"));
+ expect(screen.queryByText('Remote images blocked')).not.toBeInTheDocument();
+ });
+});