Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

feat: add external URL confirmation for markdown links and images (#988)

harshil-209684f71bf55aee
diff --git a/.changeset/markdown-external-url-confirm.md b/.changeset/markdown-external-url-confirm.md
new file mode 100644
index 000000000..7c22bb7e9
--- /dev/null
+++ b/.changeset/markdown-external-url-confirm.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge-ui': patch
+---
+
+Confirm before opening external markdown links or loading external markdown images, with per-host "Don't ask again" in localStorage.
diff --git a/packages/trueforge-ui/src/atoms/Markdown.tsx b/packages/trueforge-ui/src/atoms/Markdown.tsx
index d4b2df915..237cc02c9 100644
--- a/packages/trueforge-ui/src/atoms/Markdown.tsx
+++ b/packages/trueforge-ui/src/atoms/Markdown.tsx
@@ -7,6 +7,7 @@ import remarkGfm from 'remark-gfm';
import { useSlot, useThemeMode } from '../theme/SlotsProvider.js';
import { useOptionalContentClassNames } from '../theme/ThemeProvider.js';
+import { ExternalUrlConfirmProvider, MarkdownExternalImage, MarkdownExternalLink } from './externalUrlConfirm.js';
import { cn } from './lib/cn.js';
import type { OpenUiFenceBlockProps } from './OpenUiFenceBlock.js';
import type { SandboxArtifactDownloadProps } from './SandboxArtifactDownload.js';
@@ -84,14 +85,9 @@ function makeComponents(opts: {
} = opts;
return {
- // Chat markdown links should open in a new tab.
- a({ href, children, node: _node, ...props }) {
- return (
- <a {...props} href={href} target="_blank" rel="noopener noreferrer">
- {children}
- </a>
- );
- },
+ // External http(s) links/images confirm first; trusted hosts skip via localStorage.
+ a: MarkdownExternalLink,
+ img: MarkdownExternalImage,
// Strip default <pre> wrapper — each block renderer provides its own container.
pre({ children }: { children?: ReactNode }) {
return <>{children}</>;
@@ -205,13 +201,15 @@ export function Markdown({
);
return (
- <div
- className={cn('aui-markdown markdown-body min-w-0 max-w-full overflow-x-clip', classNames.markdown, className)}
- >
- <ReactMarkdown remarkPlugins={REMARK_PLUGINS} components={components}>
- {content}
- </ReactMarkdown>
- </div>
+ <ExternalUrlConfirmProvider>
+ <div
+ className={cn('aui-markdown markdown-body min-w-0 max-w-full overflow-x-clip', classNames.markdown, className)}
+ >
+ <ReactMarkdown remarkPlugins={REMARK_PLUGINS} components={components}>
+ {content}
+ </ReactMarkdown>
+ </div>
+ </ExternalUrlConfirmProvider>
);
}
diff --git a/packages/trueforge-ui/src/atoms/externalUrlConfirm.tsx b/packages/trueforge-ui/src/atoms/externalUrlConfirm.tsx
new file mode 100644
index 000000000..de36741b5
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/externalUrlConfirm.tsx
@@ -0,0 +1,252 @@
+'use client';
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useState,
+ type ComponentPropsWithoutRef,
+ type MouseEvent,
+ type ReactNode,
+} from 'react';
+
+import { getHostname, isExternalHttpUrl, isTrustedHost, openExternalHttpUrl, trustHost } from './externalUrlTrust.js';
+import { cn } from './lib/cn.js';
+import { Button } from './primitives/Button.js';
+import { Checkbox } from './primitives/Checkbox.js';
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from './primitives/Dialog.js';
+
+type PendingExternalUrl = {
+ kind: 'link' | 'image';
+ url: string;
+};
+
+type ExternalUrlConfirmContextValue = {
+ requestLinkConfirm: (url: string) => void;
+ requestImageConfirm: (url: string) => void;
+ isSessionImageHostTrusted: (host: string) => boolean;
+};
+
+const ExternalUrlConfirmContext = createContext<ExternalUrlConfirmContextValue | null>(null);
+
+function useExternalUrlConfirm(): ExternalUrlConfirmContextValue {
+ const value = useContext(ExternalUrlConfirmContext);
+ if (value == null) {
+ throw new Error('Markdown external URL confirm requires ExternalUrlConfirmProvider');
+ }
+ return value;
+}
+
+/**
+ * True for javascript:/data:/vbscript: hrefs (and unparseable ones). Those skip the
+ * external-link confirm path, so we block activation instead of letting the browser run them.
+ */
+function isDangerousNavigationUrl(url: string): boolean {
+ try {
+ const protocol = new URL(url, typeof window !== 'undefined' ? window.location.href : 'http://localhost').protocol;
+ return protocol === 'javascript:' || protocol === 'data:' || protocol === 'vbscript:';
+ } catch {
+ return true;
+ }
+}
+
+export function ExternalUrlConfirmProvider({ children }: { children: ReactNode }) {
+ const [pending, setPending] = useState<PendingExternalUrl | null>(null);
+ const [dontAskAgain, setDontAskAgain] = useState(false);
+ const [sessionImageHosts, setSessionImageHosts] = useState(() => new Set<string>());
+
+ const requestLinkConfirm = useCallback((url: string) => {
+ setDontAskAgain(false);
+ setPending({ kind: 'link', url });
+ }, []);
+
+ const requestImageConfirm = useCallback((url: string) => {
+ setDontAskAgain(false);
+ setPending({ kind: 'image', url });
+ }, []);
+
+ const isSessionImageHostTrusted = useCallback(
+ (host: string) => sessionImageHosts.has(host.toLowerCase()),
+ [sessionImageHosts],
+ );
+
+ const close = useCallback(() => {
+ setPending(null);
+ setDontAskAgain(false);
+ }, []);
+
+ const confirm = useCallback(() => {
+ if (pending == null) return;
+ const host = getHostname(pending.url);
+ if (pending.kind === 'link') {
+ if (dontAskAgain && host != null) trustHost({ kind: 'links', host });
+ openExternalHttpUrl(pending.url);
+ close();
+ return;
+ }
+ if (host != null) {
+ if (dontAskAgain) trustHost({ kind: 'images', host });
+ setSessionImageHosts(prev => {
+ const next = new Set(prev);
+ next.add(host.toLowerCase());
+ return next;
+ });
+ }
+ close();
+ }, [close, dontAskAgain, pending]);
+
+ const value = useMemo(
+ () => ({
+ requestLinkConfirm,
+ requestImageConfirm,
+ isSessionImageHostTrusted,
+ }),
+ [isSessionImageHostTrusted, requestImageConfirm, requestLinkConfirm],
+ );
+
+ const pendingHost = pending != null ? getHostname(pending.url) : null;
+ const title = pending?.kind === 'image' ? 'Show external image' : 'Open external link';
+ const description =
+ pending?.kind === 'image'
+ ? "You're about to load an image from an external site:"
+ : "You're leaving this app to visit an external link:";
+ const confirmLabel = pending?.kind === 'image' ? 'Show image' : 'Open link';
+ const checkboxLabel =
+ pendingHost == null
+ ? null
+ : pending?.kind === 'image'
+ ? `Don't ask again for images from ${pendingHost}`
+ : `Don't ask again for links to ${pendingHost}`;
+
+ return (
+ <ExternalUrlConfirmContext.Provider value={value}>
+ {children}
+ <Dialog
+ open={pending != null}
+ onOpenChange={open => {
+ if (!open) close();
+ }}
+ aria-label={title}
+ className="max-w-md"
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ <p className="text-sm text-text-secondary">{description}</p>
+ </DialogHeader>
+ {pending != null ? (
+ <div
+ className="max-h-24 overflow-auto break-all rounded-md bg-secondary-bg px-3 py-2 font-mono text-sm text-text-primary"
+ data-testid="aui-external-url-confirm-url"
+ >
+ {pending.url}
+ </div>
+ ) : null}
+ {checkboxLabel != null ? (
+ <button
+ type="button"
+ role="checkbox"
+ aria-checked={dontAskAgain}
+ className="flex items-start gap-2 text-left text-sm text-text-secondary"
+ onClick={() => setDontAskAgain(value => !value)}
+ >
+ <Checkbox checked={dontAskAgain} className="mt-0.5" />
+ <span>{checkboxLabel}</span>
+ </button>
+ ) : null}
+ </DialogContent>
+ <DialogFooter>
+ <Button.Secondary type="button" onClick={close}>
+ Cancel
+ </Button.Secondary>
+ <Button.Primary type="button" onClick={confirm}>
+ {confirmLabel}
+ </Button.Primary>
+ </DialogFooter>
+ </Dialog>
+ </ExternalUrlConfirmContext.Provider>
+ );
+}
+
+export function MarkdownExternalLink({
+ href,
+ children,
+ node: _node,
+ ...props
+}: ComponentPropsWithoutRef<'a'> & { node?: unknown }) {
+ const { requestLinkConfirm } = useExternalUrlConfirm();
+ const dangerous = href != null && href !== '' && isDangerousNavigationUrl(href);
+ const external = href != null && href !== '' && !dangerous && isExternalHttpUrl(href);
+ // External destinations never stay in href — middle-click / context-menu bypass onClick.
+ // Activation always goes through guardNavigation (trusted hosts skip the dialog there).
+ const anchorHref = dangerous ? undefined : external ? '#' : href;
+
+ const guardNavigation = (event: MouseEvent<HTMLAnchorElement>) => {
+ if (href == null || href === '') return;
+ if (isDangerousNavigationUrl(href)) {
+ event.preventDefault();
+ return;
+ }
+ if (!isExternalHttpUrl(href)) return;
+
+ event.preventDefault();
+ const host = getHostname(href);
+ if (host != null && isTrustedHost({ kind: 'links', host })) {
+ openExternalHttpUrl(href);
+ return;
+ }
+ requestLinkConfirm(href);
+ };
+
+ return (
+ <a
+ {...props}
+ href={anchorHref}
+ target={external || dangerous ? '_blank' : props.target}
+ rel="noopener noreferrer"
+ onClick={guardNavigation}
+ onAuxClick={guardNavigation}
+ >
+ {children}
+ </a>
+ );
+}
+
+export function MarkdownExternalImage({
+ src,
+ alt,
+ node: _node,
+ ...props
+}: ComponentPropsWithoutRef<'img'> & { node?: unknown }) {
+ const { requestImageConfirm, isSessionImageHostTrusted } = useExternalUrlConfirm();
+ const url = typeof src === 'string' ? src : '';
+ const host = url !== '' ? getHostname(url) : null;
+ const needsGate = url !== '' && isExternalHttpUrl(url);
+ const allowed =
+ !needsGate || (host != null && (isTrustedHost({ kind: 'images', host }) || isSessionImageHostTrusted(host)));
+
+ if (!allowed) {
+ return (
+ <span
+ className={cn('my-2 flex max-w-full flex-col gap-2 rounded-md border border-border bg-secondary-bg p-3')}
+ data-testid="aui-external-image-placeholder"
+ >
+ <span className="text-sm text-text-secondary">{alt != null && alt !== '' ? alt : 'External image'}</span>
+ <span className="max-h-16 overflow-auto break-all font-mono text-xs text-text-secondary">{url}</span>
+ <Button.Secondary
+ type="button"
+ size="small"
+ className="self-start"
+ onClick={() => {
+ if (url !== '') requestImageConfirm(url);
+ }}
+ >
+ Show image
+ </Button.Secondary>
+ </span>
+ );
+ }
+
+ return <img {...props} src={src} alt={alt ?? ''} />;
+}
diff --git a/packages/trueforge-ui/src/atoms/externalUrlTrust.ts b/packages/trueforge-ui/src/atoms/externalUrlTrust.ts
new file mode 100644
index 000000000..1fdc5ee57
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/externalUrlTrust.ts
@@ -0,0 +1,97 @@
+export const EXTERNAL_URL_TRUST_STORAGE_KEY = 'aui-trusted-external-hosts';
+
+export type ExternalUrlTrustKind = 'links' | 'images';
+
+type StoredExternalUrlTrust = {
+ version: 1;
+ links: string[];
+ images: string[];
+};
+
+function emptyStore(): StoredExternalUrlTrust {
+ return { version: 1, links: [], images: [] };
+}
+
+function isStringArray(value: unknown): value is string[] {
+ return Array.isArray(value) && value.every(item => typeof item === 'string');
+}
+
+function parseStore(raw: unknown): StoredExternalUrlTrust {
+ if (raw == null || typeof raw !== 'object') return emptyStore();
+ if (!('version' in raw) || raw.version !== 1) return emptyStore();
+ const links = 'links' in raw && isStringArray(raw.links) ? raw.links : [];
+ const images = 'images' in raw && isStringArray(raw.images) ? raw.images : [];
+ return { version: 1, links, images };
+}
+
+function readStore(): StoredExternalUrlTrust {
+ if (typeof window === 'undefined') return emptyStore();
+ try {
+ const raw: unknown = JSON.parse(window.localStorage.getItem(EXTERNAL_URL_TRUST_STORAGE_KEY) ?? 'null');
+ return parseStore(raw);
+ } catch {
+ return emptyStore();
+ }
+}
+
+function writeStore(store: StoredExternalUrlTrust): void {
+ if (typeof window === 'undefined') return;
+ try {
+ window.localStorage.setItem(EXTERNAL_URL_TRUST_STORAGE_KEY, JSON.stringify(store));
+ } catch {
+ // Storage can be unavailable or full; in-memory session approvals still work.
+ }
+}
+
+function resolveUrl(url: string): URL | null {
+ try {
+ // Base required so protocol-relative (`//host/path`) and relative URLs parse.
+ const base = typeof window !== 'undefined' ? window.location.href : 'http://localhost';
+ return new URL(url, base);
+ } catch {
+ return null;
+ }
+}
+
+/** Hostname for http(s) URLs resolved against the page; null for non-http(s) or unparseable. */
+export function getHostname(url: string): string | null {
+ const parsed = resolveUrl(url);
+ if (parsed == null) return null;
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
+ return parsed.hostname.toLowerCase();
+}
+
+/**
+ * True when `url` resolves to http(s) on a host that differs from the page host.
+ * Same-origin, data:, blob:, and other non-http(s) schemes return false.
+ */
+export function isExternalHttpUrl(url: string): boolean {
+ const host = getHostname(url);
+ if (host == null) return false;
+ if (typeof window === 'undefined') return true;
+ return host !== window.location.hostname.toLowerCase();
+}
+
+export function isTrustedHost({ kind, host }: { kind: ExternalUrlTrustKind; host: string }): boolean {
+ const normalized = host.toLowerCase();
+ const store = readStore();
+ return store[kind].includes(normalized);
+}
+
+export function trustHost({ kind, host }: { kind: ExternalUrlTrustKind; host: string }): void {
+ const normalized = host.toLowerCase();
+ const store = readStore();
+ if (store[kind].includes(normalized)) return;
+ writeStore({
+ ...store,
+ [kind]: [...store[kind], normalized],
+ });
+}
+
+/** Open http(s) URLs in a new tab; no-op for non-http(s) schemes (e.g. javascript:). */
+export function openExternalHttpUrl(url: string): void {
+ const parsed = resolveUrl(url);
+ if (parsed == null) return;
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return;
+ window.open(parsed.href, '_blank', 'noopener,noreferrer');
+}
diff --git a/packages/trueforge-ui/src/github-markdown-bridge.css b/packages/trueforge-ui/src/github-markdown-bridge.css
index ad633815c..cc7f4f054 100644
--- a/packages/trueforge-ui/src/github-markdown-bridge.css
+++ b/packages/trueforge-ui/src/github-markdown-bridge.css
@@ -10,7 +10,8 @@
.aui-theme-root[data-theme='dark'] .markdown-body {
/*dark */
color-scheme: dark;
- --fgColor-accent: #4493f8;
+ /* Match SDK accent (indigo) instead of GitHub link blue. */
+ --fgColor-accent: var(--color-indigo-500);
--bgColor-attention-muted: #bb800926;
--bgColor-default: #0d1117;
--bgColor-muted: #151b23;
@@ -102,7 +103,8 @@
--color-prettylights-syntax-string-regexp: #116329;
--color-prettylights-syntax-sublimelinter-gutter-mark: #818b98;
--color-prettylights-syntax-variable: #953800;
- --fgColor-accent: #0969da;
+ /* Match SDK accent (indigo) instead of GitHub link blue. */
+ --fgColor-accent: var(--color-indigo-500);
--fgColor-attention: #9a6700;
--fgColor-done: #8250df;
--fgColor-muted: #59636e;
diff --git a/packages/trueforge-ui/test/atoms/Markdown.test.tsx b/packages/trueforge-ui/test/atoms/Markdown.test.tsx
index 70b797ba4..e1777d6f1 100644
--- a/packages/trueforge-ui/test/atoms/Markdown.test.tsx
+++ b/packages/trueforge-ui/test/atoms/Markdown.test.tsx
@@ -1,8 +1,10 @@
// @vitest-environment jsdom
-import { render, screen, waitFor } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { useEffect } from 'react';
-import { describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ExternalUrlConfirmProvider, MarkdownExternalLink } from '@/atoms/externalUrlConfirm.js';
+import { EXTERNAL_URL_TRUST_STORAGE_KEY } from '@/atoms/externalUrlTrust.js';
import { LARGE_STREAMING_FENCE_CHARS, Markdown, getActiveStreamingFenceCode } from '@/atoms/Markdown.js';
import type { SyntaxHighlighterProps } from '@/atoms/SyntaxHighlighter.js';
import { SlotsProvider } from '@/theme/SlotsProvider.js';
@@ -10,6 +12,40 @@ import { SlotsProvider } from '@/theme/SlotsProvider.js';
// @openuidev mocks are in testSetup.ts; they make OpenUiFenceBlock render
// a simple div with data-testid="aui-openui-renderer" synchronously.
+const originalShowModal = Object.getOwnPropertyDescriptor(HTMLDialogElement.prototype, 'showModal');
+const originalClose = Object.getOwnPropertyDescriptor(HTMLDialogElement.prototype, 'close');
+
+beforeEach(() => {
+ Object.defineProperty(HTMLDialogElement.prototype, 'showModal', {
+ configurable: true,
+ value: function showModal(this: HTMLDialogElement) {
+ this.open = true;
+ },
+ });
+ Object.defineProperty(HTMLDialogElement.prototype, 'close', {
+ configurable: true,
+ value: function close(this: HTMLDialogElement) {
+ this.open = false;
+ this.dispatchEvent(new Event('close'));
+ },
+ });
+});
+
+afterEach(() => {
+ window.localStorage.removeItem(EXTERNAL_URL_TRUST_STORAGE_KEY);
+ vi.restoreAllMocks();
+ if (originalShowModal === undefined) {
+ Reflect.deleteProperty(HTMLDialogElement.prototype, 'showModal');
+ } else {
+ Object.defineProperty(HTMLDialogElement.prototype, 'showModal', originalShowModal);
+ }
+ if (originalClose === undefined) {
+ Reflect.deleteProperty(HTMLDialogElement.prototype, 'close');
+ } else {
+ Object.defineProperty(HTMLDialogElement.prototype, 'close', originalClose);
+ }
+});
+
describe('getActiveStreamingFenceCode', () => {
it('returns null when every fence is closed', () => {
expect(getActiveStreamingFenceCode('```js\nconst x = 1;\n```\n\ndone')).toBeNull();
@@ -29,13 +65,120 @@ describe('Markdown', () => {
expect(strong.closest('.markdown-body')).toBeTruthy();
});
- it('opens links in a new tab', () => {
+ it('marks external links for a new tab and confirms before opening', () => {
+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
render(<Markdown content="See [docs](https://example.com/docs) for details." />);
const link = screen.getByRole('link', { name: 'docs' });
- expect(link).toHaveAttribute('href', 'https://example.com/docs');
+ // Unapproved external destinations stay off href so middle-click / context-menu cannot bypass.
+ expect(link).toHaveAttribute('href', '#');
expect(link).toHaveAttribute('target', '_blank');
expect(link).toHaveAttribute('rel', 'noopener noreferrer');
expect(link).not.toHaveAttribute('node');
+
+ fireEvent.click(link);
+ expect(openSpy).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog', { name: 'Open external link' })).toBeInTheDocument();
+ expect(screen.getByTestId('aui-external-url-confirm-url')).toHaveTextContent('https://example.com/docs');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(screen.queryByRole('dialog', { name: 'Open external link' })).not.toBeInTheDocument();
+ expect(openSpy).not.toHaveBeenCalled();
+
+ fireEvent.click(link);
+ fireEvent.click(screen.getByRole('button', { name: 'Open link' }));
+ expect(openSpy).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer');
+ });
+
+ it('confirms protocol-relative external links and blocks middle-click bypass', () => {
+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
+ render(<Markdown content="See [cdn](//cdn.example.com/a) for details." />);
+ const link = screen.getByRole('link', { name: 'cdn' });
+ expect(link).toHaveAttribute('href', '#');
+
+ fireEvent(link, new MouseEvent('auxclick', { bubbles: true, cancelable: true, button: 1 }));
+ expect(openSpy).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog', { name: 'Open external link' })).toBeInTheDocument();
+ expect(screen.getByTestId('aui-external-url-confirm-url')).toHaveTextContent('//cdn.example.com/a');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Open link' }));
+ const expected = new URL('//cdn.example.com/a', window.location.href).href;
+ expect(openSpy).toHaveBeenCalledWith(expected, '_blank', 'noopener,noreferrer');
+ });
+
+ it('blocks javascript, data, and vbscript href activation', () => {
+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
+ render(
+ <ExternalUrlConfirmProvider>
+ <MarkdownExternalLink href="javascript:alert(1)">js</MarkdownExternalLink>
+ <MarkdownExternalLink href="data:text/html,hi">data</MarkdownExternalLink>
+ <MarkdownExternalLink href="vbscript:msgbox(1)">vb</MarkdownExternalLink>
+ </ExternalUrlConfirmProvider>,
+ );
+
+ for (const name of ['js', 'data', 'vb'] as const) {
+ const el = screen.getByText(name);
+ expect(el).not.toHaveAttribute('href');
+ fireEvent.click(el);
+ fireEvent(el, new MouseEvent('auxclick', { bubbles: true, cancelable: true, button: 1 }));
+ }
+
+ expect(screen.queryByRole('dialog', { name: 'Open external link' })).not.toBeInTheDocument();
+ expect(openSpy).not.toHaveBeenCalled();
+ });
+
+ it('skips the link dialog after trusting a host', () => {
+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
+ render(<Markdown content="See [docs](https://example.com/docs) for details." />);
+ const link = screen.getByRole('link', { name: 'docs' });
+
+ fireEvent.click(link);
+ fireEvent.click(screen.getByRole('checkbox'));
+ fireEvent.click(screen.getByRole('button', { name: 'Open link' }));
+ expect(openSpy).toHaveBeenCalledTimes(1);
+ expect(link).toHaveAttribute('href', '#');
+
+ fireEvent.click(link);
+ expect(screen.queryByRole('dialog', { name: 'Open external link' })).not.toBeInTheDocument();
+ expect(openSpy).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not confirm same-origin links', () => {
+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
+ const href = `${window.location.origin}/local-docs`;
+ render(<Markdown content={`See [local](${href}) for details.`} />);
+ fireEvent.click(screen.getByRole('link', { name: 'local' }));
+ expect(screen.queryByRole('dialog', { name: 'Open external link' })).not.toBeInTheDocument();
+ expect(openSpy).not.toHaveBeenCalled();
+ });
+
+ it('blocks external images until confirmed', () => {
+ render(<Markdown content={'![chart](https://cdn.example.com/a.png)'} />);
+ const placeholder = screen.getByTestId('aui-external-image-placeholder');
+ expect(placeholder).toBeInTheDocument();
+ expect(document.querySelector('img[src="https://cdn.example.com/a.png"]')).toBeNull();
+
+ fireEvent.click(within(placeholder).getByRole('button', { name: 'Show image' }));
+ const dialog = screen.getByRole('dialog', { name: 'Show external image' });
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Show image' }));
+
+ expect(screen.queryByTestId('aui-external-image-placeholder')).not.toBeInTheDocument();
+ expect(document.querySelector('img[src="https://cdn.example.com/a.png"]')).toBeTruthy();
+ });
+
+ it('blocks protocol-relative external images until confirmed', () => {
+ render(<Markdown content={'![chart](//cdn.example.com/a.png)'} />);
+ expect(screen.getByTestId('aui-external-image-placeholder')).toBeInTheDocument();
+ expect(document.querySelector('img[src="//cdn.example.com/a.png"]')).toBeNull();
+ });
+
+ it('auto-loads external images for a trusted host', () => {
+ window.localStorage.setItem(
+ EXTERNAL_URL_TRUST_STORAGE_KEY,
+ JSON.stringify({ version: 1, links: [], images: ['cdn.example.com'] }),
+ );
+ render(<Markdown content={'![chart](https://cdn.example.com/a.png)'} />);
+ expect(screen.queryByTestId('aui-external-image-placeholder')).not.toBeInTheDocument();
+ expect(document.querySelector('img[src="https://cdn.example.com/a.png"]')).toBeTruthy();
});
it('renders openui fenced blocks via OpenUiFenceBlock', async () => {
diff --git a/packages/trueforge-ui/test/atoms/externalUrlTrust.test.ts b/packages/trueforge-ui/test/atoms/externalUrlTrust.test.ts
new file mode 100644
index 000000000..158a1b424
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/externalUrlTrust.test.ts
@@ -0,0 +1,69 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ EXTERNAL_URL_TRUST_STORAGE_KEY,
+ getHostname,
+ isExternalHttpUrl,
+ isTrustedHost,
+ trustHost,
+} from '@/atoms/externalUrlTrust.js';
+
+afterEach(() => {
+ window.localStorage.removeItem(EXTERNAL_URL_TRUST_STORAGE_KEY);
+});
+
+describe('getHostname', () => {
+ it('returns lowercase host for http(s) URLs', () => {
+ expect(getHostname('https://Example.COM/path')).toBe('example.com');
+ expect(getHostname('http://evil.test/?q=1')).toBe('evil.test');
+ });
+
+ it('resolves protocol-relative URLs against the page', () => {
+ expect(getHostname('//CDN.Example.com/a.png')).toBe('cdn.example.com');
+ });
+
+ it('returns null for non-http(s) schemes', () => {
+ expect(getHostname('javascript:alert(1)')).toBeNull();
+ expect(getHostname('data:image/png;base64,abc')).toBeNull();
+ });
+
+ it('returns the page host for same-document relative paths', () => {
+ expect(getHostname('/relative/path')).toBe(window.location.hostname.toLowerCase());
+ });
+});
+
+describe('isExternalHttpUrl', () => {
+ it('is true for absolute http(s) on another host', () => {
+ expect(isExternalHttpUrl('https://example.com/x')).toBe(true);
+ });
+
+ it('is true for protocol-relative URLs on another host', () => {
+ expect(isExternalHttpUrl('//attacker.example/track')).toBe(true);
+ });
+
+ it('is false for same-origin, relative, data, and blob URLs', () => {
+ const sameOrigin = `${window.location.origin}/local.png`;
+ expect(isExternalHttpUrl(sameOrigin)).toBe(false);
+ expect(isExternalHttpUrl('/relative.png')).toBe(false);
+ expect(isExternalHttpUrl('data:image/png;base64,abc')).toBe(false);
+ expect(isExternalHttpUrl('blob:https://example.com/uuid')).toBe(false);
+ });
+});
+
+describe('trustHost / isTrustedHost', () => {
+ it('persists links and images allowlists separately', () => {
+ trustHost({ kind: 'links', host: 'React.DEV' });
+ expect(isTrustedHost({ kind: 'links', host: 'react.dev' })).toBe(true);
+ expect(isTrustedHost({ kind: 'images', host: 'react.dev' })).toBe(false);
+
+ trustHost({ kind: 'images', host: 'cdn.example.com' });
+ expect(isTrustedHost({ kind: 'images', host: 'cdn.example.com' })).toBe(true);
+ expect(isTrustedHost({ kind: 'links', host: 'cdn.example.com' })).toBe(false);
+
+ const storedRaw = window.localStorage.getItem(EXTERNAL_URL_TRUST_STORAGE_KEY);
+ expect(storedRaw).toContain('"version":1');
+ expect(storedRaw).toContain('"react.dev"');
+ expect(storedRaw).toContain('"cdn.example.com"');
+ });
+});