mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 22:49:00 +01:00
## 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>
164 lines
4.9 KiB
TypeScript
164 lines
4.9 KiB
TypeScript
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,
|
|
...keys: string[]
|
|
): string {
|
|
for (const key of keys) {
|
|
const value = metadata?.[key];
|
|
if (typeof value === "string" && value.trim()) return value.trim();
|
|
}
|
|
return "";
|
|
}
|
|
|
|
export function artifactNumber(
|
|
metadata: Record<string, unknown> | null,
|
|
...keys: string[]
|
|
): number | null {
|
|
for (const key of keys) {
|
|
const value = metadata?.[key];
|
|
if (typeof value === "number" && Number.isFinite(value) && value >= 0)
|
|
return value;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function artifactUrl(value: string | null | undefined): string {
|
|
if (!value || /[\u0000-\u0020\\]/.test(value)) 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. */
|
|
export function artifactPreviewUrl(value: string): string {
|
|
return /^\/api\/attachments\/[a-zA-Z0-9-]+\/content$/.test(value)
|
|
? value
|
|
: "";
|
|
}
|
|
|
|
export function artifactFileSize(bytes: number | null): string {
|
|
if (bytes === null) return "";
|
|
if (bytes < 1024) return `${bytes} B`;
|
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
}
|
|
|
|
export const CSV_PREVIEW_MAX_BYTES = 1024 * 1024;
|
|
const CSV_PREVIEW_MAX_ROWS = 200;
|
|
const CSV_PREVIEW_MAX_COLUMNS = 50;
|
|
|
|
/** RFC 4180 quoting, CRLF, embedded newlines, and a UTF-8 BOM; bounded for the UI. */
|
|
export function parseArtifactCsv(text: string) {
|
|
if (new TextEncoder().encode(text).length > CSV_PREVIEW_MAX_BYTES)
|
|
throw new Error(
|
|
"CSV is too large to preview. Download the file to view it.",
|
|
);
|
|
const records: string[][] = [];
|
|
let row: string[] = [],
|
|
field = "",
|
|
quoted = false,
|
|
closedQuote = false;
|
|
const endField = () => {
|
|
row.push(field);
|
|
if (row.length > CSV_PREVIEW_MAX_COLUMNS)
|
|
throw new Error(
|
|
"CSV has too many columns to preview. Download the file to view it.",
|
|
);
|
|
field = "";
|
|
closedQuote = false;
|
|
};
|
|
const input = text.replace(/^\uFEFF/, "");
|
|
for (let i = 0; i < input.length; i++) {
|
|
const char = input[i];
|
|
if (quoted) {
|
|
if (char === '"' && input[i + 1] === '"') {
|
|
field += '"';
|
|
i++;
|
|
} else if (char === '"') {
|
|
quoted = false;
|
|
closedQuote = true;
|
|
} else field += char;
|
|
} else if (char === ",") {
|
|
endField();
|
|
} else if (char === "\n" || char === "\r") {
|
|
endField();
|
|
records.push(row);
|
|
row = [];
|
|
if (char === "\r" && input[i + 1] === "\n") i++;
|
|
if (records.length > CSV_PREVIEW_MAX_ROWS + 1) break;
|
|
} else if (char === '"' && !field && !closedQuote) {
|
|
quoted = true;
|
|
} else {
|
|
if (closedQuote || char === '"')
|
|
throw new Error(
|
|
"CSV could not be previewed. Download the file to view it.",
|
|
);
|
|
field += char;
|
|
}
|
|
}
|
|
if (quoted)
|
|
throw new Error(
|
|
"CSV could not be previewed. Download the file to view it.",
|
|
);
|
|
if (field || row.length || closedQuote) {
|
|
endField();
|
|
records.push(row);
|
|
}
|
|
return {
|
|
columns: records[0] ?? [],
|
|
rows: records.slice(1, CSV_PREVIEW_MAX_ROWS + 1),
|
|
truncated: records.length > CSV_PREVIEW_MAX_ROWS + 1,
|
|
};
|
|
}
|
|
|
|
/** Only fetch authenticated attachment bytes, never a producer-supplied remote URL. */
|
|
export async function loadArtifactCsv(
|
|
contentPath: string,
|
|
signal?: AbortSignal,
|
|
) {
|
|
if (!/^\/api\/attachments\/[a-zA-Z0-9-]+\/content$/.test(contentPath))
|
|
throw new Error(
|
|
"CSV preview is unavailable. Download the file to view it.",
|
|
);
|
|
const response = await fetch(contentPath, {
|
|
credentials: "same-origin",
|
|
redirect: "error",
|
|
signal,
|
|
});
|
|
if (!response.ok)
|
|
throw new Error("CSV could not be loaded. Try again or download the file.");
|
|
if (Number(response.headers.get("content-length")) > CSV_PREVIEW_MAX_BYTES) {
|
|
await response.body?.cancel();
|
|
throw new Error(
|
|
"CSV is too large to preview. Download the file to view it.",
|
|
);
|
|
}
|
|
const reader = response.body?.getReader();
|
|
if (!reader)
|
|
throw new Error("CSV could not be loaded. Try again or download the file.");
|
|
const decoder = new TextDecoder();
|
|
let text = "",
|
|
size = 0;
|
|
try {
|
|
while (true) {
|
|
const { value, done } = await reader.read();
|
|
if (done) break;
|
|
size += value.byteLength;
|
|
if (size > CSV_PREVIEW_MAX_BYTES) {
|
|
await reader.cancel();
|
|
throw new Error(
|
|
"CSV is too large to preview. Download the file to view it.",
|
|
);
|
|
}
|
|
text += decoder.decode(value, { stream: true });
|
|
}
|
|
text += decoder.decode();
|
|
} finally {
|
|
reader.releaseLock();
|
|
}
|
|
return parseArtifactCsv(text);
|
|
}
|