Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

fix(markdown): escape code, alt, title and href under marked 17

Matt Robertsa1f5ba01a5f5
diff --git a/public/services/markdown.spec.ts b/public/services/markdown.spec.ts
index dd4398f4e..b87d2c01d 100644
--- a/public/services/markdown.spec.ts
+++ b/public/services/markdown.spec.ts
@@ -32,7 +32,8 @@ const testCases = [
},
{
input: `[Uh oh...]("onerror="alert('XSS'))`,
- expectedFull: '<p><a class="text-link" href="" rel="noopener nofollow" target="_blank">Uh oh...</a></p>',
+ // The quotes stay inside the (harmless, relative) href instead of breaking out of it
+ expectedFull: `<p><a class="text-link" href="&quot;onerror=&quot;alert('XSS')" rel="noopener nofollow" target="_blank">Uh oh...</a></p>`,
expectedPlainText: "Uh oh...",
},
{
@@ -87,6 +88,13 @@ testCases.forEach((x) => {
})
})
+// Parse rendered HTML the way the browser would and list the live elements it creates.
+const liveElements = (html: string): Element[] => {
+ const container = document.createElement("div")
+ container.innerHTML = html
+ return Array.from(container.querySelectorAll("*"))
+}
+
describe("XSS prevention", () => {
const xssInputs = [
"<script>alert(1)</script>",
@@ -97,6 +105,9 @@ describe("XSS prevention", () => {
"&lt;img src=x onerror=alert(1)&gt;",
"&lt;script&gt;alert(1)&lt;/script&gt;",
"`&lt;img src=x onerror=alert(1)&gt;`",
+ // Code spans/blocks are not escaped by marked 17's lexer; the renderers must escape them
+ "`<img src=x onerror=alert(1)>`",
+ "```\n<img src=x onerror=alert(1)>\n```",
]
xssInputs.forEach((input) => {
@@ -118,3 +129,84 @@ describe("XSS prevention", () => {
})
})
})
+
+describe("code is rendered as text", () => {
+ const inputs = ["`<b>`", "`&lt;b&gt;`", "`<img src=x onerror=alert(1)>`", "`&lt;img src=x onerror=alert(1)&gt;`", "```\n<b>bold</b>\n```"]
+
+ inputs.forEach((input) => {
+ test(`full mode creates no markup from code: ${input}`, () => {
+ const tags = liveElements(markdown.full(input)).map((e) => e.tagName.toLowerCase())
+ expect(tags.filter((t) => t !== "p" && t !== "code" && t !== "pre")).toEqual([])
+ })
+
+ test(`plainText mode creates no markup from code: ${input}`, () => {
+ expect(liveElements(markdown.plainText(input))).toEqual([])
+ })
+ })
+})
+
+describe("plainText returns HTML-safe text", () => {
+ test("does not decode entities back into markup", () => {
+ expect(liveElements(markdown.plainText("Hello <b>Beautiful</b> World"))).toEqual([])
+ expect(liveElements(markdown.plainText("&lt;b&gt;x&lt;/b&gt;"))).toEqual([])
+ })
+
+ test("displays special characters as typed", () => {
+ const container = document.createElement("p")
+ container.innerHTML = markdown.plainText("Jane's & Jim's > [Matt](https://example.com) <b>hi</b>")
+ expect(container.textContent).toEqual("Jane's & Jim's > Matt <b>hi</b>")
+ })
+})
+
+describe("attribute values are escaped", () => {
+ test("fider-image alt text cannot inject attributes", () => {
+ const [p, img] = liveElements(markdown.full('![x" class="evil" data-x="1](fider-image:attachments/abc.png)'))
+ expect(p.tagName).toEqual("P")
+ expect(img.tagName).toEqual("IMG")
+ expect(img.getAttribute("class")).toEqual("fider-inline-image")
+ expect(img.getAttribute("alt")).toEqual('x" class="evil" data-x="1')
+ expect(img.hasAttribute("data-x")).toBe(false)
+ })
+
+ test("link title is quoted", () => {
+ const [, a] = liveElements(markdown.full('[a](http://x.com "hello world")'))
+ expect(a.getAttribute("title")).toEqual("hello world")
+ expect(a.hasAttribute("world")).toBe(false)
+ })
+
+ test("link title quotes cannot inject attributes", () => {
+ const [, a] = liveElements(markdown.full(`[a](http://x.com 'say "hi" style="color:red"')`))
+ expect(a.getAttribute("title")).toEqual('say "hi" style="color:red"')
+ expect(a.hasAttribute("style")).toBe(false)
+ })
+
+ test("link href quotes cannot inject attributes", () => {
+ const [, a] = liveElements(markdown.full('[a](http://x.com/"style="color:red)'))
+ expect(a.tagName).toEqual("A")
+ expect(a.hasAttribute("style")).toBe(false)
+ })
+})
+
+describe("fider-image references", () => {
+ const unsafe = [
+ "![](fider-image:../../api/v1/admin/x)",
+ "![caption](fider-image:../../api/v1/admin/x?y)",
+ "![](fider-image:attachments/../../x.png)",
+ "![](fider-image:attachments/a%2F..%2Fb.png)",
+ ]
+
+ unsafe.forEach((input) => {
+ test(`is not rendered as an inline image: ${input}`, () => {
+ const html = markdown.full(input)
+ expect(html).not.toContain("/static/images/")
+ expect(html).not.toContain("data-bkey")
+ })
+ })
+})
+
+describe("mentions", () => {
+ test("renders non-empty @[name] as a mention and leaves @[] as text", () => {
+ const spans = liveElements(markdown.full("@[] and @[Jane Doe]")).filter((e) => e.classList.contains("mention"))
+ expect(spans.map((e) => e.textContent)).toEqual(["@Jane Doe"])
+ })
+})
diff --git a/public/services/markdown.ts b/public/services/markdown.ts
index 600807a3d..80a37dae6 100644
--- a/public/services/markdown.ts
+++ b/public/services/markdown.ts
@@ -1,6 +1,7 @@
import { Marked, RendererObject } from "marked"
import DOMPurify from "dompurify"
import { fiderAllowedSchemes } from "@fider/hooks"
+import { fiderImageBkey, MENTION_GLOBAL } from "./markdownSyntax"
if (DOMPurify.isSupported) {
DOMPurify.setConfig({
@@ -26,8 +27,12 @@ if (DOMPurify.isSupported) {
})
}
-// marked 5+ escapes text (including ' -> &#39;). We keep apostrophes literal to match the
-// historical output, while preserving existing entities and escaping & < > ".
+// marked 5+ no longer escapes token text in the lexer; escaping is the renderer's job, so every
+// override that writes token text/attributes into HTML must escape it itself.
+
+// Text and attribute values. marked 5+ escapes text (including ' -> &#39;); we keep apostrophes
+// literal to match the historical output, while preserving existing entities (input has already
+// been through encodeHTML, so "<" arrives as "&lt;") and escaping & < > ".
const escapeText = (s: string): string =>
s
.replace(/&(?![#\w]+;)/g, "&amp;")
@@ -35,8 +40,12 @@ const escapeText = (s: string): string =>
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
+// Code (spans and blocks): escape everything, exactly like marked's default code renderers,
+// so plainText and full show code the same way.
+const escapeCode = (s: string): string => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;")
+
// Expand Fider's proprietary mention syntax @[name] into a styled span.
-const renderMentions = (html: string): string => html.replace(/@\[(.*?)\]/g, (_match, name) => `<span class="mention">@${name}</span>`)
+const renderMentions = (html: string): string => html.replace(MENTION_GLOBAL, (_match, name) => `<span class="mention">@${name}</span>`)
// marked 5+ replaced the positional Renderer API with token objects and requires renderer
// overrides to be registered via .use(). Typing as RendererObject binds `this` to the
@@ -44,17 +53,18 @@ const renderMentions = (html: string): string => html.replace(/@\[(.*?)\]/g, (_m
// keep marked's defaults.
const fullRenderer: RendererObject = {
image({ href, text }) {
- // Fider's proprietary inline-image syntax: ![](fider-image:<bkey>)
- if (href && href.startsWith("fider-image:")) {
- const bkey = href.substring("fider-image:".length)
- return `<img src="/static/images/${bkey}" alt="${text || ""}" class="fider-inline-image" data-bkey="${bkey}" />`
+ // Fider's proprietary inline-image syntax: ![](fider-image:<bkey>). The bkey is validated
+ // (safe characters, no "..") so it can go into the attributes as-is.
+ const bkey = fiderImageBkey(href)
+ if (bkey) {
+ return `<img src="/static/images/${bkey}" alt="${escapeText(text || "")}" class="fider-inline-image" data-bkey="${bkey}" />`
}
return false // fall back to marked's default image renderer
},
link({ href, title, tokens }) {
const text = this.parser.parseInline(tokens)
- const titleAttr = title ? ` title=${title}` : ""
- return `<a class="text-link" href="${href}"${titleAttr} rel="noopener nofollow" target="_blank">${text}</a>`
+ const titleAttr = title ? ` title="${escapeText(title)}"` : ""
+ return `<a class="text-link" href="${escapeText(href)}"${titleAttr} rel="noopener nofollow" target="_blank">${text}</a>`
},
text(token) {
const rendered = "tokens" in token && token.tokens ? this.parser.parseInline(token.tokens) : escapeText(token.text)
@@ -88,13 +98,13 @@ const plainTextRenderer: RendererObject = {
return ` ${this.parser.parseInline(tokens)} `
},
code({ text }) {
- return text
+ return escapeCode(text)
},
codespan({ text }) {
- return text
+ return escapeCode(text)
},
html({ text }) {
- return text
+ return escapeText(text)
},
blockquote({ tokens }) {
return this.parser.parse(tokens)
diff --git a/public/services/markdownSyntax.ts b/public/services/markdownSyntax.ts
new file mode 100644
index 000000000..89dee40be
--- /dev/null
+++ b/public/services/markdownSyntax.ts
@@ -0,0 +1,26 @@
+// Fider's proprietary markdown syntax. Shared by the display renderer (services/markdown.ts)
+// and the comment editor (CustomMention / CustomImage) so both read stored content the same way.
+
+// Mentions: @[Display Name]. The name is non-empty, single-line and ends at the first "]"
+// (so "@[]" is plain text and never swallows a later "]").
+const MENTION_SOURCE = "@\\[([^\\]\\n]+)\\]"
+export const MENTION_START = "@["
+// Anchored: matches a mention at the start of the input (editor tokenizer).
+export const MENTION_AT_START = new RegExp(`^${MENTION_SOURCE}`)
+// Global: finds every mention in a string (display renderer). String.replace resets lastIndex.
+export const MENTION_GLOBAL = new RegExp(MENTION_SOURCE, "g")
+
+// Inline images: ![](fider-image:<bkey>). Only bkeys in the shape the server/editor generate
+// (e.g. attachments/<random>-<name>.png) are accepted, and never with ".." path traversal,
+// because the bkey is appended to /static/images/.
+const FIDER_IMAGE_PREFIX = "fider-image:"
+const BKEY_PATTERN = /^[a-zA-Z0-9_/.-]+$/
+
+export const fiderImageBkey = (href: string | null | undefined): string | undefined => {
+ if (!href || !href.startsWith(FIDER_IMAGE_PREFIX)) return undefined
+ const bkey = href.substring(FIDER_IMAGE_PREFIX.length)
+ if (!BKEY_PATTERN.test(bkey) || bkey.includes("..")) return undefined
+ return bkey
+}
+
+export const fiderImageMarkdown = (bkey: string): string => `![](${FIDER_IMAGE_PREFIX}${bkey})`