Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(mail): 支持阅读外部图片、打开链接和显示参与人头像

Dash8d5d9c475e2b
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-manifest.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-manifest.md
index e00a6ae5a2..9c2ed738eb 100644
--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-manifest.md
+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-manifest.md
@@ -163,6 +163,10 @@ v3 直接用顶层字段声明插件贡献项与自主 Host 能力,不再有 `
邮件插件声明 `mail: true`,调用 Cindy 内置 `cindyMail.register(adapter)`
(version 1),不生成卡片 HTML、不打包公共流程;纯邮件插件不需要 `card`。
阅读邮件可声明 `mailReader:{tool,hosts}`,工具接收 `{url}` 并返回 MailMessage,默认只读。
+返回值可包含 `participantPhotos:[{email,url}]`(最多 64 项):`email` 是精确匹配的小写邮箱,
+`url` 是无用户名、密码和自定义端口的 HTTPS 联系人照片。缺照片或权限时省略,不能阻断阅读。
+旧宿主忽略此可选字段;新版桌面优先显示照片,再回退公开邮箱头像、企业域名图标和首字。
+头像不能代表发件人身份认证;正文外部图片仍需用户单独点击显示。
`mail` 只能省略或写字面量 `true`;声明 `mailReader` 时必须同时有 `mail: true`,
且 `tool` 必须指向本清单 `tools` 中的工具。协议校验与桌面安装校验都会拒绝不完整组合。
支持打开即已读时增加 `mailReader.markRead:true`,读取工具接受可选 `markRead:true`;
diff --git a/apps/desktop/scripts/fixtures/plugin-install-mail/fixture.tsx b/apps/desktop/scripts/fixtures/plugin-install-mail/fixture.tsx
index 6a3a629556..37b21541a4 100644
--- a/apps/desktop/scripts/fixtures/plugin-install-mail/fixture.tsx
+++ b/apps/desktop/scripts/fixtures/plugin-install-mail/fixture.tsx
@@ -3,7 +3,20 @@ import { MailPreviewBody } from '../../../src/renderer/features/right-sidebar/pl
import { GhostInstallConsentHost } from '../../../src/renderer/cindy-brain/GhostInstallConsentHost';
import { GhostCardForm } from '../../../src/renderer/components/chat/GhostCardForm';
import { MailHtmlPreview } from '../../../src/renderer/components/chat/MailHtmlPreview';
+import { MailConversationView } from '../../../src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView';
import { useState } from 'react';
+import previewImage from '../../../resources/icon.png';
+
+function MailAvatarsFixture() {
+ const [opened, setOpened] = useState(false);
+ const message = { accountId: 'fixture-account', messageId: 'fixture-message',
+ from: 'Cindy <[email protected]>', to: 'Alex <[email protected]>, 设计团队 <[email protected]>', cc: '访客 <[email protected]>', bcc: '',
+ subject: '本周设计更新', date: '2026-10-25T09:00:00+13:00', bodyText: '',
+ bodyHtml: `<p>大家好,</p><p>新版邮件阅读界面已准备好,请查看设计预览。</p><img src="${new URL(previewImage, location.href).href}" alt="Preview image" width="120" height="120"><p><a href="https://example.test/details">查看设计说明</a></p>`, attachments: [],
+ participantPhotos: [{ email: '[email protected]', url: 'https://lh3.googleusercontent.com/fixture-contact' }] };
+ return opened ? <MailConversationView mail={message} read={async () => ({ message })} retry={() => {}} openMailbox={null} />
+ : <button onClick={() => setOpened(true)}>Open preview</button>;
+}
function MailTwoViewsFixture() {
const [value, setValue] = useState('<p>First paragraph</p><p>Last paragraph</p>');
@@ -15,6 +28,13 @@ function MailTwoViewsFixture() {
</div>;
}
+function MailReadFixture() {
+ return <section className="p-4">
+ <MailHtmlPreview reading value={`<p>Hello Alex,</p><p>Here is the image from our latest update.</p><img src="${new URL(previewImage, location.href).href}" alt="Preview image" width="160" height="160"><p><a href="https://example.test/details">View details</a></p>`} />
+ <output data-testid="opened-link" hidden />
+ </section>;
+}
+
function MailRefreshFixture() {
const [version, setVersion] = useState(0);
return <>
@@ -36,6 +56,11 @@ function MailEditFixture() {
void mountPage({
host: {
+ openExternal: async (url: string) => {
+ const output = document.querySelector('[data-testid="opened-link"]');
+ if (output) output.textContent = url;
+ return { success: true };
+ },
ghosts: {
onInstallConsentRequest: subscription('installConsent'),
onInstallConsentDismissed: subscription('installDismissed'),
@@ -44,7 +69,11 @@ void mountPage({
},
render: (ctx) => (
<main className="h-screen w-full">
- {ctx.case === 'two-mail-views' ? (
+ {ctx.case === 'participant-avatars' ? (
+ <MailAvatarsFixture />
+ ) : ctx.case === 'read-mail-body' ? (
+ <MailReadFixture />
+ ) : ctx.case === 'two-mail-views' ? (
<MailTwoViewsFixture />
) : ctx.case === 'edit-mail-body' ? (
<MailEditFixture />
diff --git a/apps/desktop/scripts/fixtures/plugin-install-mail/ui-page.mjs b/apps/desktop/scripts/fixtures/plugin-install-mail/ui-page.mjs
index 14d4683496..cd44283d21 100644
--- a/apps/desktop/scripts/fixtures/plugin-install-mail/ui-page.mjs
+++ b/apps/desktop/scripts/fixtures/plugin-install-mail/ui-page.mjs
@@ -1,20 +1,23 @@
+import { readFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+
export default {
name: 'plugin-install-mail',
entry: './fixture.tsx',
viewport: { width: 700, height: 600 },
- real: 'MailPreviewBody provider chooser and unavailable/failed reader states, GhostInstallConsentHost, shared confirmation dialog, buttons and five locales',
+ real: 'MailPreviewBody provider chooser and unavailable/failed reader states, MailHtmlPreview image opt-in and link activation, GhostInstallConsentHost, shared confirmation dialog, buttons and five locales',
notCovered:
- 'Mailbox tools, installer writes, account credentials, mail bodies, native mobile rendering and network connections',
+ 'Mailbox tools, installer writes, account credentials, live mail content, native mobile rendering and external network connections',
stubs: {
'src/renderer/features/right-sidebar/lib/mailPreview':
- 'export async function readMailPreview(){ const c=window.__uiPage.ctx.case; if(c==="no-reader")return {supported:false}; if(c==="not-ready")return {supported:true,error:"MAIL_PROVIDER_NOT_READY"}; if(c==="read-failed")return {supported:true,error:"MAIL_READ_FAILED"}; return {providers:[{id:"root",name:"Mail",namespace:null},{id:"team",name:"Mail for a very long organization name",namespace:"long-organization-identity-example"}]}; }',
+ 'export async function openMailPreview(){} export async function readMailPreview(){ const c=window.__uiPage.ctx.case; if(c==="no-reader")return {supported:false}; if(c==="not-ready")return {supported:true,error:"MAIL_PROVIDER_NOT_READY"}; if(c==="read-failed")return {supported:true,error:"MAIL_READ_FAILED"}; return {providers:[{id:"root",name:"Mail",namespace:null},{id:"team",name:"Mail for a very long organization name",namespace:"long-organization-identity-example"}]}; }',
'src/renderer/features/right-sidebar/registry': 'export function registerTabKind(){} export function getTabKind(){return undefined;}',
'src/renderer/features/right-sidebar/plugins/mail-preview/MailCardBody':
'export function MailCardBody(){return null;}',
- 'src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView':
- 'export function MailConversationView(){return null;}',
},
cases: {
+ 'participant-avatars': { about: 'Real reader with Google contact, public email, domain logo and initials; image endpoints use fixture bytes', viewport: { width: 360, height: 720 } },
+ 'read-mail-body': { about: 'External images require a click; links follow chat navigation', viewport: { width: 360, height: 600 } },
'two-mail-views': { about: 'Typing in either editor updates its peer without iframe navigation or blank paint' },
'edit-mail-body': { about: 'Native whole-body selection, replace, delete, undo, and saved HTML round trip' },
'refresh-mail-body': { about: 'Source updates with identical sanitized HTML must reveal the mail body' },
@@ -31,6 +34,76 @@ export default {
},
async check(page, ui) {
const selected = await page.evaluate(() => window.__uiPage.ctx.case);
+ if (selected === 'participant-avatars') {
+ const imageData = name => 'data:image/png;base64,' + readFileSync(new URL('../../../resources/' + name, import.meta.url)).toString('base64');
+ const hash = createHash('sha256').update('[email protected]').digest('hex');
+ const images = {
+ 'https://lh3.googleusercontent.com/fixture-contact': imageData('companion-preset-avatars/cindy.png'),
+ [`https://gravatar.com/avatar/${hash}?s=64&d=404&r=g`]: imageData('legacy-teammate-avatars/lizi.png'),
+ 'https://icons.duckduckgo.com/ip3/company.example.com.ico': imageData('icon.png'),
+ };
+ const hashes = Object.fromEntries(['[email protected]', '[email protected]', '[email protected]'].map(email =>
+ [email, Array.from(createHash('sha256').update(email).digest())]));
+ await page.evaluate(({ images, hashes }) => {
+ // The isolated harness blocks all off-origin requests and has no
+ // SubtleCrypto. Substitute image bytes at the DOM boundary, retaining
+ // the real component's source selection/load/error handlers. URL and
+ // SHA-256 behavior is separately exercised by MailPreview.test.tsx.
+ if (!crypto.subtle) Object.defineProperty(crypto, 'subtle', { configurable: true, value: {
+ digest: async (_algorithm, bytes) => Uint8Array.from(hashes[new TextDecoder().decode(bytes)]).buffer,
+ } });
+ function substitute(node, value) {
+ if (String(value).startsWith('https://')) {
+ if (images[value]) return images[value];
+ if (String(value).startsWith('https://gravatar.com/')) {
+ queueMicrotask(() => node.dispatchEvent(new Event('error')));
+ return null;
+ }
+ throw new Error('Unexpected avatar endpoint: ' + value);
+ }
+ return value;
+ }
+ const original = Element.prototype.setAttribute;
+ Element.prototype.setAttribute = function (name, value) {
+ const mapped = this instanceof HTMLImageElement && name === 'src' ? substitute(this, value) : value;
+ if (mapped !== null) return original.call(this, name, mapped);
+ };
+ const src = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'src');
+ Object.defineProperty(HTMLImageElement.prototype, 'src', { ...src, set(value) {
+ const mapped = substitute(this, value);
+ if (mapped !== null) src.set.call(this, mapped);
+ } });
+ }, { images, hashes });
+ await page.getByRole('button', { name: 'Open preview' }).click();
+ await page.waitForFunction(() => {
+ const images = [...document.querySelectorAll('section img')];
+ return images.length === 3 && images.every(img => img.complete && img.naturalWidth > 0 && !img.classList.contains('invisible'));
+ });
+ await ui.capture('avatars');
+ await page.locator('main').evaluate(node => { node.style.width = '320px'; });
+ await ui.capture('avatars-narrow-320');
+ await page.locator('main').evaluate(node => { node.style.width = ''; });
+ await page.getByRole('button', { name: await ui.t('mailReader.showExternalImages') }).click();
+ await page.locator('iframe[aria-busy="false"]').waitFor();
+ await page.waitForFunction(() => document.querySelector('iframe').contentDocument.querySelector('img').naturalWidth > 0);
+ await ui.capture('avatars-and-images');
+ return;
+ }
+ if (selected === 'read-mail-body') {
+ await page.locator('iframe[aria-busy="false"]').waitFor();
+ const frame = page.frameLocator('iframe');
+ if (await frame.locator('img').getAttribute('src') !== null) throw new Error('Image requested before consent');
+ await ui.capture('images-blocked');
+ await page.getByRole('button', { name: await ui.t('mailReader.showExternalImages') }).click();
+ await page.locator('iframe[aria-busy="false"]').waitFor();
+ await frame.getByText('Hello Alex,', { exact: true }).waitFor();
+ await frame.getByRole('link', { name: 'View details' }).click();
+ if (await page.getByTestId('opened-link').textContent() !== 'https://example.test/details') throw new Error('Mail link was not delegated to the host');
+ await page.waitForFunction(() => !!document.querySelector('iframe').contentDocument.querySelector('img').getAttribute('src'));
+ await page.waitForFunction(() => document.querySelector('iframe').contentDocument.querySelector('img').naturalWidth > 0);
+ await ui.capture('images-visible');
+ return;
+ }
if (selected === 'two-mail-views') {
await page.waitForFunction(() => document.querySelectorAll('iframe[aria-busy="false"]').length === 2);
await page.evaluate(() => {
diff --git a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
index fa2c4d85dd..9adeae26f3 100644
--- a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
+++ b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
@@ -1,15 +1,23 @@
-import { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { Maximize2, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { mailInlineDocument, safeMailDocument, validMailImageUrl } from '@cindy/maker-shared/mail-text-edit';
+import { externalMailImageUrl, hasMailExternalImages, mailInlineDocument, safeMailDocument, validMailImageUrl } from '@cindy/maker-shared/mail-text-edit';
+import { Button } from '@/components/ui/button';
+import { useSidebarTargetSessionId } from '@/features/cc-agent/embeddedSessionNavigation';
+import { useChatSessionFile } from './ChatSessionFileContext';
+import { activateMessageUrl } from './useOpenWithMenu';
import { followMailPreviewTheme } from './mailPreviewAppearance';
import { mailBodySerializer } from './mailBodyEditing';
export const safeMailHtml = safeMailDocument;
type PreviewProps = { value: string; images?: { cid: string; url: string }[]; disabled?: boolean; reading?: boolean; onEnlarge?: () => void; onChange?: (html: string, text: string) => void };
-function PreviewFrame({ value, images = [], enlarged = false, reading = false, disabled, onChange }: PreviewProps & { enlarged?: boolean }) {
+function PreviewFrame({ value, images = [], enlarged = false, reading = false, disabled, onChange, allowExternalImages = false }: PreviewProps & { enlarged?: boolean; allowExternalImages?: boolean }) {
+ const { t } = useTranslation();
+ const { sessionId } = useChatSessionFile();
+ const sidebarTargetSessionId = useSidebarTargetSessionId(sessionId);
const frame = useRef<HTMLIFrameElement>(null);
+ const boundDocument = useRef<Document | undefined>(undefined);
const stopTheme = useRef<(() => void) | undefined>(undefined);
const bodyResize = useRef<ResizeObserver | undefined>(undefined);
useLayoutEffect(() => () => { stopTheme.current?.(); bodyResize.current?.disconnect(); }, []);
@@ -18,12 +26,12 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, d
if (value !== model.current.emitted) model.current = { emitted: value, received: value, revision: model.current.revision + 1 };
else model.current.received = value;
}
- const current = useRef({ disabled, onChange, images });
- current.current = { disabled, onChange, images };
+ const current = useRef({ disabled, onChange, images, reading, sidebarTargetSessionId, t });
+ current.current = { disabled, onChange, images, reading, sidebarTargetSessionId, t };
const revision = model.current.revision;
// Keep the browsing context alive in both views. Other-view autosaves update
// its sanitized DOM before paint rather than navigating through a blank page.
- const [html] = useState(() => mailInlineDocument(value, images));
+ const [html] = useState(() => mailInlineDocument(value, images, allowExternalImages));
const ready = useRef(false);
const serialize = useRef<ReturnType<typeof mailBodySerializer> | undefined>(undefined);
const fit = () => {
@@ -46,6 +54,10 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, d
const image = current.current.images.find(i => i.cid === el.getAttribute('data-cindy-mail-cid'));
if (image && validMailImageUrl(image.url)) el.src = image.url;
}
+ if (allowExternalImages) for (const el of doc.querySelectorAll<HTMLImageElement>('img[data-cindy-mail-external-src]')) {
+ const url = externalMailImageUrl(el.getAttribute('data-cindy-mail-external-src') || '');
+ if (url && el.getAttribute('src') !== url) el.src = url;
+ }
};
const applySource = (replaceContents = true) => {
const doc = frame.current?.contentDocument;
@@ -53,7 +65,7 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, d
const scroll = [doc.documentElement.scrollTop, doc.body.scrollTop];
stopTheme.current?.();
if (replaceContents) {
- const next = new DOMParser().parseFromString(mailInlineDocument(model.current.emitted, current.current.images), 'text/html');
+ const next = new DOMParser().parseFromString(mailInlineDocument(model.current.emitted, current.current.images, allowExternalImages), 'text/html');
for (const [target, source] of [[doc.documentElement, next.documentElement], [doc.head, next.head], [doc.body, next.body]]) {
for (const attr of [...target.attributes]) target.removeAttribute(attr.name);
for (const attr of source.attributes) target.setAttribute(attr.name, attr.value);
@@ -82,7 +94,6 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, d
}); observer.observe(frame.current);
return () => observer.disconnect();
}, [enlarged, reading]);
- const { t } = useTranslation();
// Hide only the initial load. Synchronized content never hides/remounts it.
return <iframe ref={frame} title={t('chat.ghostCall.mailPreview')} sandbox="allow-same-origin" scrolling={reading ? 'no' : undefined}
className="block w-full border-0" aria-busy="true"
@@ -90,8 +101,10 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, d
onLoad={() => {
const doc = frame.current?.contentDocument;
if (!doc?.body || !doc.head) return;
+ if (boundDocument.current === doc) return;
+ boundDocument.current = doc;
ready.current = true;
- applySource(mailInlineDocument(model.current.emitted, current.current.images) !== html);
+ applySource(mailInlineDocument(model.current.emitted, current.current.images, allowExternalImages) !== html);
let composing = false;
const update = () => {
if (composing || current.current.disabled || !current.current.onChange) return;
@@ -103,7 +116,17 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, d
doc.addEventListener('compositionstart', () => { composing = true; });
doc.addEventListener('compositionend', () => { composing = false; update(); });
doc.addEventListener('input', update);
- doc.addEventListener('click', event => { if ((event.target as Element).closest('a')) event.preventDefault(); });
+ const openLink = (event: MouseEvent) => {
+ const link = (event.target as Element).closest('a');
+ if (!link) return;
+ event.preventDefault();
+ const href = link.getAttribute('href');
+ if (current.current.reading && !current.current.onChange && href && /^(https?:|mailto:)/i.test(href)) {
+ void activateMessageUrl(event, current.current.sidebarTargetSessionId, href, current.current.t);
+ }
+ };
+ doc.addEventListener('click', openLink);
+ doc.addEventListener('auxclick', event => { if (event.button === 1) openLink(event); });
doc.addEventListener('drop', event => event.preventDefault());
doc.addEventListener('paste', event => {
if (!current.current.onChange || current.current.disabled) return;
@@ -120,8 +143,18 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, d
export function MailHtmlPreview(props: PreviewProps) {
const [open, setOpen] = useState(false);
+ const [externalImages, setExternalImages] = useState({ source: props.value, allowed: false });
+ if (externalImages.source !== props.value) setExternalImages({ source: props.value, allowed: false });
+ const hasExternalImages = useMemo(() => props.reading && !props.onChange && hasMailExternalImages(props.value), [props.reading, props.onChange, props.value]);
+ const allowExternalImages = Boolean(hasExternalImages && externalImages.source === props.value && externalImages.allowed);
const { t } = useTranslation();
- if (props.reading) return <PreviewFrame {...props} />;
+ if (props.reading) return <>
+ {hasExternalImages && !allowExternalImages && <div className="mb-3">
+ <Button variant="secondary" size="sm" onClick={() => setExternalImages({ source: props.value, allowed: true })}>{t('mailReader.showExternalImages')}</Button>
+ </div>}
+ {/* A fresh document is required: removing a CSP meta cannot relax its policy. */}
+ <PreviewFrame key={String(allowExternalImages)} {...props} allowExternalImages={allowExternalImages} />
+ </>;
return <div className="w-full min-w-0 py-2">
<div className="mb-1 flex justify-end gap-2">
<button type="button" title={t('chat.ghostCall.mailEnlarge')} aria-label={t('chat.ghostCall.mailEnlarge')}
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
index dd216ad744..9283fca4f5 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
@@ -3,10 +3,82 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest';
import { MailHtmlPreview, safeMailHtml } from '../MailHtmlPreview';
import { GhostCardForm } from '../GhostCardForm';
+import { ChatSessionFileProvider } from '../ChatSessionFileContext';
+import { openUrlInSidebarBrowser } from '@/features/right-sidebar/lib/openInSidebarBrowser';
+import { _resetLinkOpenPreferenceForTests } from '@/hooks/useLinkOpenPreference';
import { mailInlineBindingScript, mailInlineRefreshScript } from '@cindy/maker-shared/mail-text-edit';
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('../ImageLightbox', () => ({ ImageLightbox: ({ src }: { src: string }) => <img alt="attachment-preview" src={src} /> }));
-afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+vi.mock('@/features/right-sidebar/lib/openInSidebarBrowser', () => ({ openUrlInSidebarBrowser: vi.fn(async () => undefined) }));
+vi.mock('@/features/right-sidebar/lib/mailPreview', () => ({ readMailPreview: vi.fn(async () => ({ supported: false })) }));
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.clearAllMocks(); localStorage.clear(); _resetLinkOpenPreferenceForTests(); });
+
+// Unit regressions: the reader previously had no opt-in and swallowed all links.
+// Exercise the actual iframe event listeners and shared chat navigation policy.
+it('loads external images only after a click and resets consent when changing mail', () => {
+ const first = '<p>First</p><img src="https://images.example.test/first.png">';
+ const second = '<p>Second</p><img src="https://images.example.test/second.png">';
+ const view = render(<MailHtmlPreview value={first} reading />);
+ const load = () => {
+ const frame = screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement;
+ const doc = frame.contentDocument!;
+ doc.open(); doc.write(frame.srcdoc); doc.close(); fireEvent.load(frame);
+ return { frame, doc };
+ };
+ const blocked = load();
+ expect(blocked.doc.querySelector('img')!.hasAttribute('src')).toBe(false);
+ fireEvent.click(screen.getByRole('button', { name: 'mailReader.showExternalImages' }));
+ const allowed = load();
+ expect(allowed.frame).not.toBe(blocked.frame);
+ expect(allowed.frame.getAttribute('sandbox')).toBe('allow-same-origin');
+ expect(allowed.doc.querySelector('img')!.getAttribute('src')).toBe('https://images.example.test/first.png');
+ expect(allowed.doc.querySelector('img')!.getAttribute('referrerpolicy')).toBe('no-referrer');
+ expect(screen.queryByRole('button', { name: 'mailReader.showExternalImages' })).toBeNull();
+ view.rerender(<MailHtmlPreview value={second} reading />);
+ expect(load().doc.querySelector('img')!.hasAttribute('src')).toBe(false);
+ view.rerender(<MailHtmlPreview value={first} reading />);
+ expect(screen.getByRole('button', { name: 'mailReader.showExternalImages' })).toBeTruthy();
+ view.rerender(<MailHtmlPreview value='<img src="data:image/png;base64,YQ==">' reading />);
+ expect(screen.queryByRole('button', { name: 'mailReader.showExternalImages' })).toBeNull();
+ view.rerender(<MailHtmlPreview value={first} onChange={vi.fn()} />);
+ expect(screen.queryByRole('button', { name: 'mailReader.showExternalImages' })).toBeNull();
+});
+
+it('opens reader links with chat preferences and modifiers but never navigates the iframe or editor', async () => {
+ const openExternal = vi.fn(async () => ({ success: true }));
+ vi.stubGlobal('electronAPI', { openExternal });
+ localStorage.setItem('chat.webLinkOpenPreference', 'sidebar');
+ _resetLinkOpenPreferenceForTests();
+ const value = '<a href="https://example.test/page"><b>Open</b></a><a href="javascript:alert(1)">Unsafe</a>';
+ const view = render(<ChatSessionFileProvider value={{ sessionId: 'mail-task', workingDir: '', origin: { kind: 'local' } }}>
+ <MailHtmlPreview value={value} reading />
+ </ChatSessionFileProvider>);
+ const frame = screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement;
+ const doc = frame.contentDocument!;
+ doc.open(); doc.write(frame.srcdoc); doc.close(); fireEvent.load(frame);
+ const click = (type: string, init: MouseEventInit = {}) => {
+ const event = new MouseEvent(type, { bubbles: true, cancelable: true, ...init });
+ doc.querySelector('b')!.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(true);
+ };
+ await act(async () => { click('click'); });
+ expect(openUrlInSidebarBrowser).toHaveBeenCalledWith('mail-task', 'https://example.test/page');
+ expect(openExternal).not.toHaveBeenCalled();
+ for (const modifiers of [{ ctrlKey: true }, { metaKey: true }, { shiftKey: true }]) {
+ await act(async () => { click('click', modifiers); });
+ }
+ await act(async () => { click('auxclick', { button: 1 }); });
+ expect(openExternal).toHaveBeenCalledTimes(4);
+ expect(openExternal).toHaveBeenLastCalledWith('https://example.test/page');
+ expect(doc.querySelectorAll('a')[1].hasAttribute('href')).toBe(false);
+ await act(async () => { fireEvent.click(doc.querySelectorAll('a')[1]); });
+ expect(openExternal).toHaveBeenCalledTimes(4);
+ view.rerender(<ChatSessionFileProvider value={{ sessionId: 'mail-task', workingDir: '', origin: { kind: 'local' } }}>
+ <MailHtmlPreview value={value} reading onChange={vi.fn()} />
+ </ChatSessionFileProvider>);
+ await act(async () => { click('click'); });
+ expect(openUrlInSidebarBrowser).toHaveBeenCalledTimes(1);
+});
// Chromium can expose a document before the srcdoc parser creates its body.
// Account/CID updates during that interval must wait for load, then apply the
// latest source without crashing the whole conversation reader.
diff --git a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
index 79b0fb1668..3fe65fd39b 100644
--- a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
+++ b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
@@ -79,7 +79,7 @@ export async function openUrlByPreference(
/** Identical activation for user URLs, assistant Markdown and keyboard/middle clicks. */
export async function activateMessageUrl(
- event: MouseEvent<HTMLElement>,
+ event: Pick<MouseEvent<HTMLElement>, 'preventDefault' | 'stopPropagation' | 'shiftKey' | 'metaKey' | 'ctrlKey' | 'button'>,
sessionId: string | undefined,
url: string,
t: TFunction,
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView.tsx
index c6d9386af2..a8f723a7c9 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView.tsx
@@ -6,7 +6,11 @@ import { mailPreviewImages } from '@cindy/maker-shared/ghost-card-form';
import { MAIL_PAPER_COLOR } from '@cindy/maker-shared/mail-text-edit';
import { GhostCardForm } from '@/components/chat/GhostCardForm';
import { MailHtmlPreview } from '@/components/chat/MailHtmlPreview';
+import { useChatSessionFile } from '@/components/chat/ChatSessionFileContext';
+import { UserMessageUrlLink } from '@/components/chat/UserMessageUrlLink';
+import { findLinkifyMatches } from '@/components/chat/userMessageLinkify';
import { Button } from '@/components/ui/button';
+import { MailParticipants } from './MailParticipant';
type Props = {
mail: MailMessage;
@@ -19,15 +23,25 @@ function MessageBody({ mail }: { mail: MailMessage }) {
const { t } = useTranslation();
const fields = mailMessageFields(mail, key => t(`mailReader.${key}`));
const values = Object.fromEntries(fields.map(f => [f.name, f.value]));
+ const { sessionId } = useChatSessionFile();
+ const plainBody: ReactNode[] = [];
+ if (!mail.bodyHtml) {
+ let cursor = 0;
+ for (const match of findLinkifyMatches(mail.bodyText).filter(match => match.kind === 'url')) {
+ plainBody.push(mail.bodyText.slice(cursor, match.index), <UserMessageUrlLink key={match.index} url={match.text} sessionId={sessionId} />);
+ cursor = match.index + match.length;
+ }
+ plainBody.push(mail.bodyText.slice(cursor));
+ }
return <>
{mail.markReadFailed && <p role="status" className="mb-2 text-12 text-muted-foreground">{t('mailReader.markReadFailed')}</p>}
<div className="mb-3 space-y-1 border-b border-border pb-3 text-12 text-muted-foreground">
{fields.filter(f => f.kind === 'recipients' && f.value.trim()).map(f => <div key={f.name} className="flex gap-2">
- <span className="shrink-0">{f.label}</span><span className="min-w-0 break-words">{f.value}</span>
+ <span className="shrink-0 pt-0.5">{f.label}</span><MailParticipants value={f.value} photos={mail.participantPhotos} />
</div>)}
</div>
{mail.bodyHtml ? <MailHtmlPreview value={mail.bodyHtml} images={mailPreviewImages(values)} reading />
- : <div className="whitespace-pre-wrap break-words p-1 text-14 leading-relaxed text-foreground">{mail.bodyText}</div>}
+ : <div className="whitespace-pre-wrap break-words p-1 text-14 leading-relaxed text-foreground">{plainBody}</div>}
<GhostCardForm fields={fields.filter(f => f.kind === 'mail-attachments')} disabled={false} readOnly onChange={() => {}} />
</>;
}
@@ -67,7 +81,7 @@ function MessageRow({ summary, initial, selected, initiallyExpanded, accountId,
{expanded ? <ChevronDown className="mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground" /> : <ChevronRight className="mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
<span className="min-w-0 flex-1">
<span className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
- <span className="min-w-0 break-words text-13 font-medium text-foreground">{from || t('mailReader.title')}</span>
+ <span className="min-w-0 text-13 font-medium text-foreground"><MailParticipants value={from || t('mailReader.title')} photos={message?.participantPhotos} compact={false} /></span>
<span className="flex items-center gap-2 text-12 text-muted-foreground">
{selected && <span>{t('mailReader.currentMessage')}</span>}
{dateText && <time dateTime={validDate ? date.toISOString() : undefined} title={dateText}>{formatted}</time>}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailParticipant.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailParticipant.tsx
new file mode 100644
index 0000000000..3364ce4965
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailParticipant.tsx
@@ -0,0 +1,67 @@
+import { useEffect, useState } from 'react';
+import { ghostCardRecipients } from '@cindy/maker-shared/ghost-card-form';
+import { mailParticipantEmail, type MailMessage } from '@cindy/maker-shared/mail-message';
+
+// A mailbox provider's logo is not the identity of everyone using its service.
+const publicMailDomains = new Set(('gmail.com googlemail.com outlook.com hotmail.com live.com msn.com ' +
+ 'icloud.com me.com mac.com yahoo.com yahoo.co.uk yahoo.co.jp ymail.com rocketmail.com aol.com ' +
+ 'qq.com foxmail.com 163.com 126.com yeah.net sina.com sina.cn sohu.com aliyun.com ' +
+ 'proton.me protonmail.com pm.me tutanota.com tuta.com fastmail.com hey.com mail.com gmx.com gmx.net web.de').split(' '));
+
+function domainIcon(email: string): string | undefined {
+ const domain = email.split('@')[1];
+ if (!domain || publicMailDomains.has(domain) || /^(yahoo|hotmail|outlook|live|gmx)\./.test(domain) ||
+ /(?:^|\.)(?:localhost|local|internal|test|invalid|example)$/.test(domain) || /\.{2}|^-|-$|\.-|-\./.test(domain)) return undefined;
+ // Fixed public image origin: never contact a sender-controlled website directly.
+ return `https://icons.duckduckgo.com/ip3/${encodeURIComponent(domain)}.ico`;
+}
+
+function Avatar({ email, label, photo, compact }: { email?: string; label: string; photo?: string; compact: boolean }) {
+ const [publicPhoto, setPublicPhoto] = useState<string>();
+ const [failed, setFailed] = useState<string[]>([]);
+ const [loaded, setLoaded] = useState<string>();
+ const contact = photo && !failed.includes(photo) ? photo : undefined;
+ useEffect(() => {
+ if (!email || contact) return;
+ let active = true;
+ // Gravatar receives only the normalized email hash, never the raw address.
+ void Promise.resolve().then(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(email))).then(bytes => {
+ const hash = Array.from(new Uint8Array(bytes), b => b.toString(16).padStart(2, '0')).join('');
+ if (active) setPublicPhoto(`https://gravatar.com/avatar/${hash}?s=64&d=404&r=g`);
+ }).catch(() => { if (active) setPublicPhoto(''); });
+ return () => { active = false; };
+ }, [email, contact]);
+ const domain = email ? domainIcon(email) : undefined;
+ const src = contact || (publicPhoto && !failed.includes(publicPhoto) ? publicPhoto :
+ publicPhoto !== undefined && domain && !failed.includes(domain) ? domain : undefined);
+ useEffect(() => {
+ if (!src || loaded === src) return;
+ const timer = setTimeout(() => setFailed(previous => [...previous, src]), 4000);
+ return () => clearTimeout(timer);
+ }, [src, loaded]);
+ const initials = Array.from(label.replace(/^[\s"']+/, '')).slice(0, 1).join('').toUpperCase() || '?';
+ return <span aria-hidden="true" className={`relative inline-flex shrink-0 items-center justify-center overflow-hidden bg-muted text-muted-foreground ${compact ? 'h-5 w-5 text-11' : 'h-8 w-8 text-13'} ${src === domain && domain ? 'rounded-md' : 'rounded-full'}`}>
+ {initials}
+ {src && <img key={src} src={src} alt="" referrerPolicy="no-referrer" draggable={false}
+ className={`absolute inset-0 h-full w-full ${src === domain ? 'object-contain p-0.5' : 'object-cover'} ${loaded === src ? '' : 'invisible'}`}
+ onLoad={() => setLoaded(src)} onError={() => setFailed(previous => [...previous, src])} />}
+ </span>;
+}
+
+/** Shared sender/recipient presentation; the full address remains visible on hover. */
+export function MailParticipants({ value, photos, compact = true }: {
+ value: string; photos?: MailMessage['participantPhotos']; compact?: boolean;
+}) {
+ return <span className="inline-flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1.5">
+ {ghostCardRecipients(value).map(({ address, label }, index) => {
+ const email = mailParticipantEmail(address);
+ const photo = photos?.find(item => item.email === email)?.url;
+ return <span key={`${address}:${index}`} title={address} className="inline-flex min-w-0 max-w-full items-center gap-1.5">
+ <Avatar key={`${email}:${photo}`} email={email} label={label} photo={photo} compact={compact} />
+ <span className="min-w-0 break-words [overflow-wrap:anywhere]">{compact ? address : label}
+ {!compact && email && email !== label && <span className="block text-12 font-normal text-muted-foreground">{email}</span>}
+ </span>
+ </span>;
+ })}
+ </span>;
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailPreview.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailPreview.test.tsx
index a94628fb78..2117de1e0f 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailPreview.test.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailPreview.test.tsx
@@ -1,15 +1,14 @@
// @vitest-environment jsdom
import { cleanup, render, screen, act, fireEvent } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
-import type { ReactNode } from 'react';
import type { GhostCardFormField } from '@cindy/maker-shared/ghost-card-form';
+import { createHash } from 'node:crypto';
const h = vi.hoisted(() => ({ read: vi.fn(), owner: 1 }));
vi.mock('../../lib/mailPreview', () => ({ readMailPreview: h.read }));
vi.mock('../../registry', () => ({ registerTabKind: () => {} }));
vi.mock('@/contexts/dataOwnerGeneration', () => ({ getDataOwnerGeneration: () => h.owner, isDataOwnerGenerationCurrent: (o: number) => o === h.owner }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, args?: { from?: string; count?: number }) => args ? key + ' ' + (args.from ?? args.count) : key }) }));
vi.mock('@/components/chat/GhostCardForm', () => ({ GhostCardForm: ({ fields, readOnly }: { fields: GhostCardFormField[]; readOnly?: boolean }) => <div data-testid="body" data-readonly={readOnly}>{fields.find(f => f.name === 'body')?.value}</div> }));
-vi.mock('@/components/chat/ChatSessionFileContext', () => ({ ChatSessionFileProvider: ({ children }: { children: ReactNode }) => children }));
vi.mock('@/components/chat/GhostToolCard', () => ({ MailCardEditor: ({ html, callId }: { html: string; callId: string }) => <div data-testid="editor" data-call-id={callId}>{readMailCard(html)?.fields.find(f => f.name === 'body')?.value}</div> }));
import { MailPreviewBody } from './index';
import { MailCardBody } from './MailCardBody';
@@ -18,6 +17,48 @@ import { readMailCard } from '@cindy/maker-shared/ghost-card-form';
import { ingestCardPush } from '@/cindy-brain/ghostCardStore';
const ctx = { tabId: 'tab', sessionId: 'a', workdir: '', remoteHostId: null, deviceLinkDeviceId: null, patchState() {}, onVisibilityChange() {}, setCloseInterceptor: () => () => {} };
const mail = (bodyText: string) => ({ accountId: 'account', messageId: bodyText, from: 'sender', to: 'to', cc: '', bcc: '', subject: 'Subject', date: '', bodyText, bodyHtml: '', attachments: [] });
+// Integration through the reader: photo failure must advance exactly once to
+// public email/domain/initial fallbacks, without sending a raw email to the CDN.
+it('shows sender and recipient avatars and falls back without requesting public mailbox logos', async () => {
+ vi.stubGlobal('crypto', { subtle: { digest: async (_algorithm: string, bytes: Uint8Array) => Uint8Array.from(createHash('sha256').update(bytes).digest()).buffer } });
+ const photo = 'https://lh3.googleusercontent.com/contact-photo';
+ h.read.mockResolvedValue({ message: { ...mail('Readable'), from: 'Person <[email protected]>', to: 'Other <[email protected]>',
+ participantPhotos: [{ email: '[email protected]', url: photo }] } });
+ const view = render(<MailPreviewBody state={{ url: 'https://mail.example/a' }} ctx={ctx} />);
+ await act(async () => {});
+ const sender = () => view.container.querySelector<HTMLImageElement>('img[src="' + photo + '"]');
+ expect(sender()).not.toBeNull();
+ expect(sender()!.getAttribute('referrerpolicy')).toBe('no-referrer');
+ await act(async () => { fireEvent.error(sender()!); });
+ const hash = createHash('sha256').update('[email protected]').digest('hex');
+ const publicImage = view.container.querySelector<HTMLImageElement>(`img[src*="${hash}"]`)!;
+ expect(publicImage.src).toBe(`https://gravatar.com/avatar/${hash}?s=64&d=404&r=g`);
+ await act(async () => { fireEvent.error(publicImage); });
+ const logo = view.container.querySelector('img[src*="icons.duckduckgo.com"]')!;
+ expect(logo.getAttribute('src')).toBe('https://icons.duckduckgo.com/ip3/company.example.com.ico');
+ await act(async () => { fireEvent.error(logo); });
+ const recipient = view.container.querySelector('img')!;
+ expect(recipient.getAttribute('src')).toContain('gravatar.com/avatar/');
+ await act(async () => { fireEvent.error(recipient); });
+ expect(view.container.querySelector('img')).toBeNull();
+ expect(screen.getByText('Readable')).toBeTruthy();
+ expect(screen.getByText('P')).toBeTruthy();
+ expect(screen.getByText('O')).toBeTruthy();
+});
+// Unit: plain-text mail previously had no clickable URLs. Only web URLs may
+// become actions; local paths and task deep links from senders remain text.
+it('makes plain-text mail URLs clickable without interpreting other content', async () => {
+ const openExternal = vi.fn(async () => ({ success: true }));
+ vi.stubGlobal('electronAPI', { openExternal });
+ h.read.mockResolvedValue({ message: mail('Details: https://example.test/page.\n/private/file.png <b>literal</b>') });
+ render(<MailPreviewBody state={{ url: 'https://mail.example/a' }} ctx={ctx} />);
+ await act(async () => {});
+ const link = screen.getByRole('link', { name: 'https://example.test/page' });
+ expect(screen.getAllByRole('link')).toHaveLength(1);
+ expect(link.parentElement!.textContent).toBe('Details: https://example.test/page.\n/private/file.png <b>literal</b>');
+ await act(async () => { fireEvent.click(link); });
+ expect(openExternal).toHaveBeenCalledExactlyOnceWith('https://example.test/page');
+});
// Unit regression: a remote draft binding must not replace the readable mail
// with the local-only editor. Existing link tests only exercised local tasks.
it('keeps remote drafts readable and preserves the mailbox link', async () => {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index eb03ab5c97..adcf3fe2b3 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6,6 +6,7 @@
"button": "Use Original File"
},
"mailReader": {
+ "showExternalImages": "Show External Images",
"markReadFailed": "Could not sync read status. Check mailbox authorization and reopen this email.",
"title": "Mail",
"openMailbox": "Open in mailbox",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a53ff7f519..da8fc50e03 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6,6 +6,7 @@
"button": "元のファイルを使用"
},
"mailReader": {
+ "showExternalImages": "外部画像を表示",
"markReadFailed": "既読状態を同期できませんでした。メールボックスの認証を確認して開き直してください。",
"title": "メール",
"openMailbox": "メールボックスで開く",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b926f5632e..28504fced5 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6,6 +6,7 @@
"button": "원본 파일 사용"
},
"mailReader": {
+ "showExternalImages": "외부 이미지 표시",
"markReadFailed": "읽음 상태를 동기화하지 못했습니다. 메일함 인증을 확인하고 다시 여세요.",
"title": "메일",
"openMailbox": "메일함에서 열기",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 215d56cdcb..495a27b1ff 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6,6 +6,7 @@
"button": "使用原文件"
},
"mailReader": {
+ "showExternalImages": "显示外部图片",
"markReadFailed": "未能同步已读状态,请检查邮箱授权后重新打开。",
"title": "邮件",
"openMailbox": "在邮箱中打开",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 0e823f9a27..5811229e12 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -6,6 +6,7 @@
"button": "使用原始檔案"
},
"mailReader": {
+ "showExternalImages": "顯示外部圖片",
"markReadFailed": "未能同步已讀狀態,請檢查信箱授權後重新開啟。",
"title": "郵件",
"openMailbox": "在信箱中開啟",
diff --git a/apps/desktop/src/shared/__tests__/mailMessage.test.ts b/apps/desktop/src/shared/__tests__/mailMessage.test.ts
index 7f163d6217..08ed975359 100644
--- a/apps/desktop/src/shared/__tests__/mailMessage.test.ts
+++ b/apps/desktop/src/shared/__tests__/mailMessage.test.ts
@@ -63,3 +63,15 @@ it('drops invalid history without losing the selected message or accepting dupli
expect(parsed?.conversationUnavailable).toBe(true);
}
});
+// Provider photo metadata is optional: invalid images must not lose the mail or
+// introduce file/script/custom-protocol access in the reader (including peers).
+it('keeps only bounded, normalized email photos with credential-free HTTPS URLs', () => {
+ const mail = { accountId: 'a', messageId: 'm', from: '', to: '', cc: '', bcc: '', subject: '', date: '', bodyText: 'selected', bodyHtml: '', attachments: [] };
+ const photo = { email: '[email protected]', url: 'https://photos.example.test/photo.png' };
+ const invalid = ['file:///secret.png', 'javascript:alert(1)', 'http://photos.example.test/a', 'https://user:[email protected]/a', 'https://photos.example.test:123/a'];
+ const parsed = parseMailMessage({ ...mail, participantPhotos: [photo, ...invalid.map(url => ({ ...photo, url })), { ...photo, email: 'Not an email' }] });
+ expect(parsed?.participantPhotos).toEqual([photo]);
+ expect(parsed?.bodyText).toBe('selected');
+ expect(parseMailMessage(mail)?.participantPhotos).toBeUndefined();
+ expect(parseMailMessage({ ...mail, participantPhotos: Array(100).fill(photo) })?.participantPhotos).toHaveLength(64);
+});
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 01f3750bc2..e262e3dec8 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -3180,6 +3180,16 @@ Restored inactive tabs and a hidden sidebar must not mark mail read merely by mo
Mark only the successfully resolved, visibly opened message, never the whole thread or drafts. A failed
mark must retain the body and return `markReadFailed:true` for a non-blocking notice.
It returns `MailMessage` (maker-shared/mail-message).
+Optional `participantPhotos:[{email,url}]` supplies exact normalized-email contact
+photos (at most 64, credential-free HTTPS URLs). Invalid photo entries are discarded
+without dropping the message. Old providers omit this field; old clients ignore it.
+It travels in the existing message response/resource with no new IPC or permission.
+Desktop uses it before Gravatar (SHA-256 normalized email), a fixed DuckDuckGo domain
+favicon endpoint for non-public mailbox domains, and initials. External avatars use
+no referrer and bounded load fallbacks; they do not enable remote images in the body.
+Domain icons are presentation, not authenticated sender identity. Other clients may
+continue displaying addresses alone. Provider contact enrichment must remain optional
+when new contact scopes are missing; Gmail bounds its lookup budget and account cache.
Credentials and MIME parsing remain with the provider. Cindy validates the data
and reuses its inert HTML/CID/recipient renderers for delivered mail. Multiple
matching providers/accounts cannot silently select the first. Host setup metadata
diff --git a/packages/maker-shared/src/__tests__/ghostCardForm.test.ts b/packages/maker-shared/src/__tests__/ghostCardForm.test.ts
index ac99bdbc7f..2d7ff4c768 100644
--- a/packages/maker-shared/src/__tests__/ghostCardForm.test.ts
+++ b/packages/maker-shared/src/__tests__/ghostCardForm.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { parse, type DefaultTreeAdapterTypes } from 'parse5';
-import { applyMailInlineEdits, mailInlineDocument, mailInlineRuns, mailTextParagraphs, safeMailDocument } from '../mailTextEdit';
+import { applyMailInlineEdits, hasMailExternalImages, mailInlineDocument, mailInlineRuns, mailTextParagraphs, safeMailDocument } from '../mailTextEdit';
import {
parseGhostCardForm,
parseGhostCardFormValues,
@@ -37,6 +37,26 @@ describe("declarative card forms", () => {
expect(csp.attrs.find(a => a.name === 'content')?.value.split(';').map(s => s.trim())).toContain('img-src data: cindy-media:');
expect(applyMailInlineEdits(source, {})!.html).toBe(source);
});
+ // Unit: opt-in adds only validated image requests; it must not enable scripts,
+ // CSS tracking, forged attributes or local-file access in either client.
+ it('allows external image sources only with explicit consent while retaining the mail sandbox', () => {
+ const source = '<img src="https://images.example.test/a" onerror="evil()" referrerpolicy="unsafe-url"><img src="http://images.example.test/b"><img src="//images.example.test/c"><img src="file:///private/photo.png"><img src="javascript:evil()"><img src="https://user:[email protected]/d"><script>evil()</script><style>@import "https://images.example.test/style";p{background:url(https://images.example.test/bg)}</style>';
+ expect(hasMailExternalImages(source)).toBe(true);
+ expect(hasMailExternalImages('<template><img src="https://images.example.test/a"></template><img src="cid:photo">')).toBe(false);
+ const nodes = elements(parse(mailInlineDocument(source, [], true)));
+ const images = nodes.filter(n => n.tagName === 'img');
+ expect(images.every(n => !n.attrs.some(a => a.name === 'src'))).toBe(true);
+ expect(images.map(n => n.attrs.find(a => a.name === 'data-cindy-mail-external-src')?.value)).toEqual([
+ 'https://images.example.test/a', 'http://images.example.test/b', 'https://images.example.test/c', undefined, undefined, undefined,
+ ]);
+ expect(images.slice(0, 3).every(n => n.attrs.some(a => a.name === 'referrerpolicy' && a.value === 'no-referrer'))).toBe(true);
+ const csp = nodes.find(n => n.tagName === 'meta' && n.attrs.some(a => a.name === 'http-equiv'))!.attrs.find(a => a.name === 'content')!.value;
+ expect(csp).toContain('img-src data: cindy-media: https: http:');
+ expect(csp).toContain("script-src 'none'");
+ expect(csp).toContain("default-src 'none'");
+ expect(mailInlineDocument(source, [], true)).not.toMatch(/evil|file:|@import|url\(|unsafe-url|password/);
+ expect(applyMailInlineEdits(source, {})!.html).toBe(source);
+ });
it('omits legacy form nodes without joining malformed markup into executable tags', () => {
const form = '<div data-ghost-form="[{&quot;name&quot;:&quot;body&quot;,&quot;label&quot;:&quot;Body&quot;,&quot;value&quot;:&quot;text&quot;}]"><div>Preview</div></div>';
for (const split of ['<scr<style></style>ipt>alert(1)</script>', '<scr<script></script>ipt>alert(1)</script>']) {
diff --git a/packages/maker-shared/src/mailMessage.ts b/packages/maker-shared/src/mailMessage.ts
index 82509a6bc5..d61291a5fc 100644
--- a/packages/maker-shared/src/mailMessage.ts
+++ b/packages/maker-shared/src/mailMessage.ts
@@ -61,6 +61,8 @@ export interface MailMessage {
bodyText: string;
bodyHtml: string;
attachments: MailAttachmentItem[];
+ /** Optional exact-email contact photos. Older providers/clients may omit/ignore these. */
+ participantPhotos?: { email: string; url: string }[];
/** Optional, chronological metadata only. Bodies are read on explicit expansion. */
conversation?: MailConversation;
conversationUnavailable?: boolean;
@@ -109,12 +111,28 @@ export function parseMailMessage(value: unknown): MailMessage | null {
const attachments = parseMailAttachmentItems(JSON.stringify(p.attachments));
if (!attachments) return null;
const conversation = parseConversation(p.conversation, p.messageId as string);
+ const participantPhotos = Array.isArray(p.participantPhotos) ? p.participantPhotos.slice(0, 64).flatMap(photo => {
+ if (!photo || typeof photo.email !== 'string' || photo.email.length > 320 ||
+ mailParticipantEmail(photo.email) !== photo.email || typeof photo.url !== 'string' || photo.url.length > 2048) return [];
+ try {
+ const url = new URL(photo.url);
+ if (url.protocol !== 'https:' || url.username || url.password || url.port) return [];
+ return [{ email: photo.email, url: url.href }];
+ } catch { return []; }
+ }) : [];
return { ...Object.fromEntries(Object.keys(limits).map(k => [k, p[k]])), attachments,
+ ...(participantPhotos.length ? { participantPhotos } : {}),
...(p.markReadFailed === true ? { markReadFailed: true } : {}),
...(conversation ? { conversation } : {}),
...(p.conversationUnavailable === true || (p.conversation !== undefined && !conversation) ? { conversationUnavailable: true } : {}),
} as unknown as MailMessage;
}
+
+/** Conservative display lookup: never infer an email from a person's name. */
+export function mailParticipantEmail(address: string): string | undefined {
+ const email = (/<([^<>]+)>\s*$/.exec(address)?.[1] || address).trim().toLowerCase();
+ return email.length <= 320 && /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(email) ? email : undefined;
+}
/** Reuse the compose card's HTML, recipients, CID and attachment renderers, with no actions. */
export function mailMessageFields(mail: MailMessage, label: (key: string) => string): GhostCardFormField[] {
return [
diff --git a/packages/maker-shared/src/mailTextEdit.ts b/packages/maker-shared/src/mailTextEdit.ts
index 5865132b26..4ea033ceec 100644
--- a/packages/maker-shared/src/mailTextEdit.ts
+++ b/packages/maker-shared/src/mailTextEdit.ts
@@ -68,9 +68,28 @@ const attrs = new Set('class id href src alt title width height colspan rowspan
const cleanCss = (value: string) => /expression|\\/i.test(value) ? '' : value.replace(/@import[^;]*;?/gi, '').replace(/url\s*\([^)]*\)/gi, 'none');
export type MailInlineImage = { cid: string; url: string };
+/** External mail images are opt-in; relative URLs have no trustworthy base. */
+export function externalMailImageUrl(value: string): string | undefined {
+ try {
+ const url = new URL(value.startsWith('//') ? `https:${value}` : value);
+ if ((url.protocol === 'https:' || url.protocol === 'http:') && !url.username && !url.password) return url.href;
+ } catch { /* Invalid image sources stay blocked. */ }
+}
+
+export function hasMailExternalImages(source: string): boolean {
+ const visit = (node: DefaultTreeAdapterTypes.Node): boolean => {
+ if ('tagName' in node) {
+ if (!tags.has(node.tagName) || node.namespaceURI !== htmlNames.NS.HTML) return false;
+ if (node.tagName === 'img' && externalMailImageUrl(node.attrs.find(a => a.name === 'src')?.value || '')) return true;
+ }
+ return 'childNodes' in node && node.childNodes.some(visit);
+ };
+ return visit(parse(source));
+}
+
/** Sanitize before creating our markers. Mail-provided editing attributes,
* scripts, nested contexts and event handlers can never become editor controls. */
-export function safeMailDocument(source: string, inline = false, images: MailInlineImage[] = []): string {
+export function safeMailDocument(source: string, inline = false, images: MailInlineImage[] = [], allowExternalImages = false): string {
const doc = parse(source, { sourceCodeLocationInfo: true });
const runs = inline ? mailInlineRuns(source) : [];
const byStart = new Map(runs.map((run, id) => [run.start, { ...run, id }]));
@@ -86,9 +105,14 @@ export function safeMailDocument(source: string, inline = false, images: MailInl
for (const node of parent.childNodes) {
if ('tagName' in node) {
if (!tags.has(node.tagName) || node.namespaceURI !== htmlNames.NS.HTML) continue;
+ const externalImage = allowExternalImages && node.tagName === 'img'
+ ? externalMailImageUrl(node.attrs.find(a => a.name === 'src')?.value || '') : undefined;
node.attrs = node.attrs.filter(a => a.name === 'style' || (attrs.has(a.name) &&
(a.name !== 'href' || /^(https?:|mailto:)/i.test(a.value)) &&
(a.name !== 'src' || /^(cid:|data:image\/(png|jpeg|gif|webp);base64,)/i.test(a.value))));
+ // Inline hosts start opted-in requests after the document is ready, so
+ // a slow image server cannot hold the entire mail body invisible.
+ if (externalImage) node.attrs.push({ name: inline ? 'data-cindy-mail-external-src' : 'src', value: externalImage }, { name: 'referrerpolicy', value: 'no-referrer' });
for (const attr of node.attrs) if (attr.name === 'style') attr.value = cleanCss(attr.value);
if (node.tagName === 'style') {
node.childNodes = node.childNodes.filter(n => 'value' in n);
@@ -130,8 +154,8 @@ export const validMailImageUrl = (url: string) => /^cindy-media:\/\/blobs\/[a-f0
// without the app theme's warm-white tint. Authored body colors still win.
export const MAIL_PAPER_COLOR = 'white';
export const MAIL_INLINE_STYLE = `html{color-scheme:light}body{margin:4px;background:${MAIL_PAPER_COLOR};color:#111;font:16px/1.6 Arial,Helvetica,sans-serif;overflow-wrap:anywhere}img{max-width:100%;height:auto}table{max-width:100%}[data-cindy-mail-run]{white-space:pre-wrap;outline:none}[data-cindy-mail-run]:empty{display:inline-block;min-width:1ch;min-height:1em}`;
-export function mailInlineDocument(source: string, images: MailInlineImage[] = []): string {
- return '<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'none\'; img-src data: cindy-media:; style-src \'unsafe-inline\'; form-action \'none\'; base-uri \'none\'"><meta name="viewport" content="width=device-width,initial-scale=1"><style>' + MAIL_INLINE_STYLE + '</style>' + safeMailDocument(source, true, images);
+export function mailInlineDocument(source: string, images: MailInlineImage[] = [], allowExternalImages = false): string {
+ return '<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'none\'; img-src data: cindy-media:' + (allowExternalImages ? ' https: http:' : '') + '; style-src \'unsafe-inline\'; form-action \'none\'; base-uri \'none\'"><meta name="viewport" content="width=device-width,initial-scale=1"><style>' + MAIL_INLINE_STYLE + '</style>' + safeMailDocument(source, true, images, allowExternalImages);
}
/** Executed only by the native WebView injection API. The document CSP allows