From ad163d0e360147bfee10bb31f56cd9696a093782 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:37:06 -0600 Subject: [PATCH] fix(ui): open and link only http(s) or same-origin URLs from user and agent content (#22639) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The board UI shows content that agents and people write: comments, tool results, work products, approval cards and runtime links > - Some of this content becomes a link, an image or a new window > - Some of these places did not limit the URL scheme, and the chat image click opened the URL without `noopener` > - A URL with a script scheme must never open or navigate from the board, because it would run with the board origin > - This pull request adds one URL helper and routes the content-fed link, image-click and window sinks through it > - The benefit is that only http(s) or same-origin URLs can open from user or agent content, and new windows never get an opener ## Linked Issues or Issue Description **What happened?** The issue-reference parser accepted a URL with any scheme when its path contained an issue path. The markdown renderer trusted that match and kept the URL. The chat image click then gave the URL to `window.open` with no scheme check and no `noopener`. Several other components had their own copies of a scheme check, and some links used content URLs with no check. **What did you expect?** The board opens or links only http(s) URLs and same-origin paths from user or agent content. New windows open with `noopener,noreferrer`. **Steps to reproduce** Render markdown with an image whose URL uses a non-http scheme and an issue path, then click the image. The new unit tests cover this case. **Impact** Defense-in-depth hardening of the board UI against unsafe URLs in stored content. ## What Changed - Add `ui/src/lib/safe-url.ts` with `safeNavigableUrl` (http(s) or same-origin), `safeExternalHttpUrl` (absolute http(s) only) and `openSafeUrl` (opens with `noopener,noreferrer`). - `parseIssueReferenceHref` in `packages/shared` now accepts only relative paths and http(s) URLs. - `MarkdownBody` keeps the issue-reference shortcut only for safe URLs. The image click handler gets only a safe URL. - The task chat image click, the work products panel and MCP app links open through `openSafeUrl`. - The plugin bridge does a top-level navigation only to an http(s) URL. - Replace the local scheme checks in the task chat thread, protocol activity row, transcript adapter, MCP app host, workspace detail pages and artifact cards with the shared helper. - Apply the helper to artifact rows, rich artifact source and download links, approval result links, request-confirmation target links, attachment links in chat bubbles, provider source links, action test result links and runtime service links. - Refresh `tests/runner-e2e/source-sdk-public-inputs.json` for the changed shared files. ## Verification - `ui/src/lib/safe-url.test.ts`: one table of hostile inputs (script, data, file, blob, about and custom schemes, whitespace and control-character variants, non-string values) runs against each helper. It also checks that `openSafeUrl` uses `noopener,noreferrer`. - `ui/src/components/MarkdownBody.interaction.test.tsx`: an image with an unsafe URL never reaches the click handler. An http image still does. This test failed before the fix (the unsafe URL reached the handler) and passes now. - `packages/shared/src/issue-references.test.ts`: non-http schemes with an issue path return `null`. These cases failed before the fix and pass now. - A headless Chromium check confirmed the risk of the old call: a script URL opened with `window.open(url, "_blank")` ran with access to the opener. With `noopener,noreferrer` it did not reach the opener. - `npx vitest run` on the affected UI folders: 116 files, 2119 tests pass. `tsc --noEmit` for `ui` has no errors in `src`. - `pnpm verify` exits 2 because the pinned-input registry changed. Required CI gives the broad coverage. ## Risks - Low risk. A link from content with a non-http scheme (for example `mailto:` in an artifact source link) no longer renders as a link in the changed components. Markdown links keep the existing `react-markdown` URL rules. - Mention chips with their own schemes (agent, project, user, skill, routine) do not change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- packages/shared/src/issue-references.test.ts | 11 +++ packages/shared/src/issue-references.ts | 1 + .../runner-e2e/source-sdk-public-inputs.json | 4 +- ui/src/components/ArtifactsPanel.tsx | 5 +- ui/src/components/IssueChatThread.tsx | 7 +- .../components/IssueThreadInteractionCard.tsx | 8 +- .../MarkdownBody.interaction.test.tsx | 39 +++++++++ ui/src/components/MarkdownBody.tsx | 23 +++-- ui/src/components/TaskChatThread.tsx | 16 +--- .../components/WorkspaceRuntimeControls.tsx | 7 +- .../components/WorkspaceServiceControlBar.tsx | 7 +- .../artifacts/RichArtifactCards.tsx | 11 +-- .../components/artifacts/v1/ArtifactRow.tsx | 6 +- ui/src/components/mcp-app/McpAppFrame.tsx | 3 +- .../components/mcp-app/mcp-app-host.test.ts | 6 +- ui/src/components/mcp-app/mcp-app-host.ts | 14 +-- .../components/task-chat/TaskChatBubble.tsx | 3 +- .../task-chat/TaskChatProtocolActivityRow.tsx | 19 +--- .../task-chat/transcript-adapter.ts | 14 +-- ui/src/lib/artifact-card-data.ts | 13 ++- ui/src/lib/issue-thread-interactions.ts | 7 +- ui/src/lib/safe-url.test.ts | 86 +++++++++++++++++++ ui/src/lib/safe-url.ts | 38 ++++++++ ui/src/pages/ExecutionWorkspaceDetail.tsx | 13 +-- ui/src/pages/IssueDetail.tsx | 3 +- ui/src/pages/ProjectWorkspaceDetail.tsx | 13 +-- .../apps/app-detail/ActionTestDialog.tsx | 3 +- ui/src/plugins/bridge.ts | 4 +- 28 files changed, 256 insertions(+), 128 deletions(-) create mode 100644 ui/src/lib/safe-url.test.ts create mode 100644 ui/src/lib/safe-url.ts 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 ?