Skip to content
Merged
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
4 changes: 2 additions & 2 deletions docs/content/4.plugins/1.built-in/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,11 @@ Framework renderers (Vue, React, Svelte, Angular) never forward `innerHTML`, `da

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.
- `as` and `is` (and their bindings) that are not strings, since they name the element or component to render: Vue mounts an array as a component, and React throws on one. `tag` is often a data prop, so only objects are dropped there.
- Any object or array with one of those keys at any depth, such as `:icon='{"extends": {"template": "..."}}'` or `:icon='{"__v_isVNode": true, "type": "script"}'`.
- An `__v_isVNode` attribute on the element itself, bound or not. Vue would otherwise render the element's attributes as a ready-made element.

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.
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 array or object to `as` or `is`, or an object to `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.
Expand Down
13 changes: 13 additions & 0 deletions packages/comark-react/test/bound-component-props.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { parseMarkdown } from 'comark'
import { MarkdownDocument } from '../src/components/MarkdownDocument'

describe('non-string as in React', () => {
Expand All @@ -11,4 +12,16 @@ describe('non-string as in React', () => {
expect(html).not.toContain('<i>probe</i>')
expect(html).toContain('hi')
})

it('does not hand a non-string as to a component, which React cannot render as an element type', async () => {
const Poly = ({ as: As = 'div' }: { as?: any }) => React.createElement(As, null, 'poly')
for (const markdown of [
`::poly{:as='["section"]'}\n::`,
`---\nlist: [section]\n---\n::poly{:as="frontmatter.list"}\n::`,
]) {
const value = await parseMarkdown(markdown)
const html = renderToString(React.createElement(MarkdownDocument, { value, components: { poly: Poly } }))
expect(html).toContain('<div>poly</div>')
}
})
})
18 changes: 18 additions & 0 deletions packages/comark-vue/test/bound-component-props.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,24 @@ describe('bound props cannot smuggle a component into a polymorphic slot', () =>
}
})

it('does not hand a non-string `as` or `is` to a component, without the security plugin', async () => {
// Vue mounts an array as a component, since `isObject([])` is true.
for (const markdown of [
`::poly{:as='["section"]'}\n::`,
`::poly{:is='5'}\n::`,
`::poly{:as='true'}\n::`,
`---\nlist: [section]\n---\n::poly{:as="frontmatter.list"}\n::`,
]) {
const html = await renderMarkdown(markdown)
expect(html).toContain('<div>poly</div>')
}
})

it('keeps a non-object `tag`', async () => {
const html = await renderMarkdown(`::poly{:tag='"section"'}\n::`)
expect(html).toContain('<section>poly</section>')
})

it('keeps string tags for `as`', async () => {
const html = await renderMarkdown('::poly{:as=\'"section"\'}\n::')
expect(html).toContain('<section>poly</section>')
Expand Down
21 changes: 11 additions & 10 deletions packages/comark/src/internal/sanitize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -392,13 +392,6 @@ export function isTagSelector(key: string): boolean {
return tagSelectors.includes(normalizePropName(key))
}

/**
* Props that must not be an object. `as` and `is` pick a component in the renderers. `tag` is only checked
* for type: no renderer resolves it as a component name, so the tag filter doesn't apply to it.
* Arrays, numbers and booleans stay: `h()` renders nothing for them.
*/
const componentSelectors = ['as', 'is', 'tag']

/**
* Keys that make Vue treat a plain object as a component, a VNode (`__v_isVNode`), or a built-in
* (Teleport, Suspense, KeepAlive). JSON can't carry functions, so a JSON object with these is never legit.
Expand Down Expand Up @@ -434,8 +427,8 @@ export function isVNodeMarkerKey(key: string): boolean {
}

/**
* Whether a decoded prop value is unsafe to hand a renderer: `as` / `is` / `tag`
* must not be objects, and no object at any depth may carry component options or
* Whether a decoded prop value is unsafe to hand a renderer: `as` / `is` must be
* strings, `tag` must not be an object, and no object at any depth may carry component options or
* an HTML sink key. Components pass object props on to `h(tag, prop)` or spread
* them onto elements, so a nested `innerHTML` reaches the DOM like a top-level one.
* Applied to markdown-authored values only.
Expand All @@ -444,8 +437,16 @@ export function isUnsafeRendererProp(attribute: string, value: unknown): boolean
return isComponentSelectorViolation(attribute, value) || hasUnsafeObjectKeys(value)
}

/**
* `as` and `is` name the element or component to render, so only a string (or nothing) may reach them:
* Vue mounts any object, arrays included, as a component, and React throws on a non-string element type.
* `tag` is often a data prop (`tag: [vue, nuxt]`) and no renderer resolves it as a component name, so it
* only must not be an object or a function.
*/
function isComponentSelectorViolation(attribute: string, value: unknown): boolean {
if (!componentSelectors.includes(normalizePropName(attribute))) return false
const name = normalizePropName(attribute)
if (tagSelectors.includes(name)) return value != null && typeof value !== 'string'
if (name !== 'tag') return false
return typeof value === 'function' || (typeof value === 'object' && value !== null && !Array.isArray(value))
}

Expand Down
24 changes: 21 additions & 3 deletions packages/comark/test/plugins/security.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -699,10 +699,28 @@ describe('security plugin — component-like values', () => {
}
})

it('keeps an array, number or boolean as or is or tag', async () => {
const tree = makeTree([['span', { ':tag': '["hello","world"]', ':is': '5', ':as': 'true' }, 'x']])
it('strips an array, number or boolean as or is', async () => {
const tree = makeTree([
['span', { ':as': '["section"]', ':is': '5' }, 'x'],
['span', { ':as': 'true', is: ['section'] }, 'x'],
])
await runPlugin(tree)
expect((tree.nodes[0] as [string, any])[1]).toEqual({ ':tag': '["hello","world"]', ':is': '5', ':as': 'true' })
expect((tree.nodes[0] as [string, any])[1]).toEqual({})
expect((tree.nodes[1] as [string, any])[1]).toEqual({})
})

it('keeps a string or null as or is, and an array, number or boolean tag', async () => {
const tree = makeTree([
['span', { ':as': '"section"', ':is': 'null', ':tag': '["hello","world"]' }, 'x'],
['span', { as: 'section', ':tag': '5' }, 'x'],
])
await runPlugin(tree)
expect((tree.nodes[0] as [string, any])[1]).toEqual({
':as': '"section"',
':is': 'null',
':tag': '["hello","world"]',
})
expect((tree.nodes[1] as [string, any])[1]).toEqual({ as: 'section', ':tag': '5' })
})

it('strips a forged VNode at any depth', async () => {
Expand Down
2 changes: 1 addition & 1 deletion test/bundle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ describe('package bundle size', { timeout: 60_000 }, () => {
"@comark/react": "42.9k (83 files)",
"@comark/svelte": "50.3k (91 files)",
"@comark/vue": "62.6k (89 files)",
"comark": "438k (171 files)",
"comark": "439k (171 files)",
}
`)
})
Expand Down
Loading