fix(ui): open and link only http(s) or same-origin URLs from user and agent content (#22639)

## 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 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-23 09:37:06 -06:00
1 parent b7dea0f070
commit ad163d0e36
28 files changed
+256 -128

No files matched your search

@@ -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");
});
+1
View File
@@ -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("/")
@@ -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",
+3 -2
View File
@@ -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);
}
}}
>
+2 -5
View File
@@ -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<string, unknown>)
: {};
const href =
typeof source.url === "string" &&
/^https?:\/\//.test(source.url)
? source.url
: null;
const href = safeExternalHttpUrl(source.url);
return (
<div key={String(source.sourceId ?? index)}>
{href ? (
@@ -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({
</Collapsible>
) : <p className="flex items-center gap-1.5">{status}</p>}
{detail ? <p className={cn("break-words", state === "failed" && "text-destructive")}>{detail}</p> : null}
{state === "executed" && result?.resultHref?.trim() ? (
<a className="inline-flex items-center gap-1 underline underline-offset-4 hover:text-foreground" href={result.resultHref} target="_blank" rel="noreferrer">View result<ExternalLink className="h-3 w-3" /></a>
{state === "executed" && safeNavigableUrl(result?.resultHref) ? (
<a className="inline-flex items-center gap-1 underline underline-offset-4 hover:text-foreground" href={safeNavigableUrl(result?.resultHref) ?? undefined} target="_blank" rel="noreferrer">View result<ExternalLink className="h-3 w-3" /></a>
) : null}
</div>
);
@@ -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(
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<MarkdownBody onImageClick={onImageClick}>{markdown}</MarkdownBody>
</ThemeProvider>
</QueryClientProvider>,
);
});
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());
});
});
+14 -9
View File
@@ -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 (
<img
{...imgProps}
src={finalSrc}
alt={alt ?? ""}
role={onImageClick && finalSrc ? "button" : undefined}
tabIndex={onImageClick && finalSrc ? 0 : undefined}
aria-label={onImageClick && finalSrc ? `Open image: ${alt || "Untitled image"}` : undefined}
onClick={onImageClick && finalSrc ? (e) => {
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")}
/>
);
};
+3 -13
View File
@@ -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,
},
@@ -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({
/>
</div>
<div className="space-y-1 text-xs text-muted-foreground">
{item.url ? (
<a href={item.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 hover:underline">
{safeExternalHttpUrl(item.url) ? (
<a href={safeExternalHttpUrl(item.url) ?? undefined} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 hover:underline">
{item.url}
<ExternalLink className="h-3.5 w-3.5" />
</a>
@@ -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;
@@ -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 ? (
<a
href={entry.url ?? undefined}
href={safeExternalHttpUrl(entry.url) ?? undefined}
target="_blank"
rel="noreferrer"
title={entry.url ?? undefined}
@@ -184,7 +185,7 @@ function UrlSegment({ entry, compact }: { entry: WorkspaceServiceControlEntry; c
title="Open in new tab"
>
{live ? (
<a href={entry.url ?? undefined} target="_blank" rel="noreferrer" aria-label="Open in new tab">
<a href={safeExternalHttpUrl(entry.url) ?? undefined} target="_blank" rel="noreferrer" aria-label="Open in new tab">
<ExternalLink className="size-3" />
</a>
) : (
@@ -379,7 +380,7 @@ function ServicePopoverRow({
{live && entry.url ? (
<>
<a
href={entry.url}
href={safeExternalHttpUrl(entry.url) ?? undefined}
target="_blank"
rel="noreferrer"
title={entry.url}
@@ -90,9 +90,10 @@ function Card({ children }: { children: ReactNode }) {
}
function SourceLink({ url, children }: { url: string; children: ReactNode }) {
return url ? (
const safeUrl = artifactUrl(url);
return safeUrl ? (
<Button variant="outline" size="sm" asChild>
<a href={url} target="_blank" rel="noreferrer">
<a href={safeUrl} target="_blank" rel="noreferrer">
{children}
<ExternalLink className="size-3" />
</a>
@@ -522,7 +523,7 @@ export function DataCard(props: DataCardProps) {
<a
download={props.filename}
href={
props.downloadUrl ||
artifactUrl(props.downloadUrl) ||
`data:text/csv;charset=utf-8,${encodeURIComponent(csv)}`
}
>
@@ -734,9 +735,9 @@ export function FileCard(props: FileCardProps) {
{props.openUrl && (
<SourceLink url={props.openUrl}>Open file</SourceLink>
)}
{props.downloadUrl ? (
{artifactUrl(props.downloadUrl) ? (
<Button asChild size="sm" variant="outline">
<a href={props.downloadUrl} download={props.filename}>
<a href={artifactUrl(props.downloadUrl)} download={props.filename}>
Download file
</a>
</Button>
@@ -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 ? (
<Link to={to} aria-label={label} data-testid={`${testId}-open`} className={CONTROL_CLASS}>
{content}
</Link>
) : href ? (
) : safeHref ? (
<a
href={href}
href={safeHref}
target={external ? "_blank" : undefined}
rel={external ? "noreferrer" : undefined}
aria-label={label}
+2 -1
View File
@@ -9,6 +9,7 @@ import {
type McpAppDisplayMode,
type McpAppHostContext,
} from "./mcp-app-host";
import { openSafeUrl } from "@/lib/safe-url";
const MAX_HEIGHT = 640;
const INITIAL_HEIGHT = 120;
@@ -115,7 +116,7 @@ export function McpAppFrame({
get toolInput() { return latest.current.toolInput; },
get toolResult() { return latest.current.toolResult; },
callTool: (name, args) => 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) } : {}),
@@ -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();
});
});
+2 -12
View File
@@ -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;
@@ -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 ? <button type="button" /> :
<a
href={ref.openPath ?? ref.url}
href={safeNavigableUrl(ref.openPath ?? ref.url) ?? undefined}
onClick={(event) => {
if (openText && ref.id && isTextAttachment({ contentType: ref.contentType ?? "", originalFilename: ref.name }) && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey) {
event.preventDefault(); openText(ref.id, ref.name);
@@ -29,6 +29,7 @@ import {
providerNoticeSeverity,
} from "./task-chat-activity-presentation";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { safeNavigableUrl } from "@/lib/safe-url";
const COMPACT_RESEARCH_RESULT_LIMIT = 5;
const COMPACT_WORKSPACE_FILE_LIMIT = 8;
@@ -269,30 +270,18 @@ function detailContent(item: TaskChatProtocolItem, neutral = false): ReactNode |
}
}
function safeActivityHref(value: string | null | undefined): string | undefined {
if (!value) return undefined;
try {
// A fixed HTTPS base accepts relative app paths and fragments as well as
// external HTTP(S) resources, but never executable or local-file schemes.
const url = new URL(value, "https://paperclip.invalid");
return url.protocol === "https:" || url.protocol === "http:" ? value : undefined;
} catch {
return undefined;
}
}
export function hasTaskChatProtocolActivityDetails(item: TaskChatProtocolItem): boolean {
if (item.surface === "provider_activity" && item.autoReview) return true;
// A check expands only when it has an outcome that may not fit on one line.
if (item.surface === "provider_activity" && item.family === "verification") return detailContent(item) !== null;
if (item.surface === "resource") return Boolean(safeActivityHref(item.href));
if (item.surface === "resource") return Boolean(safeNavigableUrl(item.href));
return detailContent(item) !== null || (item.surface === "provider_activity" && Boolean(item.summary?.trim()));
}
export function TaskChatProtocolActivityDetails({ item, neutral = false }: { item: TaskChatProtocolItem; neutral?: boolean }) {
const detail = detailContent(item, neutral);
if (item.surface === "resource") {
const href = safeActivityHref(item.href);
const href = safeNavigableUrl(item.href);
return href ? <a href={href} className="text-foreground underline">{item.title}</a> : <p>{item.title}</p>;
}
return <>{item.surface === "provider_activity" && item.family !== "verification" && item.summary ? <p className="whitespace-pre-wrap break-words">{item.summary}</p> : null}{detail}{item.surface === "provider_activity" && item.autoReview ? <AutoReviewDetail review={item.autoReview} /> : null}</>;
@@ -419,7 +408,7 @@ export function TaskChatProtocolActivityRow({ item }: { item: TaskChatProtocolIt
</>
);
const resourceHref = item.surface === "resource" ? safeActivityHref(item.href) : undefined;
const resourceHref = item.surface === "resource" ? (safeNavigableUrl(item.href) ?? undefined) : undefined;
if (resourceHref) {
return (
<a className="group/activity -mx-1.5 flex min-h-6 w-full min-w-0 max-w-full items-center gap-2 overflow-hidden rounded-sm px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground" href={resourceHref} data-testid="task-chat-protocol-activity-row">
@@ -35,6 +35,7 @@ import {
toolActivityPresentation,
toolTaxonomy,
} from "./tool-taxonomy";
import { safeExternalHttpUrl } from "@/lib/safe-url";
const TERMINAL_STATUSES = new Set([
"failed",
@@ -329,17 +330,6 @@ function titleCaseKey(value: string): string {
.replace(/\b\w/g, (letter) => letter.toUpperCase());
}
function safeHttpHref(value: unknown): string | null {
const href = stringValue(value);
if (!href) return null;
try {
const url = new URL(href);
return url.protocol === "http:" || url.protocol === "https:" ? href : null;
} catch {
return null;
}
}
const PROVIDER_DETAIL_KEYS: Record<
TaskChatProviderActivityItem["family"],
readonly string[]
@@ -504,7 +494,7 @@ function providerActivityItem(
.map(objectRecord)
.slice(0, 64)
.flatMap((source) => {
const href = safeHttpHref(source.url);
const href = safeExternalHttpUrl(source.url);
return href
? [
{
+6 -7
View File
@@ -1,3 +1,5 @@
import { safeExternalHttpUrl, safeNavigableUrl } from "./safe-url";
/** Optional producer metadata must never become invented facts in an artifact card. */
export function artifactText(
metadata: Record<string, unknown> | null,
@@ -24,13 +26,10 @@ export function artifactNumber(
export function artifactUrl(value: string | null | undefined): string {
if (!value || /[\u0000-\u0020\\]/.test(value)) return "";
if (value.startsWith("/") && !value.startsWith("//")) return value;
try {
const url = new URL(value);
return ["https:", "http:"].includes(url.protocol) ? value : "";
} catch {
return "";
}
const safe = value.startsWith("/") && !value.startsWith("//")
? safeNavigableUrl(value)
: safeExternalHttpUrl(value);
return safe ?? "";
}
/** Optional link thumbnails and video posters must not contact producer-chosen hosts. */
+4 -3
View File
@@ -57,6 +57,7 @@ import type {
SuggestTasksInteraction,
SuggestTasksResultCreatedTask,
} from "@paperclipai/shared";
import { safeExternalHttpUrl, safeNavigableUrl } from "./safe-url";
export function isInteractionPreparingApproval(interaction: IssueThreadInteraction): boolean {
return interaction.status === "pending"
@@ -194,9 +195,9 @@ export function getCheckboxConfirmationSelectedLabels(args: {
export function normalizeRequestConfirmationTargetHref(href: string) {
const value = href.trim();
if (value.startsWith("#")) return value;
if (value.startsWith("/")) return value.startsWith("//") ? null : value;
return /^https?:\/\//i.test(value) ? value : null;
if (value.startsWith("//")) return null;
if (value.startsWith("#") || value.startsWith("/")) return safeNavigableUrl(value);
return safeExternalHttpUrl(value);
}
export function getRequestConfirmationTargetHref({
+86
View File
@@ -0,0 +1,86 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
import { openSafeUrl, safeExternalHttpUrl, safeNavigableUrl } from "./safe-url";
const hostileInputs: ReadonlyArray<readonly [string, unknown]> = [
["javascript scheme", "javascript:alert(1)"],
["javascript scheme with an issue path", "javascript:alert(1)//issues/PAP-1"],
["mixed-case javascript scheme", "JaVaScRiPt:alert(1)"],
["javascript scheme after leading whitespace", " javascript:alert(1)"],
["javascript scheme after a control character", "\u0001javascript:alert(1)"],
["javascript scheme split by a tab", "java\tscript:alert(1)"],
["javascript scheme split by a newline", "java\nscript:alert(1)"],
["vbscript scheme", "vbscript:msgbox(1)"],
["html data URL", "data:text/html,<script>alert(1)</script>"],
["base64 data URL", "data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="],
["svg data URL", "data:image/svg+xml,<svg onload=alert(1)>"],
["file URL", "file:///etc/passwd"],
["blob URL", "blob:https://paperclip.ing/1234"],
["filesystem URL", "filesystem:https://paperclip.ing/temporary/x"],
["about URL", "about:blank"],
["custom app scheme", "paperclip-desktop://open"],
["mention scheme", "agent://agent-1"],
["empty string", ""],
["whitespace only", " "],
["null", null],
["undefined", undefined],
["number", 42],
["object", { href: "https://example.com" }],
];
afterEach(() => {
vi.restoreAllMocks();
});
describe("safeNavigableUrl", () => {
it.each(hostileInputs)("rejects %s", (_label, input) => {
expect(safeNavigableUrl(input)).toBeNull();
});
it.each([
["https URL", "https://example.com/a?b=c#d", "https://example.com/a?b=c#d"],
["http URL", "http://localhost:3100/issues/PAP-1", "http://localhost:3100/issues/PAP-1"],
["uppercase https scheme", "HTTPS://example.com/", "HTTPS://example.com/"],
["app-relative path", "/PAP/issues/PAP-1", "/PAP/issues/PAP-1"],
["fragment", "#comment-1", "#comment-1"],
["query", "?tab=files", "?tab=files"],
["path with surrounding whitespace", " /issues/PAP-1 ", "/issues/PAP-1"],
])("keeps %s", (_label, input, expected) => {
expect(safeNavigableUrl(input)).toBe(expected);
});
});
describe("safeExternalHttpUrl", () => {
it.each(hostileInputs)("rejects %s", (_label, input) => {
expect(safeExternalHttpUrl(input)).toBeNull();
});
it("rejects relative paths", () => {
expect(safeExternalHttpUrl("/issues/PAP-1")).toBeNull();
expect(safeExternalHttpUrl("#comment-1")).toBeNull();
});
it("keeps absolute http and https URLs", () => {
expect(safeExternalHttpUrl("https://example.com/x")).toBe("https://example.com/x");
expect(safeExternalHttpUrl("http://example.com/x")).toBe("http://example.com/x");
});
});
describe("openSafeUrl", () => {
it.each(hostileInputs)("does not open %s", (_label, input) => {
const open = vi.spyOn(window, "open").mockReturnValue(null);
expect(openSafeUrl(input)).toBe(false);
expect(open).not.toHaveBeenCalled();
});
it("opens http and same-origin URLs in a new context without an opener or referrer", () => {
const open = vi.spyOn(window, "open").mockReturnValue(null);
expect(openSafeUrl("https://example.com/image.png")).toBe(true);
expect(openSafeUrl("/api/attachments/1/content")).toBe(true);
expect(open.mock.calls).toEqual([
["https://example.com/image.png", "_blank", "noopener,noreferrer"],
["/api/attachments/1/content", "_blank", "noopener,noreferrer"],
]);
});
});
+38
View File
@@ -0,0 +1,38 @@
const FALLBACK_BASE = "https://paperclip.invalid/";
function currentBase(): string {
return typeof window !== "undefined" && window.location?.href ? window.location.href : FALLBACK_BASE;
}
function isHttpProtocol(protocol: string): boolean {
return protocol === "http:" || protocol === "https:";
}
function hasScheme(value: string): boolean {
return /^[a-z][a-z0-9+.-]*:/i.test(value.replace(/[\t\n\r]/g, ""));
}
export function safeNavigableUrl(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
if (!trimmed) return null;
if (/[\u0000-\u001f]/.test(trimmed)) return null;
try {
const url = new URL(trimmed, currentBase());
return isHttpProtocol(url.protocol) ? trimmed : null;
} catch {
return null;
}
}
export function safeExternalHttpUrl(value: unknown): string | null {
const safe = safeNavigableUrl(value);
return safe && hasScheme(safe) ? safe : null;
}
export function openSafeUrl(value: unknown): boolean {
const safe = safeNavigableUrl(value);
if (!safe) return false;
window.open(safe, "_blank", "noopener,noreferrer");
return true;
}
+2 -11
View File
@@ -52,6 +52,7 @@ import {
} from "../lib/workspace-routines";
import { useUpdateIssueMutation } from "../hooks/useUpdateIssueMutation";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { safeExternalHttpUrl } from "@/lib/safe-url";
type WorkspaceFormState = {
name: string;
@@ -133,16 +134,6 @@ function LegacyWorkspaceTabRedirect({ workspaceId }: { workspaceId: string }) {
return <Navigate to={executionWorkspaceTabPath(workspaceId, "issues")} replace />;
}
function isSafeExternalUrl(value: string | null | undefined) {
if (!value) return false;
try {
const parsed = new URL(value);
return parsed.protocol === "http:" || parsed.protocol === "https:";
} catch {
return false;
}
}
function readText(value: string | null | undefined) {
return value ?? "";
}
@@ -1506,7 +1497,7 @@ export function ExecutionWorkspaceDetail() {
{workspace.providerRef ? <MonoValue value={workspace.providerRef} copy /> : "None"}
</DetailRow>
<DetailRow label="Repo URL">
{workspace.repoUrl && isSafeExternalUrl(workspace.repoUrl) ? (
{workspace.repoUrl && safeExternalHttpUrl(workspace.repoUrl) ? (
<div className="inline-flex max-w-full items-start gap-2">
<a href={workspace.repoUrl} target="_blank" rel="noreferrer" className="inline-flex min-w-0 items-center gap-1 break-all hover:underline">
{workspace.repoUrl}
+2 -1
View File
@@ -426,6 +426,7 @@ import {
import { AgentQueueWaitChip } from "@/components/AgentQueueWait";
import { agentQueueWaitOf, isWaitingToStart } from "@/lib/agent-queue-wait";
import { taskStatusIconProps } from "@/lib/task-status-presentation";
import { openSafeUrl } from "@/lib/safe-url";
// Stable empty array for React Query `data` defaults. A literal `= []` default
// creates a new array reference on every render while `data` is undefined
@@ -6371,7 +6372,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
const handleChatImageClick = useCallback(
(src: string) => {
if (!openIssueGallery(src)) window.open(src, "_blank");
if (!openIssueGallery(src)) openSafeUrl(src);
},
[openIssueGallery],
);
+2 -11
View File
@@ -23,6 +23,7 @@ import { useCompany } from "../context/CompanyContext";
import { useManagedSandboxOnly } from "../hooks/useManagedSandboxOnly";
import { queryKeys } from "../lib/queryKeys";
import { projectRouteRef, projectWorkspaceUrl } from "../lib/utils";
import { safeExternalHttpUrl } from "@/lib/safe-url";
type WorkspaceFormState = {
name: string;
@@ -85,16 +86,6 @@ const VISIBILITY_OPTIONS: Array<{ value: ProjectWorkspaceVisibility; label: stri
{ value: "advanced", label: "Advanced" },
];
function isSafeExternalUrl(value: string | null | undefined) {
if (!value) return false;
try {
const parsed = new URL(value);
return parsed.protocol === "http:" || parsed.protocol === "https:";
} catch {
return false;
}
}
function isAbsolutePath(value: string) {
return value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value);
}
@@ -700,7 +691,7 @@ export function ProjectWorkspaceDetail() {
</DetailRow>
)}
<DetailRow label="Repo">
{workspace.repoUrl && isSafeExternalUrl(workspace.repoUrl) ? (
{workspace.repoUrl && safeExternalHttpUrl(workspace.repoUrl) ? (
<a href={workspace.repoUrl} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 hover:underline">
{workspace.repoUrl}
<ExternalLink className="h-3 w-3" />
@@ -46,6 +46,7 @@ import {
import { cn, relativeTime } from "@/lib/utils";
import { appTabHref } from "../app-tabs";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { safeExternalHttpUrl } from "@/lib/safe-url";
// ---------------------------------------------------------------------------
// Small format helpers
@@ -973,7 +974,7 @@ function PrettyPreview({ value }: { value: unknown }) {
function PreviewRowCard({ row, index }: { row: Record<string, unknown>; index: number }) {
const titleKey = ["title", "name", "label"].find((key) => typeof row[key] === "string" && row[key] !== "");
const summaryKey = ["highlight", "description", "summary"].find((key) => typeof row[key] === "string" && row[key] !== "");
const url = typeof row.url === "string" && /^https?:\/\//i.test(row.url) ? row.url : null;
const url = safeExternalHttpUrl(row.url);
const details = Object.entries(row)
.filter(([key]) => key !== titleKey && key !== summaryKey && (key !== "url" || !url))
.sort(([left], [right]) => {
+3 -1
View File
@@ -41,6 +41,7 @@ import { useToastActions, type ToastInput } from "@/context/ToastContext";
import { useSidebar } from "@/context/SidebarContext";
import { isGlobalPath, normalizeCompanyPrefix } from "@/lib/company-routes";
import { normalizeRememberedInstanceSettingsPath } from "@/lib/instance-settings";
import { safeExternalHttpUrl } from "@/lib/safe-url";
// ---------------------------------------------------------------------------
// Bridge error type (mirrors the SDK's PluginBridgeError)
@@ -527,7 +528,8 @@ export function useHostNavigation(): HostNavigation {
const href = resolveHref(to);
const sameOriginPath = sameOriginPathFromHref(href);
if (sameOriginPath === null) {
window.location.assign(href);
const safeHref = safeExternalHttpUrl(href);
if (safeHref) window.location.assign(safeHref);
return;
}
routerNavigate(sameOriginPath, options as NavigateOptions | undefined);