diff --git a/packages/shared/src/issue-references.test.ts b/packages/shared/src/issue-references.test.ts index d4af275ae8c..273873e8ecd 100644 --- a/packages/shared/src/issue-references.test.ts +++ b/packages/shared/src/issue-references.test.ts @@ -23,6 +23,17 @@ describe("issue references", () => { expect(parseIssueReferenceHref("https://paperclip.ing/projects/PAP-789")).toBeNull(); }); + it.each([ + "javascript:alert(1)//issues/PAP-1", + "JavaScript:void(0)//issues/PAP-1", + "data:text/html,x//issues/PAP-1", + "vbscript:x//issues/PAP-1", + "file:///issues/PAP-1", + "blob:https://paperclip.ing/issues/PAP-1", + ])("rejects issue hrefs with a non-http scheme: %s", (href) => { + expect(parseIssueReferenceHref(href)).toBeNull(); + }); + it("builds canonical issue hrefs", () => { expect(buildIssueReferenceHref("pap-123")).toBe("/issues/PAP-123"); }); diff --git a/packages/shared/src/issue-references.ts b/packages/shared/src/issue-references.ts index bfdd2126fb1..3516c974d3e 100644 --- a/packages/shared/src/issue-references.ts +++ b/packages/shared/src/issue-references.ts @@ -111,6 +111,7 @@ export function parseIssueReferenceHref(href: string): { identifier: string } | } catch { return null; } + if (url.protocol !== "http:" && url.protocol !== "https:") return null; const segments = url.pathname .split("/") diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 7d6211cc0c3..153f971299d 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -283,8 +283,8 @@ "packages/shared/src/issue-context-usage.ts": "2de0de824da2e4bce3c248335cdb5694d2a926ce", "packages/shared/src/issue-creation-source.test.ts": "afd00ce1ad8357daf860bc7e8e79340c765805f7", "packages/shared/src/issue-creation-source.ts": "48bd43f183b1a9f7bc233128ad0fe84c82e04c17", - "packages/shared/src/issue-references.test.ts": "d4af275ae8c615ccdc587dfbfd675cea8626e530", - "packages/shared/src/issue-references.ts": "bfdd2126fb12797f2c8177113285b2c3233aecef", + "packages/shared/src/issue-references.test.ts": "273873e8ecdb41aa9f88f76792880222822e39ee", + "packages/shared/src/issue-references.ts": "3516c974d3e1b8e9de3bc204408ea3f130705323", "packages/shared/src/issue-thread-interactions.test.ts": "6f516055744fcedd2e0c06ce82c6a1a019120762", "packages/shared/src/issue-write-denial.test.ts": "e21b93aa79e6635c019ac338eff954ec618a98ed", "packages/shared/src/issue-write-denial.ts": "e6b4d72a83f6e4e76e85e34a80f88d1d69b7dfe4", diff --git a/ui/src/components/ArtifactsPanel.tsx b/ui/src/components/ArtifactsPanel.tsx index f5a058b4baf..dbf6be9e9e0 100644 --- a/ui/src/components/ArtifactsPanel.tsx +++ b/ui/src/components/ArtifactsPanel.tsx @@ -22,6 +22,7 @@ import { } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; +import { openSafeUrl } from "@/lib/safe-url"; interface ArtifactsPanelProps { taskId: string; @@ -185,8 +186,8 @@ export function ArtifactsPanel({ taskId, isAgentWorking, openDocKey, openDocTitl onClick={() => { if (wp.type === "document") { setViewingDoc({ key: "plan", title: wp.title }); - } else if (wp.url) { - window.open(wp.url, "_blank", "noopener,noreferrer"); + } else { + openSafeUrl(wp.url); } }} > diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsx index ff4dd72d0ab..3b575b0e2e6 100644 --- a/ui/src/components/IssueChatThread.tsx +++ b/ui/src/components/IssueChatThread.tsx @@ -280,6 +280,7 @@ import { import { SourceTrustBadge } from "./SourceTrustBadge"; import { CommentAttributionChip } from "./CommentAttributionChip"; import { resolveCommentAttribution } from "../lib/comment-attribution"; +import { safeExternalHttpUrl } from "../lib/safe-url"; interface IssueChatMessageContext { feedbackDataSharingPreference: FeedbackDataSharingPreference; @@ -1906,11 +1907,7 @@ function IssueChatProviderActivity({ typeof entry === "object" && entry !== null ? (entry as Record) : {}; - const href = - typeof source.url === "string" && - /^https?:\/\//.test(source.url) - ? source.url - : null; + const href = safeExternalHttpUrl(source.url); return (
{href ? ( diff --git a/ui/src/components/IssueThreadInteractionCard.tsx b/ui/src/components/IssueThreadInteractionCard.tsx index ec2e911c3c0..cc3e09be9f2 100644 --- a/ui/src/components/IssueThreadInteractionCard.tsx +++ b/ui/src/components/IssueThreadInteractionCard.tsx @@ -33,6 +33,7 @@ import { type SuggestedTaskDraft, type SuggestedTaskTreeNode, } from "../lib/issue-thread-interactions"; +import { safeNavigableUrl } from "../lib/safe-url"; import { cn, formatDateTime, formatShortDate } from "../lib/utils"; import { InteractionPreparationNotice } from "./InteractionPreparationNotice"; import { InteractionAudienceLine } from "./InteractionAudienceLine"; @@ -1746,7 +1747,8 @@ function requestConfirmationTargetHref({ if (target.type === "issue_attachment") { return `/api/attachments/${encodeURIComponent(target.attachmentId)}/content`; } - if (target.href) return target.href; + const safeTargetHref = target.href ? normalizeRequestConfirmationTargetHref(target.href) : null; + if (safeTargetHref) return safeTargetHref; if (target.type === "issue_document") { const issueId = target.issueId ?? interaction.issueId; return `/issues/${issueId}#document-${encodeURIComponent(target.key)}`; @@ -1992,8 +1994,8 @@ function ToolActionResolution({ ) :

{status}

} {detail ?

{detail}

: null} - {state === "executed" && result?.resultHref?.trim() ? ( - View result + {state === "executed" && safeNavigableUrl(result?.resultHref) ? ( + View result ) : null}
); diff --git a/ui/src/components/MarkdownBody.interaction.test.tsx b/ui/src/components/MarkdownBody.interaction.test.tsx index 6931815af35..6b53fe30484 100644 --- a/ui/src/components/MarkdownBody.interaction.test.tsx +++ b/ui/src/components/MarkdownBody.interaction.test.tsx @@ -120,3 +120,42 @@ describe("MarkdownBody code block interactions", () => { expect(wrapButton?.getAttribute("aria-label")).toBe("Wrap lines"); }); }); + +describe("MarkdownBody image clicks", () => { + function renderWithImageClick(markdown: string, onImageClick: (src: string) => void) { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + flushSync(() => { + root?.render( + + + {markdown} + + , + ); + }); + return container; + } + + it.each([ + "javascript:alert(1)//issues/PAP-1", + "javascript:alert(1)", + "data:text/html,x//issues/PAP-1", + ])("never hands an unsafe image URL to the click handler: %s", (src) => { + const onImageClick = vi.fn(); + const node = renderWithImageClick(`![x](${src})`, onImageClick); + const image = node.querySelector("img"); + if (image) click(image); + expect(onImageClick).not.toHaveBeenCalled(); + expect(image?.getAttribute("src") ?? "").not.toMatch(/^(javascript|data):/i); + }); + + it("hands an http image URL to the click handler", () => { + const onImageClick = vi.fn(); + const node = renderWithImageClick("![x](https://example.com/a.png)", onImageClick); + click(node.querySelector("img")); + expect(onImageClick).toHaveBeenCalledWith("https://example.com/a.png", expect.anything()); + }); +}); diff --git a/ui/src/components/MarkdownBody.tsx b/ui/src/components/MarkdownBody.tsx index c220252c4d4..ae784b31a6f 100644 --- a/ui/src/components/MarkdownBody.tsx +++ b/ui/src/components/MarkdownBody.tsx @@ -51,6 +51,7 @@ import { externalObjectProviderLabel, } from "../lib/external-objects"; import { normalizeExternalObjectHref } from "../lib/external-object-href"; +import { safeNavigableUrl } from "../lib/safe-url"; import { copyTextToClipboard } from "../lib/clipboard"; import type { Agent, @@ -435,7 +436,10 @@ function extractMermaidSource(children: ReactNode): string | null { function safeMarkdownUrlTransform(url: string): string { if (url.startsWith(WORKSPACE_FILE_HREF_PREFIX)) return url; - return parseMentionChipHref(url) ? url : defaultUrlTransform(url); + const mention = parseMentionChipHref(url); + if (!mention) return defaultUrlTransform(url); + if (mention.kind === "issue") return safeNavigableUrl(url) ?? ""; + return url; } type MarkdownAstNode = { @@ -1004,26 +1008,27 @@ function MarkdownBodyImpl({ map.img = ({ node: _node, src, alt, ...imgProps }) => { const resolved = resolveImageSrc && src ? resolveImageSrc(src) : null; const finalSrc = resolved ?? src; + const clickSrc = onImageClick ? safeNavigableUrl(finalSrc) : null; return ( {alt { + role={clickSrc ? "button" : undefined} + tabIndex={clickSrc ? 0 : undefined} + aria-label={clickSrc ? `Open image: ${alt || "Untitled image"}` : undefined} + onClick={onImageClick && clickSrc ? (e) => { e.preventDefault(); e.stopPropagation(); - onImageClick(finalSrc, e.currentTarget); + onImageClick(clickSrc, e.currentTarget); } : undefined} - onKeyDown={onImageClick && finalSrc ? (e) => { + onKeyDown={onImageClick && clickSrc ? (e) => { if (e.key !== "Enter" && e.key !== " ") return; e.preventDefault(); e.stopPropagation(); - onImageClick(finalSrc, e.currentTarget); + onImageClick(clickSrc, e.currentTarget); } : undefined} - className={cn(imgProps.className, onImageClick && "cursor-pointer")} + className={cn(imgProps.className, clickSrc && "cursor-pointer")} /> ); }; diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsx index b28cde32a13..77f0ce220cb 100644 --- a/ui/src/components/TaskChatThread.tsx +++ b/ui/src/components/TaskChatThread.tsx @@ -162,6 +162,7 @@ import { queryKeys } from "@/lib/queryKeys"; import { useQueryClient } from "@tanstack/react-query"; import { TaskChatPresentationProvider } from "@/components/task-chat/presentation-mode"; import { isRunStopConfirmed } from "@/lib/wait-for-stopped-runs"; +import { safeNavigableUrl } from "@/lib/safe-url"; const EMPTY_BROWSERS: TaskBrowser[] = []; const COMPACT_RUN_LOG_READ_LIMIT_BYTES = 32_000; @@ -176,17 +177,6 @@ function normalizedMessageText(value: string | null | undefined): string { return (value ?? "").trim().replace(/\s+/g, " "); } -function safeResourceHref(value: string | null | undefined): string | null { - if (!value) return null; - if (value.startsWith("/") || value.startsWith("#")) return value; - try { - const url = new URL(value); - return url.protocol === "http:" || url.protocol === "https:" ? value : null; - } catch { - return null; - } -} - function formatResourceBytes(value: number): string { if (value < 1024) return `${value} B`; if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`; @@ -1441,7 +1431,7 @@ export function TaskChatThread(props: TaskChatThreadProps) { ] .filter(Boolean) .join(" · "), - href: safeResourceHref(href), + href: safeNavigableUrl(href), timestamp: new Date(workProduct.createdAt).toISOString(), workProduct, }, @@ -1463,7 +1453,7 @@ export function TaskChatThread(props: TaskChatThreadProps) { resourceKind: "attachment", title: attachment.originalFilename ?? "Agent attachment", subtitle: `${attachment.contentType} · ${formatResourceBytes(attachment.byteSize)}`, - href: safeResourceHref(attachment.openPath ?? attachment.contentPath), + href: safeNavigableUrl(attachment.openPath ?? attachment.contentPath), timestamp: new Date(attachment.createdAt).toISOString(), attachment, }, diff --git a/ui/src/components/WorkspaceRuntimeControls.tsx b/ui/src/components/WorkspaceRuntimeControls.tsx index 4b94d1de89a..4a1b76878a4 100644 --- a/ui/src/components/WorkspaceRuntimeControls.tsx +++ b/ui/src/components/WorkspaceRuntimeControls.tsx @@ -18,6 +18,7 @@ import type { WorkspaceServiceControlAction, WorkspaceServiceControlEntry, } from "@/components/WorkspaceServiceControlBar"; +import { safeExternalHttpUrl } from "../lib/safe-url"; export type WorkspaceRuntimeAction = "start" | "stop" | "restart" | "run"; @@ -470,8 +471,8 @@ function CommandSection({ />
- {item.url ? ( - + {safeExternalHttpUrl(item.url) ? ( + {item.url} @@ -605,7 +606,7 @@ export function WorkspaceRuntimeQuickControls({ iconOnly?: boolean; }) { const controlItems = sections.services.length > 0 ? sections.services : sections.otherServices; - const serviceUrl = getRunningRuntimeServiceUrl(sections); + const serviceUrl = safeExternalHttpUrl(getRunningRuntimeServiceUrl(sections)); const alignEnd = align === "end"; if (controlItems.length === 0 && !serviceUrl) return null; diff --git a/ui/src/components/WorkspaceServiceControlBar.tsx b/ui/src/components/WorkspaceServiceControlBar.tsx index 2f27d8b27a0..1d6bdd5dc86 100644 --- a/ui/src/components/WorkspaceServiceControlBar.tsx +++ b/ui/src/components/WorkspaceServiceControlBar.tsx @@ -14,6 +14,7 @@ import { Button } from "@/components/ui/button"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { cn } from "@/lib/utils"; import { copyTextToClipboard } from "@/lib/clipboard"; +import { safeExternalHttpUrl } from "../lib/safe-url"; export type WorkspaceServiceControlState = | "stopped" @@ -157,7 +158,7 @@ function UrlSegment({ entry, compact }: { entry: WorkspaceServiceControlEntry; c <> {live ? ( {live ? ( - + ) : ( @@ -379,7 +380,7 @@ function ServicePopoverRow({ {live && entry.url ? ( <> - + {children} @@ -522,7 +523,7 @@ export function DataCard(props: DataCardProps) { @@ -734,9 +735,9 @@ export function FileCard(props: FileCardProps) { {props.openUrl && ( Open file )} - {props.downloadUrl ? ( + {artifactUrl(props.downloadUrl) ? ( diff --git a/ui/src/components/artifacts/v1/ArtifactRow.tsx b/ui/src/components/artifacts/v1/ArtifactRow.tsx index ff896aa251d..39f4741872b 100644 --- a/ui/src/components/artifacts/v1/ArtifactRow.tsx +++ b/ui/src/components/artifacts/v1/ArtifactRow.tsx @@ -11,6 +11,7 @@ import { usePreviewFailure } from "./ArtifactPrint"; import { ROW_ICON, ROW_PLAY } from "./geometry"; import { glyphOf, isAudio, labelOf, previewSourceOf, treatmentOf, type ArtifactSubject } from "./kinds"; import { panelDateLabel } from "./when"; +import { safeNavigableUrl } from "@/lib/safe-url"; /** * One row, from the panel mock (node 2096:87691) and reused in the thread: @@ -148,13 +149,14 @@ export function ArtifactRow({ subject, to, href, external = false, onClick, expa ); const label = `Open ${name}`; + const safeHref = safeNavigableUrl(href); const control = to ? ( {content} - ) : href ? ( + ) : safeHref ? ( latest.current.callTool(name, args), - openLink: (url) => window.open(url, "_blank", "noopener,noreferrer"), + openLink: (url) => { openSafeUrl(url); }, ...(canProposeMessages ? { proposeMessage: (text: string) => latest.current.proposeMessage!(text) } : {}), ...(canUpdateModelContext ? { updateModelContext: (context: McpAppModelContext | null) => latest.current.updateModelContext!(context) } : {}), ...(canChangeDisplayMode ? { setDisplayMode: (mode: McpAppDisplayMode) => latest.current.onRequestDisplayMode?.(mode) } : {}), diff --git a/ui/src/components/mcp-app/mcp-app-host.test.ts b/ui/src/components/mcp-app/mcp-app-host.test.ts index 335ee89b3d0..158c7fece5c 100644 --- a/ui/src/components/mcp-app/mcp-app-host.test.ts +++ b/ui/src/components/mcp-app/mcp-app-host.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { createMcpAppHost, MCP_APP_ESCAPE_NOTIFICATION, MCP_APP_NAVIGATION_GUARD, mcpAppDocument, safeExternalUrl, type McpAppHostContext } from "./mcp-app-host"; +import { createMcpAppHost, MCP_APP_ESCAPE_NOTIFICATION, MCP_APP_NAVIGATION_GUARD, mcpAppDocument, type McpAppHostContext } from "./mcp-app-host"; const hostContext: McpAppHostContext = { theme: "dark", @@ -300,8 +300,4 @@ describe("mcpAppDocument", () => { expect(onEscape).toHaveBeenCalledTimes(1); }); - it("allows only http(s) external urls", () => { - expect(safeExternalUrl("https://circleback.ai")).toBe("https://circleback.ai/"); - expect(safeExternalUrl("data:text/html,x")).toBeNull(); - }); }); diff --git a/ui/src/components/mcp-app/mcp-app-host.ts b/ui/src/components/mcp-app/mcp-app-host.ts index b209fbc2f8b..d6a2e34ea7a 100644 --- a/ui/src/components/mcp-app/mcp-app-host.ts +++ b/ui/src/components/mcp-app/mcp-app-host.ts @@ -7,6 +7,7 @@ import { type McpAppModelContext, type McpAppResourceCsp, } from "@paperclipai/shared"; +import { safeExternalHttpUrl } from "../../lib/safe-url"; /** * Host side of the MCP Apps postMessage protocol (spec 2026-01-26). Pure and @@ -90,17 +91,6 @@ export function isJsonRpcMessage(value: unknown): value is JsonRpcMessage { return message?.jsonrpc === "2.0" && (typeof message.method === "string" || "id" in message); } -/** Only http(s) links leave the sandbox, and always into a new browsing context. */ -export function safeExternalUrl(value: unknown): string | null { - if (typeof value !== "string") return null; - try { - const url = new URL(value); - return url.protocol === "https:" || url.protocol === "http:" ? url.toString() : null; - } catch { - return null; - } -} - export function createMcpAppHost(options: McpAppHostOptions) { let initialized = false; // Set once this document has sent `ui/initialize`. Requests that act on the @@ -176,7 +166,7 @@ export function createMcpAppHost(options: McpAppHostOptions) { return; } case "ui/open-link": { - const url = safeExternalUrl(params.url); + const url = safeExternalHttpUrl(params.url); if (!url) { fail(message.id, SERVER_ERROR, "Only http and https links can be opened"); return; diff --git a/ui/src/components/task-chat/TaskChatBubble.tsx b/ui/src/components/task-chat/TaskChatBubble.tsx index da38b567dff..56f4177d7e2 100644 --- a/ui/src/components/task-chat/TaskChatBubble.tsx +++ b/ui/src/components/task-chat/TaskChatBubble.tsx @@ -45,6 +45,7 @@ import { import { TaskChatBubbleActions } from "./TaskChatBubbleActions"; import { TaskChatSystemNotice } from "./TaskChatSystemNotice"; import type { TaskChatMessageItem } from "./task-chat-model"; +import { safeNavigableUrl } from "@/lib/safe-url"; interface TaskChatBubbleProps { item: TaskChatMessageItem; @@ -372,7 +373,7 @@ function TaskChatBubbleContent({ onClick={video ? () => openImage(ref.url) : undefined} render={video ?