Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// @vitest-environment happy-dom

import { describe, expect, it } from 'vitest'
import { Editor } from '@tiptap/core'
import type { Node as ProseMirrorNode } from '@tiptap/pm/model'
import { createRichMarkdownEditorCodec } from './rich-markdown-source-transport'
import { createRichMarkdownExtensions } from './rich-markdown-extensions'
import { encodeRawMarkdownHtmlForRichEditor } from './raw-markdown-html'

function createEditor(markdown: string): Editor {
const codec = createRichMarkdownEditorCodec()
return new Editor({
element: null,
extensions: createRichMarkdownExtensions({ codec }),
content: encodeRawMarkdownHtmlForRichEditor(markdown, codec),
contentType: 'markdown'
})
}

function findRawInlineNodes(editor: Editor): ProseMirrorNode[] {
const nodes: ProseMirrorNode[] = []
editor.state.doc.descendants((node) => {
if (node.type.name === 'rawMarkdownHtmlInline') {
nodes.push(node)
}
})
return nodes
}

function renderTag(node: ProseMirrorNode): string {
const spec = node.type.spec.toDOM?.(node)
return Array.isArray(spec) ? String(spec[0]) : ''
}

const TABLE_WITH_BREAKS =
'| Field | Description |\n' +
'| --- | --- |\n' +
'| verdict | Values:<br/><br/>`normal`<br>`defect` |\n'

describe('raw markdown <br> line breaks in the rich editor', () => {
it('renders <br> and <br/> inside a table cell as real line breaks, not literal text', () => {
const editor = createEditor(TABLE_WITH_BREAKS)
try {
const breakNodes = findRawInlineNodes(editor)
expect(breakNodes.length).toBeGreaterThan(0)
// Every <br>/<br/> in the cell renders as an actual <br> element so the
// values appear on their own lines rather than as raw "<br>" text.
for (const node of breakNodes) {
expect(renderTag(node)).toBe('br')
}
} finally {
editor.destroy()
}
})

it('keeps non-break inline HTML as an inert literal span', () => {
const editor = createEditor('Before <span>hi</span> after\n')
try {
const [spanNode] = findRawInlineNodes(editor)
expect(spanNode).toBeDefined()
expect(renderTag(spanNode)).toBe('span')
} finally {
editor.destroy()
}
})

it('round-trips verbatim <br> tags after the rendered DOM is parsed again', () => {
const editor = createEditor(TABLE_WITH_BREAKS)
try {
const rendered = document.createElement('div')
rendered.innerHTML = editor.getHTML()
expect(rendered.querySelectorAll('br[data-raw-markdown-html-inline]')).toHaveLength(3)
expect(rendered.textContent).not.toContain('<br')

editor.commands.setContent(rendered.innerHTML)
const output = (editor as Editor & { getMarkdown(): string }).getMarkdown()
expect(output.match(/<br\s*\/?>/g)).toEqual(['<br/>', '<br/>', '<br>'])
// The break must not silently collapse into a space on serialization.
expect(output).not.toContain('`normal` `defect`')
} finally {
editor.destroy()
}
})

it('does not accept arbitrary Markdown source from a forged break marker', () => {
const editor = createEditor('Before<br/>after\n')
try {
const rendered = document.createElement('div')
rendered.innerHTML = editor.getHTML()
rendered
.querySelector('br[data-raw-markdown-html-inline]')
?.setAttribute('data-raw-markdown-html-value', '<script>alert(1)</script>')
Comment on lines +90 to +92

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Avoid optional chaining when setting up test conditions.

If querySelector fails to find the element (e.g., due to a change in the DOM structure), the optional chain will silently abort. The test would then proceed against an unmodified element and potentially pass, resulting in a false positive for this security test.

Explicitly assert that the element exists before mutating it to ensure the test fails loudly if the setup contract breaks.

🐛 Proposed fix
-      rendered
-        .querySelector('br[data-raw-markdown-html-inline]')
-        ?.setAttribute('data-raw-markdown-html-value', '<script>alert(1)</script>')
+      const breakNode = rendered.querySelector('br[data-raw-markdown-html-inline]')
+      expect(breakNode).not.toBeNull()
+      breakNode!.setAttribute('data-raw-markdown-html-value', '<script>alert(1)</script>')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
rendered
.querySelector('br[data-raw-markdown-html-inline]')
?.setAttribute('data-raw-markdown-html-value', '<script>alert(1)</script>')
const breakNode = rendered.querySelector('br[data-raw-markdown-html-inline]')
expect(breakNode).not.toBeNull()
breakNode!.setAttribute('data-raw-markdown-html-value', '<script>alert(1)</script>')


editor.commands.setContent(rendered.innerHTML)
const output = (editor as Editor & { getMarkdown(): string }).getMarkdown()
expect(output).toContain('Before<br>after')
expect(output).not.toContain('<script>')
} finally {
editor.destroy()
}
})
})
82 changes: 82 additions & 0 deletions src/renderer/src/components/editor/raw-markdown-html-source-dom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { mergeAttributes } from '@tiptap/core'
import type { DOMOutputSpec, Node as ProseMirrorNode, TagParseRule } from '@tiptap/pm/model'
import type { RichMarkdownSourceKind } from './rich-markdown-source-transport'

