Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix: sanitize markdown rendering in comments and shared renderers (#679)
Jiayuan Zhang6c5879215db0
diff --git a/packages/ui/markdown/Markdown.tsx b/packages/ui/markdown/Markdown.tsxindex fedcc67c86..c642ffde81 100644--- a/packages/ui/markdown/Markdown.tsx+++ b/packages/ui/markdown/Markdown.tsx@@ -1,6 +1,7 @@import * as React from 'react'import ReactMarkdown, { type Components, defaultUrlTransform } from 'react-markdown'import rehypeRaw from 'rehype-raw'+import rehypeSanitize, { defaultSchema } from 'rehype-sanitize'import remarkGfm from 'remark-gfm'import { cn } from '@multica/ui/lib/utils'import { CodeBlock, InlineCode } from './CodeBlock'@@ -49,6 +50,28 @@ export interface MarkdownProps {renderMention?: (props: { type: string; id: string }) => React.ReactNode}+// Sanitization schema — extends GitHub defaults to allow code highlighting classes+// and the mention:// protocol used for @mentions.+const sanitizeSchema = {+ ...defaultSchema,+ protocols: {+ ...defaultSchema.protocols,+ href: [...(defaultSchema.protocols?.href ?? []), 'mention'],+ },+ attributes: {+ ...defaultSchema.attributes,+ code: [+ ...(defaultSchema.attributes?.code ?? []),+ ['className', /^language-/],+ ['className', /^hljs/],+ ],+ img: [+ ...(defaultSchema.attributes?.img ?? []),+ 'alt',+ ],+ },+}+/*** Custom URL transform that allows mention:// protocol (used for @mentions)* while keeping the default security for all other URLs.@@ -327,7 +350,7 @@ export function Markdown({<div className={cn('markdown-content break-words', className)}><ReactMarkdownremarkPlugins={[[remarkGfm, { singleTilde: false }]]}- rehypePlugins={[rehypeRaw]}+ rehypePlugins={[rehypeRaw, [rehypeSanitize, sanitizeSchema]]}urlTransform={urlTransform}components={components}>diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 391051007b..dd5cb229e3 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -53,6 +53,7 @@"@types/linkify-it": "^5.0.0","@types/react": "catalog:","@types/react-dom": "catalog:",+ "rehype-sanitize": "^6.0.0","typescript": "catalog:"}}diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsxindex 94965a942b..2c65200b6f 100644--- a/packages/views/editor/readonly-content.tsx+++ b/packages/views/editor/readonly-content.tsx@@ -23,6 +23,7 @@ import ReactMarkdown, {} from "react-markdown";import remarkGfm from "remark-gfm";import rehypeRaw from "rehype-raw";+import rehypeSanitize, { defaultSchema } from "rehype-sanitize";import { createLowlight, common } from "lowlight";// @ts-expect-error -- hast-util-to-html has no bundled type declarationsimport { toHtml } from "hast-util-to-html";@@ -41,6 +42,36 @@ import "./content-editor.css";const lowlight = createLowlight(common);+// ---------------------------------------------------------------------------+// Sanitization schema — extends GitHub defaults to allow file-card data attrs+// ---------------------------------------------------------------------------++const sanitizeSchema = {+ ...defaultSchema,+ protocols: {+ ...defaultSchema.protocols,+ href: [...(defaultSchema.protocols?.href ?? []), "mention"],+ },+ attributes: {+ ...defaultSchema.attributes,+ div: [+ ...(defaultSchema.attributes?.div ?? []),+ "dataType",+ "dataHref",+ "dataFilename",+ ],+ code: [+ ...(defaultSchema.attributes?.code ?? []),+ ["className", /^language-/],+ ["className", /^hljs/],+ ],+ img: [+ ...(defaultSchema.attributes?.img ?? []),+ "alt",+ ],+ },+};+// ---------------------------------------------------------------------------// URL transform — allow mention:// protocol through react-markdown's sanitizer// ---------------------------------------------------------------------------@@ -159,7 +190,9 @@ const components: Partial<Components> = {div: ({ node, children, ...props }) => {const dataType = node?.properties?.dataType as string | undefined;if (dataType === "fileCard") {- const href = (node?.properties?.dataHref as string) || "";+ const rawHref = (node?.properties?.dataHref as string) || "";+ // Only allow http(s) URLs to prevent javascript: and other dangerous schemes.+ const href = /^https?:\/\//i.test(rawHref) ? rawHref : "";const filename = (node?.properties?.dataFilename as string) || "";return (<div className="my-1 flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2.5 py-1 transition-colors hover:bg-muted">@@ -243,7 +276,7 @@ export function ReadonlyContent({ content, className }: ReadonlyContentProps) {<div className={cn("rich-text-editor readonly text-sm", className)}><ReactMarkdownremarkPlugins={[[remarkGfm, { singleTilde: false }]]}- rehypePlugins={[rehypeRaw]}+ rehypePlugins={[rehypeRaw, [rehypeSanitize, sanitizeSchema]]}urlTransform={urlTransform}components={components}>diff --git a/packages/views/package.json b/packages/views/package.jsonindex f962c5573f..f7ffc9bd1a 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -35,40 +35,40 @@"./settings": "./settings/index.ts"},"dependencies": {- "@multica/core": "workspace:*",- "@multica/ui": "workspace:*",- "cmdk": "^1.1.1","@base-ui/react": "^1.3.0","@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2","@floating-ui/dom": "^1.7.6",+ "@multica/core": "workspace:*",+ "@multica/ui": "workspace:*","@tiptap/core": "^3.22.1","@tiptap/extension-code-block-lowlight": "^3.22.1",+ "@tiptap/extension-document": "^3.22.1","@tiptap/extension-image": "^3.22.1","@tiptap/extension-link": "^3.22.1","@tiptap/extension-mention": "^3.22.1",+ "@tiptap/extension-paragraph": "^3.22.1","@tiptap/extension-placeholder": "^3.22.1","@tiptap/extension-table": "^3.22.1","@tiptap/extension-table-cell": "^3.22.1","@tiptap/extension-table-header": "^3.22.1","@tiptap/extension-table-row": "^3.22.1",+ "@tiptap/extension-text": "^3.22.1","@tiptap/extension-typography": "^3.22.1","@tiptap/markdown": "^3.22.1","@tiptap/pm": "^3.22.1","@tiptap/react": "^3.22.1","@tiptap/starter-kit": "^3.22.1",- "@tiptap/extension-document": "^3.22.1",- "@tiptap/extension-paragraph": "^3.22.1",- "@tiptap/extension-text": "^3.22.1","@tiptap/suggestion": "^3.22.1",+ "cmdk": "^1.1.1","hast-util-to-html": "^4.0.1","lowlight": "^3.3.0","react-markdown": "^10.1.0",- "rehype-raw": "^7.0.0",- "remark-gfm": "^4.0.1","react-resizable-panels": "^4.7.5","recharts": "3.8.0",+ "rehype-raw": "^7.0.0",+ "remark-gfm": "^4.0.1","sonner": "^2.0.7"},"peerDependencies": {@@ -87,6 +87,7 @@"@types/react-dom": "catalog:","@vitejs/plugin-react": "catalog:","jsdom": "catalog:",+ "rehype-sanitize": "^6.0.0","typescript": "catalog:","vitest": "catalog:"}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 287dcbddf9..5c07891940 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -562,6 +562,9 @@ importers:'@types/react-dom':specifier: ^19.2.0version: 19.2.3(@types/[email protected])+ rehype-sanitize:+ specifier: ^6.0.0+ version: 6.0.0typescript:specifier: 'catalog:'version: 5.9.3@@ -713,6 +716,9 @@ importers:jsdom:specifier: 'catalog:'version: 29.0.1(@noble/[email protected])+ rehype-sanitize:+ specifier: ^6.0.0+ version: 6.0.0typescript:specifier: 'catalog:'version: 5.9.3@@ -4269,6 +4275,9 @@ packages:resolution: {integrity: sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==}+ resolution: {integrity: sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg==}+resolution: {integrity: sha512-48+B/rJWAp0jamNbAAf9M7Uf//UVqAoMmgXhBdxTDJLGKY+LRnZ99qcG+Qjl5HfMpYNzS5v4EAwVEF34LeAj7w==}@@ -5890,6 +5899,9 @@ packages:resolution: {integrity: sha512-lqA4rGUf1JmacCNWWZx0Wv1dHqMwxzsDWYMTowuplHF3xH0N/MmrZ/G3BDZnzAkRmxDadujCjaKM2hqYdCBOGw==}+ resolution: {integrity: sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg==}+resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}@@ -10679,6 +10691,12 @@ snapshots:web-namespaces: 2.0.1zwitch: 2.0.4+ dependencies:+ '@types/hast': 3.0.4+ '@ungap/structured-clone': 1.3.0+ unist-util-position: 5.0.0+dependencies:'@types/estree': 1.0.8@@ -12689,6 +12707,11 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/hast': 3.0.4+ hast-util-sanitize: 5.0.2+dependencies:'@types/mdast': 4.0.4diff --git a/server/go.mod b/server/go.modindex 3bcaec562e..c46a511cf3 100644--- a/server/go.mod+++ b/server/go.mod@@ -34,12 +34,16 @@ require (github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.18 // indirectgithub.com/aws/aws-sdk-go-v2/service/sts v1.41.10 // indirectgithub.com/aws/smithy-go v1.24.2 // indirect+ github.com/aymerick/douceur v0.2.0 // indirectgithub.com/google/uuid v1.6.0 // indirect+ github.com/gorilla/css v1.0.1 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirectgithub.com/jackc/pgpassfile v1.0.0 // indirectgithub.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirectgithub.com/jackc/puddle/v2 v2.2.2 // indirect+ github.com/microcosm-cc/bluemonday v1.0.27 // indirectgithub.com/spf13/pflag v1.0.9 // indirect+ golang.org/x/net v0.26.0 // indirectgolang.org/x/sync v0.20.0 // indirectgolang.org/x/text v0.35.0 // indirect)diff --git a/server/go.sum b/server/go.sumindex 66dea6546b..815fdc2541 100644--- a/server/go.sum+++ b/server/go.sum@@ -38,6 +38,8 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.41.10 h1:p8ogvvLugcR/zLBXTXrTkj0RYBUgithub.com/aws/aws-sdk-go-v2/service/sts v1.41.10/go.mod h1:60dv0eZJfeVXfbT1tFJinbHrDfSJ2GZl4Q//OSSNAVw=github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng=github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=+github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=+github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=@@ -50,6 +52,8 @@ github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63Ygithub.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=+github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=@@ -64,6 +68,8 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHogithub.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=github.com/lmittmann/tint v1.1.3 h1:Hv4EaHWXQr+GTFnOU4VKf8UvAtZgn0VuKT+G0wFlO3I=github.com/lmittmann/tint v1.1.3/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=+github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=+github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/resend/resend-go/v2 v2.28.0 h1:ttM1/VZR4fApBv3xI1TneSKi1pbfFsVrq7fXFlHKtj4=@@ -79,6 +85,8 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=+golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=+golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex d7c3f90006..6cc328d5e5 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -12,6 +12,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/logger""github.com/multica-ai/multica/server/internal/mention"+ "github.com/multica-ai/multica/server/internal/sanitize""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -218,6 +219,9 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {// Expand bare issue identifiers (e.g. MUL-117) into mention links.req.Content = mention.ExpandIssueIdentifiers(r.Context(), h.Queries, issue.WorkspaceID, req.Content)+ // Sanitize HTML to prevent stored XSS.+ req.Content = sanitize.HTML(req.Content)+comment, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{IssueID: issue.ID,WorkspaceID: issue.WorkspaceID,@@ -481,6 +485,9 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {return}+ // Sanitize HTML to prevent stored XSS.+ req.Content = sanitize.HTML(req.Content)+comment, err := h.Queries.UpdateComment(r.Context(), db.UpdateCommentParams{ID: parseUUID(commentId),Content: req.Content,diff --git a/server/internal/sanitize/html.go b/server/internal/sanitize/html.gonew file mode 100644index 0000000000..89ca4e0947--- /dev/null+++ b/server/internal/sanitize/html.go@@ -0,0 +1,35 @@+package sanitize++import (+ "regexp"++ "github.com/microcosm-cc/bluemonday"+)++// httpURL matches only http:// and https:// URLs — blocks javascript:, data:, etc.+var httpURL = regexp.MustCompile(`^https?://`)++// policy is a shared bluemonday policy that allows safe Markdown HTML while+// stripping dangerous elements (script, iframe, object, embed, style, on*).+//+// Note: bluemonday operates on raw text, so HTML inside Markdown code blocks+// (e.g. ```<script>```) will also be stripped. This is an acceptable trade-off+// for defense-in-depth — the primary sanitization happens in the frontend via+// rehype-sanitize which understands the Markdown AST.+var policy *bluemonday.Policy++func init() {+ policy = bluemonday.UGCPolicy()+ policy.AllowElements("div", "span")+ // Allow file-card data attributes, but restrict data-href to http(s) only+ // to prevent javascript: and other dangerous URL schemes.+ policy.AllowAttrs("data-type", "data-filename").OnElements("div")+ policy.AllowAttrs("data-href").Matching(httpURL).OnElements("div")+ policy.AllowAttrs("class").OnElements("code", "div", "span", "pre")+}++// HTML sanitizes user-provided HTML/Markdown content, stripping dangerous+// tags (script, iframe, object, embed, etc.) and event-handler attributes.+func HTML(input string) string {+ return policy.Sanitize(input)+}diff --git a/server/internal/sanitize/html_test.go b/server/internal/sanitize/html_test.gonew file mode 100644index 0000000000..9745a97e4b--- /dev/null+++ b/server/internal/sanitize/html_test.go@@ -0,0 +1,93 @@+package sanitize++import (+ "testing"+)++func TestHTML(t *testing.T) {+ tests := []struct {+ name string+ input string+ want string+ }{+ {+ name: "plain text",+ input: "hello world",+ want: "hello world",+ },+ {+ name: "safe markdown",+ input: "**bold** and *italic*",+ want: "**bold** and *italic*",+ },+ {+ name: "script tag stripped",+ input: `<script>alert(1)</script>`,+ want: "",+ },+ {+ name: "iframe stripped",+ input: `<iframe srcdoc="<script>parent.__xss=1</script>"></iframe>`,+ want: "",+ },+ {+ name: "img with onerror stripped",+ input: `<img src=x onerror="alert(1)">`,+ want: `<img src="x">`,+ },+ {+ name: "safe link preserved",+ input: `<a href="https://example.com">link</a>`,+ want: `<a href="https://example.com" rel="nofollow">link</a>`,+ },+ {+ name: "file card div preserved",+ input: `<div data-type="fileCard" data-href="https://cdn.example.com/file.pdf" data-filename="report.pdf"></div>`,+ want: `<div data-type="fileCard" data-href="https://cdn.example.com/file.pdf" data-filename="report.pdf"></div>`,+ },+ {+ name: "object tag stripped",+ input: `<object data="evil.swf"></object>`,+ want: "",+ },+ {+ name: "embed tag stripped",+ input: `<embed src="evil.swf">`,+ want: "",+ },+ {+ name: "style tag stripped",+ input: `<style>body{display:none}</style>`,+ want: "",+ },+ {+ name: "mention link preserved",+ input: `[@User](mention://member/abc-123)`,+ want: `[@User](mention://member/abc-123)`,+ },+ {+ name: "file card with javascript href stripped",+ input: `<div data-type="fileCard" data-href="javascript:alert(1)" data-filename="evil.pdf"></div>`,+ want: `<div data-type="fileCard" data-filename="evil.pdf"></div>`,+ },+ {+ name: "file card with data URI stripped",+ input: `<div data-type="fileCard" data-href="data:text/html,<script>alert(1)</script>" data-filename="x.html"></div>`,+ want: `<div data-type="fileCard" data-filename="x.html"></div>`,+ },+ {+ name: "file card with http href preserved",+ input: `<div data-type="fileCard" data-href="http://example.com/file.pdf" data-filename="file.pdf"></div>`,+ want: `<div data-type="fileCard" data-href="http://example.com/file.pdf" data-filename="file.pdf"></div>`,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := HTML(tt.input)+ if got != tt.want {+ t.Errorf("HTML(%q) = %q, want %q", tt.input, got, tt.want)+ }+ })+ }+}