Skip to content
15 changes: 14 additions & 1 deletion docs/content/4.plugins/1.built-in/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,20 @@ Attributes that can be abused regardless of value are always stripped:
Prop names are normalized before these checks: case, binding prefixes (`:`, `v-bind:`), Vue's `.prop` / `^attr` prefixes (`.innerHTML`, `^onclick`), and `:` / `-` / `_` separators are ignored.

::note
Framework renderers (Vue, React, Svelte, Angular) never forward `innerHTML`, `dangerouslySetInnerHTML`, or `textContent` from document attributes, even without this plugin. Raw HTML has its own explicit path through the default `html` plugin.
Framework renderers (Vue, React, Svelte, Angular) never forward `innerHTML`, `dangerouslySetInnerHTML`, or `textContent` from document attributes, even without this plugin. A prop object or array that holds one of these keys at any depth is dropped whole, since components can pass it on to `h(tag, prop)` or spread it onto an element. Raw HTML has its own explicit path through the default `html` plugin.
::

### Component-like values

Renderers hand bound props to components, and Vue treats a plain object with a `template`, `render`, `ssrRender`, `setup`, `extends` or `mixins` key as a component definition, one with `__v_isVNode` as a ready-made element, and one with `__isTeleport`, `__isSuspense` or `__isKeepAlive` as a built-in component. Its template can then run during server rendering, or the element skips tag filtering. These values are always dropped:

- `as`, `is` and `tag` (and their bindings) that are objects. Strings, arrays, numbers and booleans stay: Vue renders nothing for the last three.
- Any object or array with one of those keys at any depth, such as `:icon='{"extends": {"template": "..."}}'` or `:icon='{"__v_isVNode": true, "type": "script"}'`.

Data props keep working, for example `:items='[{"label": "a"}]'`. The Vue renderer also only resolves `as` to a component when it is a string. Frontmatter is checked for component options only, so data such as `tag: [vue, nuxt]` stays; a binding that passes a frontmatter object to `as`, `is` or `tag` is still dropped.

::warning
Rendering untrusted markdown (chat messages, LLM output, user comments) is only safe with this plugin enabled. The renderers apply a minimum floor to bound props, but the plugin is the full policy: it also removes the values from the document tree. Keep `security()` enabled for untrusted input.
::