// Why: preserves the exact authored <br> spelling on the rendered break node so
// renderMarkdown can round-trip it verbatim instead of a native hardBreak, which
// serializes to a space and silently drops the tag inside Markdown table cells.
const HTML_LINE_BREAK_VALUE_ATTR = 'data-raw-markdown-html-value'

type RawMarkdownSourceDomConfig = {
inline: boolean
kind: RichMarkdownSourceKind
marker: string
className?: string
}

function isHtmlLineBreak(value: string): boolean {
return /^<br\s*\/?>$/i.test(value.trim())
}

function parsedHtmlLineBreakValue(element: HTMLElement): string {
const value = element.getAttribute(HTML_LINE_BREAK_VALUE_ATTR)
// Why: DOM input can come from the clipboard, so only trusted break syntax
// may become hidden Markdown source through the internal preservation marker.
return value && isHtmlLineBreak(value) ? value : '<br>'
}

function nodeValue(node: ProseMirrorNode): string {
return typeof node.attrs.value === 'string' ? node.attrs.value : ''
}

// Why: only inline raw HTML can carry a <br>, so line-break rendering is scoped
// to that node kind; literal envelopes and block HTML stay verbatim.
function rendersLineBreaks(config: RawMarkdownSourceDomConfig): boolean {
return config.inline && config.kind === 'inline-html'
}

export function rawMarkdownSourceParseRules(config: RawMarkdownSourceDomConfig): TagParseRule[] {
const rules: TagParseRule[] = [
{
tag: `${config.inline ? 'span' : 'div'}[${config.marker}]`,
getAttrs: (element: HTMLElement) => ({ value: element.textContent ?? '' })
}
]
if (rendersLineBreaks(config)) {
// Why: a <br> renders as a real break element (see renderHTML), so it must
// round-trip back to this node rather than StarterKit's hardBreak; the marker
// attribute and priority keep it ahead of hardBreak's bare `br` rule.
rules.push({
tag: `br[${config.marker}]`,
priority: 100,
getAttrs: (element: HTMLElement) => ({ value: parsedHtmlLineBreakValue(element) })
})
}
return rules
}

export function renderRawMarkdownSourceHtml(
config: RawMarkdownSourceDomConfig,
attributes: Record<string, unknown>,
node: ProseMirrorNode
): DOMOutputSpec {
const value = nodeValue(node)
// Why: <br> is the one inline HTML tag with line-break semantics the rich
// surface can honor directly. Render it as an actual break so it displays
// correctly where blank-line breaks are impossible (e.g. Markdown table cells).
if (rendersLineBreaks(config) && isHtmlLineBreak(value)) {
return [
'br',
mergeAttributes(attributes, { [config.marker]: '', [HTML_LINE_BREAK_VALUE_ATTR]: value })
]
}
return [
config.inline ? 'span' : 'div',
mergeAttributes(attributes, {
[config.marker]: '',
contenteditable: 'false',
class: config.className
}),
config.inline ? value : ['pre', value]
]
}
24 changes: 7 additions & 17 deletions src/renderer/src/components/editor/raw-markdown-html.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { Node, mergeAttributes } from '@tiptap/core'
import { Node } from '@tiptap/core'
import {
rawMarkdownSourceParseRules,
renderRawMarkdownSourceHtml
} from './raw-markdown-html-source-dom'
import { isEditableDetailsHtmlBlock, matchDetailsHtmlBlock } from './details-markdown-html'
import { formatMarkdownDocLinkBody, parseMarkdownDocLink } from './markdown-doc-links'
import { normalizeMarkdownReferenceLinks } from './markdown-reference-link-normalization'
Expand Down Expand Up @@ -299,25 +303,11 @@ function createRawSourceNode({
renderText: ({ node }) => (typeof node.attrs.value === 'string' ? node.attrs.value : ''),

parseHTML() {
return [
{
tag: `${inline ? 'span' : 'div'}[${marker}]`,
getAttrs: (element: HTMLElement) => ({ value: element.textContent ?? '' })
}
]
return rawMarkdownSourceParseRules({ inline, kind, marker, className })
},

renderHTML({ HTMLAttributes, node }) {
const value = typeof node.attrs.value === 'string' ? node.attrs.value : ''
return [
inline ? 'span' : 'div',
mergeAttributes(HTMLAttributes, {
[marker]: '',
contenteditable: 'false',
class: className
}),
inline ? value : ['pre', value]
]
return renderRawMarkdownSourceHtml({ inline, kind, marker, className }, HTMLAttributes, node)
}
})
}
Expand Down