Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(web-app): open links from untrusted content only through the external-link helper
James Dam7e4cc890ae9b
diff --git a/web-app/src/components/Citations.tsx b/web-app/src/components/Citations.tsxindex d5ff6bf9b..b05bec0cb 100644--- a/web-app/src/components/Citations.tsx+++ b/web-app/src/components/Citations.tsx@@ -5,6 +5,7 @@ import {useAttachmentName,useEnsureAttachmentNames,} from '@/hooks/useAttachmentNames'+import { ExternalAnchor } from '@/components/ExternalAnchor'export type RagCitation = {id: string@@ -113,15 +114,13 @@ const WebCitationItem = memo(({ c }: { c: WebCitation }) => {) : (<GlobeIcon className="size-3.5 shrink-0 text-muted-foreground" />)}- <a+ <ExternalAnchorhref={c.url}- target="_blank"- rel="noreferrer noopener"className="truncate font-medium hover:underline"title={c.url}>{c.title || host}- </a>+ </ExternalAnchor><span className="ml-auto truncate text-[10px] text-muted-foreground">{host}</span>diff --git a/web-app/src/components/ExternalAnchor.tsx b/web-app/src/components/ExternalAnchor.tsxnew file mode 100644index 000000000..8aec02dd4--- /dev/null+++ b/web-app/src/components/ExternalAnchor.tsx@@ -0,0 +1,44 @@+import { forwardRef, type AnchorHTMLAttributes } from 'react'+import { externalHref, openExternalUrl } from '@/lib/externalLink'++export type ExternalAnchorProps = Omit<+ AnchorHTMLAttributes<HTMLAnchorElement>,+ 'href' | 'target' | 'rel'+> & { href?: string | null }++/**+ * A link to a URL the app does not control (search results, citations, model+ * cards, server-provided pages). A web or mail link opens outside the app; any+ * other href (`javascript:`, `file:`, app routes, ...) renders as inert text.+ */+export const ExternalAnchor = forwardRef<+ HTMLAnchorElement,+ ExternalAnchorProps+>(({ href, onClick, children, ...rest }, ref) => {+ const external = externalHref(href)+ if (!external) {+ return (+ <a ref={ref} {...rest}>+ {children}+ </a>+ )+ }+ return (+ <a+ ref={ref}+ {...rest}+ href={external}+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e) => {+ onClick?.(e)+ if (e.defaultPrevented) return+ e.preventDefault()+ openExternalUrl(external)+ }}+ >+ {children}+ </a>+ )+})+ExternalAnchor.displayName = 'ExternalAnchor'diff --git a/web-app/src/components/WebCitationChip.tsx b/web-app/src/components/WebCitationChip.tsxindex 9b1218326..5e6b8d7b3 100644--- a/web-app/src/components/WebCitationChip.tsx+++ b/web-app/src/components/WebCitationChip.tsx@@ -7,6 +7,7 @@ import {import { useWebCitationStore } from '@/stores/web-citation-store'import { cn } from '@/lib/utils'import { faviconForUrl, hostOf } from '@/lib/webUrl'+import { ExternalAnchor } from '@/components/ExternalAnchor'export const WebCitationChip = memo(({ messageId, url }: { messageId?: string; url: string }) => {@@ -18,10 +19,8 @@ export const WebCitationChip = memo(return (<HoverCard openDelay={80} closeDelay={120}><HoverCardTrigger asChild>- <a+ <ExternalAnchorhref={url}- target="_blank"- rel="noreferrer noopener"className="mx-0.5 inline-flex translate-y-[-0.15em] align-baseline no-underline"title={citation?.title || url}>@@ -30,7 +29,7 @@ export const WebCitationChip = memo(alt=""className="inline-block size-3.5 rounded-full border border-border/60 bg-white object-contain hover:ring-2 hover:ring-primary/40"/>- </a>+ </ExternalAnchor></HoverCardTrigger><HoverCardContentalign="start"@@ -45,14 +44,12 @@ export const WebCitationChip = memo(/><span className="truncate text-muted-foreground">{host}</span></div>- <a+ <ExternalAnchorhref={url}- target="_blank"- rel="noreferrer noopener"className={cn('block truncate font-medium hover:underline')}>{citation?.title || host}- </a>+ </ExternalAnchor>{citation?.text && (<p className="line-clamp-4 whitespace-pre-wrap leading-relaxed text-muted-foreground">{citation.text}diff --git a/web-app/src/components/__tests__/ExternalAnchor.test.tsx b/web-app/src/components/__tests__/ExternalAnchor.test.tsxnew file mode 100644index 000000000..99332f546--- /dev/null+++ b/web-app/src/components/__tests__/ExternalAnchor.test.tsx@@ -0,0 +1,60 @@+import { createRef } from 'react'+import { describe, expect, it, vi, afterEach } from 'vitest'+import { fireEvent, render, screen } from '@testing-library/react'+import '@testing-library/jest-dom'+import { openExternalUrl } from '@/lib/externalLink'+import { ExternalAnchor } from '../ExternalAnchor'++vi.mock('@/lib/externalLink', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/externalLink')>()),+ openExternalUrl: vi.fn(),+}))++describe('ExternalAnchor', () => {+ afterEach(() => vi.mocked(openExternalUrl).mockClear())++ it('opens a web link outside the app', () => {+ render(+ <ExternalAnchor href="https://example.com/a?b=1">Web</ExternalAnchor>+ )+ const link = screen.getByRole('link', { name: 'Web' })+ expect(link).toHaveAttribute('href', 'https://example.com/a?b=1')+ expect(link).toHaveAttribute('target', '_blank')+ expect(link).toHaveAttribute('rel', 'noopener noreferrer')+ const notPrevented = fireEvent.click(link)+ expect(notPrevented).toBe(false)+ expect(openExternalUrl).toHaveBeenCalledWith('https://example.com/a?b=1')+ })++ it.each([+ 'javascript:alert(1)',+ 'file:///etc/passwd',+ 'tauri://localhost/settings',+ 'asset://localhost/x',+ '/settings',+ '',+ undefined,+ null,+ ])('renders %s as inert text', (href) => {+ render(<ExternalAnchor href={href}>Inert</ExternalAnchor>)+ const el = screen.getByText('Inert')+ expect(el).not.toHaveAttribute('href')+ expect(el).not.toHaveAttribute('target')+ fireEvent.click(el)+ expect(openExternalUrl).not.toHaveBeenCalled()+ })++ it('keeps the caller onClick and forwards the ref', () => {+ const onClick = vi.fn()+ const ref = createRef<HTMLAnchorElement>()+ render(+ <ExternalAnchor ref={ref} href="https://example.com/" onClick={onClick}>+ Web+ </ExternalAnchor>+ )+ fireEvent.click(screen.getByRole('link', { name: 'Web' }))+ expect(onClick).toHaveBeenCalledTimes(1)+ expect(ref.current).toBeInstanceOf(HTMLAnchorElement)+ expect(openExternalUrl).toHaveBeenCalledWith('https://example.com/')+ })+})diff --git a/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsx b/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsxindex 441da9125..7bb724d64 100644--- a/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsx+++ b/web-app/src/components/ai-elements/__tests__/chain-of-thought.test.tsx@@ -300,10 +300,20 @@ describe('ChainOfThoughtSearchResult', () => {</ChainOfThoughtSearchResult>)const link = screen.getByRole('link', { name: /Example/ })- expect(link).toHaveAttribute('href', 'https://example.com')+ expect(link).toHaveAttribute('href', 'https://example.com/')expect(link).toHaveAttribute('target', '_blank')expect(link).toHaveAttribute('rel', 'noopener noreferrer')})++ it('renders a non-web href as inert text', () => {+ render(+ <ChainOfThoughtSearchResult href="javascript:alert(1)">+ Bad+ </ChainOfThoughtSearchResult>+ )+ expect(screen.queryByRole('link')).toBeNull()+ expect(screen.getByText('Bad').closest('a')).not.toHaveAttribute('href')+ })})describe('ChainOfThoughtImage', () => {diff --git a/web-app/src/components/ai-elements/chain-of-thought.tsx b/web-app/src/components/ai-elements/chain-of-thought.tsxindex acc3f7a73..3005a55a8 100644--- a/web-app/src/components/ai-elements/chain-of-thought.tsx+++ b/web-app/src/components/ai-elements/chain-of-thought.tsx@@ -31,6 +31,10 @@ import { Streamdown } from 'streamdown'import { useTranslation } from '@/i18n/react-i18next-compat'import { formatCompactDuration } from '@/lib/duration'import { Shimmer } from './shimmer'+import {+ ExternalAnchor,+ type ExternalAnchorProps,+} from '@/components/ExternalAnchor'// ── Types ──────────────────────────────────────────────────────────────────@@ -422,14 +426,12 @@ export const ChainOfThoughtSearchResults = memo(// ── ChainOfThoughtSearchResult ─────────────────────────────────────────────-export type ChainOfThoughtSearchResultProps = ComponentProps<'a'>+export type ChainOfThoughtSearchResultProps = ExternalAnchorPropsexport const ChainOfThoughtSearchResult = memo(({ className, children, href, ...props }: ChainOfThoughtSearchResultProps) => (- <a+ <ExternalAnchorhref={href}- target="_blank"- rel="noopener noreferrer"className={cn('inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground',className@@ -439,7 +441,7 @@ export const ChainOfThoughtSearchResult = memo(<SearchIcon className="size-3 shrink-0" /><span className="truncate max-w-[200px]">{children}</span><ExternalLinkIcon className="size-3 shrink-0 opacity-50" />- </a>+ </ExternalAnchor>))diff --git a/web-app/src/containers/McpServerAuth.tsx b/web-app/src/containers/McpServerAuth.tsxindex ddb22ad6a..ef917a509 100644--- a/web-app/src/containers/McpServerAuth.tsx+++ b/web-app/src/containers/McpServerAuth.tsx@@ -2,6 +2,7 @@ import { Button } from '@/components/ui/button'import { useTranslation } from '@/i18n/react-i18next-compat'import { cn } from '@/lib/utils'import type { MCPAuthStatus } from '@/services/mcp/types'+import { ExternalAnchor } from '@/components/ExternalAnchor'/*** The `Auth:` line for one remote MCP server in the settings list: a badge for@@ -108,14 +109,12 @@ export function McpServerAuth({{/* The flow is already waiting on the redirect by the time this shows, soa browser that failed to launch is still recoverable by hand. */}{authorizing && consentUrl && (- <a+ <ExternalAnchorhref={consentUrl}- target="_blank"- rel="noopener noreferrer"className="text-xs text-blue-500 hover:underline">{t('mcp-servers:auth.openSignInPage')}- </a>+ </ExternalAnchor>)}</div>)diff --git a/web-app/src/containers/dialogs/AddModel.tsx b/web-app/src/containers/dialogs/AddModel.tsxindex 819b7b56d..8f427c8e6 100644--- a/web-app/src/containers/dialogs/AddModel.tsx+++ b/web-app/src/containers/dialogs/AddModel.tsx@@ -17,6 +17,7 @@ import { getProviderTitle } from '@/lib/utils'import { useTranslation } from '@/i18n/react-i18next-compat'import { getModelCapabilities } from '@/lib/models'import { toast } from 'sonner'+import { ExternalAnchor } from '@/components/ExternalAnchor'type DialogAddModelProps = {provider: ModelProvider@@ -122,10 +123,8 @@ export const DialogAddModel = ({ provider, trigger }: DialogAddModelProps) => {{/* Explore models link */}{provider.explore_models_url && (<div className="text-sm text-muted-foreground">- <a+ <ExternalAnchorhref={provider.explore_models_url}- target="_blank"- rel="noopener noreferrer"className="flex items-center gap-1 hover:underline"><span>@@ -133,7 +132,7 @@ export const DialogAddModel = ({ provider, trigger }: DialogAddModelProps) => {provider: getProviderTitle(provider.provider),})}</span>- </a>+ </ExternalAnchor></div>)}diff --git a/web-app/src/containers/dialogs/AppUpdater.tsx b/web-app/src/containers/dialogs/AppUpdater.tsxindex 8fd8ad915..755667680 100644--- a/web-app/src/containers/dialogs/AppUpdater.tsx+++ b/web-app/src/containers/dialogs/AppUpdater.tsx@@ -80,13 +80,6 @@ const DialogAppUpdater = () => {) : (<RenderMarkdowncomponents={{- a: ({ ...props }) => (- <a- {...props}- target="_blank"- rel="noopener noreferrer"- />- ),h2: ({ ...props }) => (<h2 {...props} className="text-xl! mt-0!" />),diff --git a/web-app/src/containers/message/WebToolWidget.tsx b/web-app/src/containers/message/WebToolWidget.tsxindex 89c267437..36a3ead63 100644--- a/web-app/src/containers/message/WebToolWidget.tsx+++ b/web-app/src/containers/message/WebToolWidget.tsx@@ -11,6 +11,7 @@ import {} from '@/lib/toolPresentation'import { faviconForUrl, hostOf } from '@/lib/webUrl'import { ToolBar } from './ToolBar'+import { ExternalAnchor } from '@/components/ExternalAnchor'const Favicon = ({ url }: { url: string }) => (<img@@ -27,10 +28,8 @@ const ResultRow = ({url: stringtitle?: string}) => (- <a+ <ExternalAnchorhref={url}- target="_blank"- rel="noreferrer noopener"className="flex items-center gap-2 rounded-md px-2 py-1.5 no-underline transition-colors hover:bg-secondary"title={url}>@@ -41,7 +40,7 @@ const ResultRow = ({<span className="shrink-0 text-xs text-muted-foreground/70">{hostOf(url)}</span>- </a>+ </ExternalAnchor>)export type WebToolWidgetProps = {diff --git a/web-app/src/routes/hub/$modelId.tsx b/web-app/src/routes/hub/$modelId.tsxindex a2eb50ca2..ed7a6c5a8 100644--- a/web-app/src/routes/hub/$modelId.tsx+++ b/web-app/src/routes/hub/$modelId.tsx@@ -275,15 +275,6 @@ function HubModelDetailContent() {<div className="text-muted-foreground mb-4"><RenderMarkdownclassName="select-none reset-heading"- components={{- a: ({ ...props }) => (- <a- {...props}- target="_blank"- rel="noopener noreferrer"- />- ),- }}content={extractDescription(modelData.description) ||modelData.description@@ -494,17 +485,7 @@ function HubModelDetailContent() {</div>) : readmeContent ? (<div className="prose prose-invert max-w-none">- <RenderMarkdown- components={{- a: ({ ...props }) => (- <a- {...props}- target="_blank"- rel="noopener noreferrer"- />- ),- }}- content={readmeContent}+ <RenderMarkdown content={readmeContent}/></div>) : (diff --git a/web-app/src/routes/hub/index.tsx b/web-app/src/routes/hub/index.tsxindex 1dfd2f4b6..d32291dd4 100644--- a/web-app/src/routes/hub/index.tsx+++ b/web-app/src/routes/hub/index.tsx@@ -611,15 +611,6 @@ function HubContent() {<div className="line-clamp-2 mt-3 text-muted-foreground leading-normal"><RenderMarkdownclassName="select-none reset-heading"- components={{- a: ({ ...props }) => (- <a- {...props}- target="_blank"- rel="noopener noreferrer"- />- ),- }}content={extractDescription(filteredModels[virtualItem.index]?.descriptiondiff --git a/web-app/src/routes/settings/extensions.tsx b/web-app/src/routes/settings/extensions.tsxindex 13e870e00..5ed18aa87 100644--- a/web-app/src/routes/settings/extensions.tsx+++ b/web-app/src/routes/settings/extensions.tsx@@ -58,14 +58,6 @@ function ExtensionsContent() {<RenderMarkdowncontent={item.description ?? ''}components={{- // Make links open in a new tab- a: ({ ...props }) => (- <a- {...props}- target="_blank"- rel="noopener noreferrer"- />- ),// Custom paragraph component remove marginp: ({ ...props }) => (<p {...props} className="mb-0!" />diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsxindex a12153777..ea99fb7ee 100644--- a/web-app/src/routes/settings/providers/$providerName.tsx+++ b/web-app/src/routes/settings/providers/$providerName.tsx@@ -775,16 +775,6 @@ function ProviderDetail() {className="![>p]:text-muted-foreground select-none"content={setting.description}components={{- // Make links open in a new tab- a: ({ ...props }) => {- return (- <a- {...props}- target="_blank"- rel="noopener noreferrer"- />- )- },p: ({ ...props }) => (<p {...props} className="mb-0!" />),