### Nested props
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ function prepareNode(

let customComponent: Type<any> | undefined
if ((parent as ElementNode | undefined)?.[0] !== 'pre') {
if (as) {
if (typeof as === 'string' && as) {
customComponent = resolveComponent(as, components)
}
if (!customComponent) {
Expand Down
4 changes: 2 additions & 2 deletions packages/comark-react/src/components/MarkdownDocument.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,8 @@ function renderNode(
let componentTag = tag

if ((parent as ElementNode | undefined)?.[0] !== 'pre') {
if (as) {
customComponent = resolveComponent(as as string, components, componentsManifest)
if (typeof as === 'string' && as) {
customComponent = resolveComponent(as, components, componentsManifest)
if (customComponent) componentTag = as as string
}
if (!customComponent) {
Expand Down
14 changes: 14 additions & 0 deletions packages/comark-react/test/bound-component-props.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { describe, expect, it } from 'vitest'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { MarkdownDocument } from '../src/components/MarkdownDocument'

describe('non-string as in React', () => {
it('does not resolve a component from a non-string as', () => {
const Probe = () => React.createElement('i', null, 'probe')
const value = { nodes: [['div', { as: ['Probe'] }, 'hi']], frontmatter: {}, meta: {} } as any
const html = renderToString(React.createElement(MarkdownDocument, { value, components: { Probe } }))
expect(html).not.toContain('<i>probe</i>')
expect(html).toContain('hi')
})
})
5 changes: 3 additions & 2 deletions packages/comark-vue/src/components/MarkdownDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,9 @@ function renderNode(
let customComponent

if ((parent as ElementNode | undefined)?.[0] !== 'pre') {
if (as) {
customComponent = resolveComponent(as as string, components, componentsManifest)
// Only a string tag may pick a component: never a value (object, function) from node props
if (typeof as === 'string' && as) {
customComponent = resolveComponent(as, components, componentsManifest)
}
if (!customComponent) {
customComponent = resolveComponent(tag, components, componentsManifest)
Expand Down
169 changes: 169 additions & 0 deletions packages/comark-vue/test/bound-component-props.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import { describe, expect, it } from 'vitest'
import { createSSRApp, defineComponent, h } from 'vue'
import { renderToString } from '@vue/server-renderer'
import { parseMarkdown } from 'comark'
import security from 'comark/plugins/security'
import { MarkdownDocument } from '../src/components/MarkdownDocument.ts'

const TEMPLATE_PAYLOAD = '<b>{{ 7 * 191 }}</b>'

// Polymorphic element like Reka UI's `Primitive`: renders whatever `as` / `is` / `tag` holds.
const Poly = defineComponent({
props: {
as: { type: null, default: undefined },
is: { type: null, default: undefined },
tag: { type: null, default: undefined },
},
setup(props) {
return () => h((props.as || props.is || props.tag || 'div') as any, null, 'poly')
},
})

// Renders a bound component value, like `<component :is>` on an app-provided prop.
const Icon = defineComponent({
props: { icon: { type: null, default: undefined } },
setup(props) {
return () => h((props.icon || 'span') as any, null, 'icon')
},
})

const Items = defineComponent({
props: { items: { type: Array, default: () => [] } },
setup(props) {
return () =>
h(
'ul',
null,
(props.items as { label: string }[]).map((item) => h('li', null, item.label))
)
},
})

async function renderMarkdown(markdown: string) {
const tree = await parseMarkdown(markdown)
const app = createSSRApp({
setup: () => () => h(MarkdownDocument, { value: tree, components: { poly: Poly, icon: Icon, items: Items } }),
})
return renderToString(app as any)
}

describe('bound props cannot smuggle a component into a polymorphic slot', () => {
it('does not compile a `template` object passed as `as`', async () => {
const html = await renderMarkdown(`::poly{:as='{"template":"${TEMPLATE_PAYLOAD}"}'}\n::`)
expect(html).not.toContain('1337')
})

it('does not compile a `template` object passed as `is`', async () => {
const html = await renderMarkdown(`::poly{:is='{"template":"${TEMPLATE_PAYLOAD}"}'}\n::`)
expect(html).not.toContain('1337')
})

it('does not compile a `template` object passed as `tag`', async () => {
const html = await renderMarkdown(`::poly{:tag='{"template":"${TEMPLATE_PAYLOAD}"}'}\n::`)
expect(html).not.toContain('1337')
})

it('does not compile a nested `extends` component object', async () => {
const html = await renderMarkdown(`::icon{:icon='{"extends":{"template":"${TEMPLATE_PAYLOAD}"}}'}\n::`)
expect(html).not.toContain('1337')
})

it('does not compile `render`, `setup` or `mixins` component keys', async () => {
for (const key of ['render', 'setup', 'mixins']) {
const html = await renderMarkdown(`::icon{:icon='{"${key}":"${TEMPLATE_PAYLOAD}"}'}\n::`)
expect(html).not.toContain('1337')
}
})

it('does not compile a `template` object passed as an unbound `as`, `is` or `tag`', async () => {
for (const key of ['as', 'is', 'tag']) {
const html = await renderMarkdown(`::poly{${key}='{"template":"${TEMPLATE_PAYLOAD}"}'}\n::`)
expect(html).not.toContain('1337')
expect(html).toContain('<div>poly</div>')
}
})

it('does not render a forged VNode or built-in component object', async () => {
const payloads = [
'{"__v_isVNode":true,"type":"script","props":{"src":"https://example.invalid/probe.js"},"shapeFlag":1}',
'{"__v_isVNode":true,"type":"div","props":{"innerHTML":"<img src=x onerror=alert(1)>"},"shapeFlag":1}',
'{"nested":[{"__v_isVNode":true,"type":"script","shapeFlag":1}]}',
'{"__isTeleport":true}',
'{"__isSuspense":true}',
'{"__isKeepAlive":true}',
]
for (const payload of payloads) {
for (const plugins of [[], [security({ blockedTags: ['script'] })]]) {
const tree = await parseMarkdown(`::icon{:icon='${payload}'}\n::`, { plugins })
const app = createSSRApp({
setup: () => () => h(MarkdownDocument, { value: tree, components: { icon: Icon } }),
})
const html = await renderToString(app as any)
expect(html).not.toMatch(/<script|<img|probe\.js/)
expect(html).toMatch(/^<div class="comark-content">(<span>icon<\/span>|<!---->)<\/div>$/)
}
}
})

it('keeps string tags for `as`', async () => {
const html = await renderMarkdown('::poly{:as=\'"section"\'}\n::')
expect(html).toContain('<section>poly</section>')
})
})

describe('object props handed on to elements', () => {
// `h(tag, prop)` reads a plain object as element props; spreading a prop does the same.
const Label = defineComponent({
props: { label: { type: null, default: undefined } },
setup(props) {
return () => h('span', props.label ?? 'none')
},
})
const Spread = defineComponent({
props: { items: { type: null, default: undefined } },
setup(props) {
return () =>
h(
'ul',
null,
((props.items as object[]) || []).map((item) => h('li', { ...item }, 'item'))
)
},
})

async function render(markdown: string) {
const tree = await parseMarkdown(markdown)
const app = createSSRApp({
setup: () => () => h(MarkdownDocument, { value: tree, components: { label: Label, spread: Spread } }),
})
return renderToString(app as any)
}

it('drops an object prop with an HTML sink at any depth', async () => {
const sink = '"<img src=x onerror=alert(1)>"'
const cases = [
`::label{:label='{"innerHTML":${sink}}'}\n::`,
`::label{:label='{".innerHTML":${sink}}'}\n::`,
`::label{:label='{"textContent":"overwrite"}'}\n::`,
`::label{label='{"innerHTML":${sink}}'}\n::`,
`::spread{:items='[{"class":"a"},{"innerHTML":${sink}}]'}\n::`,
`---\nl:\n innerHTML: ${sink}\n---\n::label{:label="frontmatter.l"}\n::`,
]
for (const markdown of cases) {
const html = await render(markdown)
expect(html).not.toMatch(/<img|overwrite/)
}
})

it('keeps object props without HTML sinks', async () => {
const html = await render(`::spread{:items='[{"class":"a"},{"title":"b"}]'}\n::`)
expect(html).toContain('<ul><li class="a">item</li><li title="b">item</li></ul>')
})
})

describe('data-valued bound props', () => {
it('passes object and array data props through unchanged', async () => {
const html = await renderMarkdown('::items{:items=\'[{"label":"a"}]\'}\n::')
expect(html).toContain('<li>a</li>')
})
})
Loading
Loading