From b6b1873163a4e2067fafde169d0d1467bf395f0e Mon Sep 17 00:00:00 2001 From: Farnabaz Date: Tue, 10 Nov 2026 13:09:58 +0100 Subject: [PATCH 1/9] fix: restrict object values in bound props --- docs/content/4.plugins/1.built-in/security.md | 13 +++ .../src/components/MarkdownDocument.ts | 5 +- .../test/bound-component-props.test.ts | 88 +++++++++++++++++++ packages/comark/src/internal/sanitize.ts | 36 ++++++++ .../src/internal/stringify/html-attributes.ts | 6 +- packages/comark/test/plugins/security.test.ts | 36 ++++++++ 6 files changed, 181 insertions(+), 3 deletions(-) create mode 100644 packages/comark-vue/test/bound-component-props.test.ts diff --git a/docs/content/4.plugins/1.built-in/security.md b/docs/content/4.plugins/1.built-in/security.md index f2df50b21..f544fb23f 100644 --- a/docs/content/4.plugins/1.built-in/security.md +++ b/docs/content/4.plugins/1.built-in/security.md @@ -107,6 +107,19 @@ Prop names are normalized before these checks: case, binding prefixes (`:`, `v-b 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. :: +### 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. Its template can then run during server rendering. These values are always dropped: + +- `as`, `is` and `tag` (and their bindings) that are not strings. +- Any object or array at any depth with a `template`, `render`, `ssrRender`, `setup`, `extends` or `mixins` key, such as `:icon='{"extends": {"template": "..."}}'`. + +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 the same way. + +::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 Object and array prop values (`:links='[{"to": "/docs", "label": "Docs"}]'`, YAML props) are validated recursively: every nested key goes through the same checks as a top-level prop, so nested `on*` handlers, `*Html` keys, and unsafe URLs are removed at any depth while the rest of the value is kept. Array items are checked against the prop name that holds them. diff --git a/packages/comark-vue/src/components/MarkdownDocument.ts b/packages/comark-vue/src/components/MarkdownDocument.ts index ddaae93ec..cc84beb9c 100644 --- a/packages/comark-vue/src/components/MarkdownDocument.ts +++ b/packages/comark-vue/src/components/MarkdownDocument.ts @@ -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) diff --git a/packages/comark-vue/test/bound-component-props.test.ts b/packages/comark-vue/test/bound-component-props.test.ts new file mode 100644 index 000000000..74b8e716b --- /dev/null +++ b/packages/comark-vue/test/bound-component-props.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest' +import { createSSRApp, defineComponent, h } from 'vue' +import { renderToString } from '@vue/server-renderer' +import { parseMarkdown } from 'comark' +import { MarkdownDocument } from '../src/components/MarkdownDocument.ts' + +const TEMPLATE_PAYLOAD = '{{ 7 * 191 }}' + +// 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 `` 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('keeps string tags for `as`', async () => { + const html = await renderMarkdown('::poly{:as=\'"section"\'}\n::') + expect(html).toContain('
poly
') + }) +}) + +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('
  • a
  • ') + }) +}) diff --git a/packages/comark/src/internal/sanitize.ts b/packages/comark/src/internal/sanitize.ts index 2babe9e22..0279425a6 100644 --- a/packages/comark/src/internal/sanitize.ts +++ b/packages/comark/src/internal/sanitize.ts @@ -264,6 +264,39 @@ export function isTagSelector(key: string): boolean { return tagSelectors.includes(normalizePropName(key)) } +/** Props a renderer may hand to `h()` as a component, so only strings are accepted. */ +const componentSelectors = ['as', 'is', 'tag'] + +/** Keys that make a plain object a compiled Vue component. JSON can't carry functions, so a JSON object with these is never a legit component. */ +const componentOptionKeys = new Set(['template', 'render', 'ssrrender', 'setup', 'extends', 'mixins']) + +/** + * Whether a decoded prop value could make a renderer treat it as a component: + * `as` / `is` / `tag` must be strings, and no object at any depth may carry + * component options. Applied to markdown-authored values only. + */ +export function isComponentPropViolation(attribute: string, value: unknown): boolean { + if (componentSelectors.includes(normalizePropName(attribute)) && typeof value !== 'string') return true + return hasComponentOptions(value) +} + +function hasComponentOptions(value: unknown): boolean { + // Iterative with a visited set: cyclic or shared (YAML alias) values neither + // overflow the stack nor get scanned twice. + const seen = new Set() + const pending: unknown[] = [value] + while (pending.length) { + const current = pending.pop() + if (typeof current !== 'object' || current === null || seen.has(current)) continue + seen.add(current) + for (const [key, item] of Object.entries(current)) { + if (!Array.isArray(current) && componentOptionKeys.has(key.toLowerCase())) return true + pending.push(item) + } + } + return false +} + /** A filter for tag selectors: `unsafeTags` and `blockedTags`, or any tag outside `allowedTags` when set. */ export function createTagFilter(blockedTags: string[] = [], allowedTags: string[] = []): (tag: string) => boolean { const blocked = new Set([...blockedTags, ...unsafeTags].map((tag) => tag.toLowerCase())) @@ -307,6 +340,7 @@ export function validateProp(attribute: string, value: unknown, options: PropsVa } catch { // Not JSON — a dot-path binding or literal, validated as-is } + if (isComponentPropViolation(attribute, decoded)) return REJECTED_PROP if (typeof decoded === 'object' && decoded !== null) { const result = validateValue(name, decoded, options) return result === REJECTED_PROP ? REJECTED_PROP : JSON.stringify(result) @@ -317,6 +351,7 @@ export function validateProp(attribute: string, value: unknown, options: PropsVa return result === REJECTED_PROP ? REJECTED_PROP : value } + if (isComponentPropViolation(attribute, value)) return REJECTED_PROP return validateValue(name, value, options) } @@ -429,6 +464,7 @@ export function sanitizeData(data: unknown, options: SanitizeDataOptions = {}): if (key !== undefined) { if (isUnsafePropName(name)) return REJECTED_PROP if (tagSelectors.includes(name) && isUnsafeTagSelector(key, value, isFilteredTag)) return REJECTED_PROP + if (isComponentPropViolation(key, value)) return REJECTED_PROP } return typeof value === 'string' ? validateString(name, value, options) : value } diff --git a/packages/comark/src/internal/stringify/html-attributes.ts b/packages/comark/src/internal/stringify/html-attributes.ts index 36dbbfc30..3393b0a7b 100644 --- a/packages/comark/src/internal/stringify/html-attributes.ts +++ b/packages/comark/src/internal/stringify/html-attributes.ts @@ -1,5 +1,5 @@ import { escapeHtml, get } from '../../utils/index.ts' -import { isUnsafeUrlValue, isUrlPropKey } from '../sanitize.ts' +import { isComponentPropViolation, isUnsafeUrlValue, isUrlPropKey } from '../sanitize.ts' import type { NodeRenderData } from '../../types.ts' export interface ResolveAttributesOptions { @@ -85,6 +85,10 @@ export function resolveAttributes( outValue = value } + // Hard floor: a binding must never hand a renderer a value it could treat as a + // component (`as` / `is` / `tag` strings only, no component options at any depth). + if (options.parseJson && isBinding && isComponentPropViolation(outKey, outValue)) continue + // Hard floor: a binding must never resolve a URL prop to an unsafe scheme // (javascript:, data:text/html, …). Parse-time validation only sees the // literal path, so the resolved value is checked here — even when the diff --git a/packages/comark/test/plugins/security.test.ts b/packages/comark/test/plugins/security.test.ts index 189380d45..4e6513d1a 100644 --- a/packages/comark/test/plugins/security.test.ts +++ b/packages/comark/test/plugins/security.test.ts @@ -677,6 +677,42 @@ describe('security plugin — as prop', () => { }) }) +describe('security plugin — component-like values', () => { + it('strips a non-string as or is or tag', async () => { + const tree = makeTree([ + ['span', { ':as': '{"template":"x"}' }, 'x'], + ['span', { ':is': '["a"]' }, 'x'], + ['span', { tag: 42 }, 'x'], + ]) + await runPlugin(tree) + for (const node of tree.nodes) { + const el = node as [string, any] + expect(el[1]).toEqual({}) + } + }) + + it('strips a bound object carrying component options at any depth', async () => { + const tree = makeTree([ + ['span', { ':icon': '{"extends":{"template":"x"}}' }, 'x'], + ['span', { ':items': '[{"render":"x"}]' }, 'x'], + ['span', { ':config': '{"setup":1}' }, 'x'], + ['span', { ':config': '{"mixins":[]}' }, 'x'], + ]) + await runPlugin(tree) + for (const node of tree.nodes) { + const el = node as [string, any] + expect(el[1]).toEqual({}) + } + }) + + it('keeps data-valued bound props', async () => { + const tree = makeTree([['span', { ':items': '[{"label":"a"}]', ':options': '{"k":"v"}' }, 'x']]) + await runPlugin(tree) + const el = tree.nodes[0] as [string, any] + expect(el[1]).toEqual({ ':items': '[{"label":"a"}]', ':options': '{"k":"v"}' }) + }) +}) + describe('security plugin — prop sanitization', () => { it('strips event handler props', async () => { const tree = makeTree([['div', { onclick: 'evil()', class: 'safe' }]]) From 5df70affa2b56b434ace70358c428be1c3e64b3c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:59:52 +0000 Subject: [PATCH 2/9] test: update bundle size snapshot --- test/bundle.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 83183dd24..0eefda1b4 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -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": "425k (169 files)", + "comark": "426k (169 files)", } `) }) From ba9f4072014f27dcd071dc57f53cbc9a2c38b939 Mon Sep 17 00:00:00 2001 From: Farnabaz Date: Tue, 10 Nov 2026 14:04:47 +0100 Subject: [PATCH 3/9] fix: only resolve string tags to components in React and Angular --- .../src/components/markdown-node.component.ts | 2 +- .../src/components/MarkdownDocument.tsx | 4 ++-- .../test/bound-component-props.test.tsx | 14 ++++++++++++++ packages/comark/src/internal/sanitize.ts | 5 ++++- 4 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 packages/comark-react/test/bound-component-props.test.tsx diff --git a/packages/comark-angular/src/components/markdown-node.component.ts b/packages/comark-angular/src/components/markdown-node.component.ts index d40c030b8..314afd679 100644 --- a/packages/comark-angular/src/components/markdown-node.component.ts +++ b/packages/comark-angular/src/components/markdown-node.component.ts @@ -89,7 +89,7 @@ function prepareNode( let customComponent: Type | undefined if ((parent as ElementNode | undefined)?.[0] !== 'pre') { - if (as) { + if (typeof as === 'string' && as) { customComponent = resolveComponent(as, components) } if (!customComponent) { diff --git a/packages/comark-react/src/components/MarkdownDocument.tsx b/packages/comark-react/src/components/MarkdownDocument.tsx index ca38cca2e..68039aef5 100644 --- a/packages/comark-react/src/components/MarkdownDocument.tsx +++ b/packages/comark-react/src/components/MarkdownDocument.tsx @@ -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) { diff --git a/packages/comark-react/test/bound-component-props.test.tsx b/packages/comark-react/test/bound-component-props.test.tsx new file mode 100644 index 000000000..8e471f27a --- /dev/null +++ b/packages/comark-react/test/bound-component-props.test.tsx @@ -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('probe') + expect(html).toContain('hi') + }) +}) diff --git a/packages/comark/src/internal/sanitize.ts b/packages/comark/src/internal/sanitize.ts index 0279425a6..29fcfb041 100644 --- a/packages/comark/src/internal/sanitize.ts +++ b/packages/comark/src/internal/sanitize.ts @@ -264,7 +264,10 @@ export function isTagSelector(key: string): boolean { return tagSelectors.includes(normalizePropName(key)) } -/** Props a renderer may hand to `h()` as a component, so only strings are accepted. */ +/** + * Props whose value must be a string. `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. + */ const componentSelectors = ['as', 'is', 'tag'] /** Keys that make a plain object a compiled Vue component. JSON can't carry functions, so a JSON object with these is never a legit component. */ From 38bb8154372cc8115db77684d924574a1e748bd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Tue, 10 Nov 2026 13:52:46 +0000 Subject: [PATCH 4/9] fix: check prop types on unbound props too Amp-Thread-ID: https://ampcode.com/threads/T-01a1c5ae-b7dd-7541-b1b3-7f6a41881394 --- packages/comark-vue/test/bound-component-props.test.ts | 8 ++++++++ packages/comark/src/internal/stringify/html-attributes.ts | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/comark-vue/test/bound-component-props.test.ts b/packages/comark-vue/test/bound-component-props.test.ts index 74b8e716b..c57e86c3d 100644 --- a/packages/comark-vue/test/bound-component-props.test.ts +++ b/packages/comark-vue/test/bound-component-props.test.ts @@ -74,6 +74,14 @@ describe('bound props cannot smuggle a component into a polymorphic slot', () => } }) + 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('
    poly
    ') + } + }) + it('keeps string tags for `as`', async () => { const html = await renderMarkdown('::poly{:as=\'"section"\'}\n::') expect(html).toContain('
    poly
    ') diff --git a/packages/comark/src/internal/stringify/html-attributes.ts b/packages/comark/src/internal/stringify/html-attributes.ts index 3393b0a7b..23547ed2b 100644 --- a/packages/comark/src/internal/stringify/html-attributes.ts +++ b/packages/comark/src/internal/stringify/html-attributes.ts @@ -85,9 +85,10 @@ export function resolveAttributes( outValue = value } - // Hard floor: a binding must never hand a renderer a value it could treat as a + // Hard floor: a prop must never hand a renderer a value it could treat as a // component (`as` / `is` / `tag` strings only, no component options at any depth). - if (options.parseJson && isBinding && isComponentPropViolation(outKey, outValue)) continue + // Unbound props count too: the parser decodes `as='{…}'` into an object. + if (options.parseJson && isComponentPropViolation(outKey, outValue)) continue // Hard floor: a binding must never resolve a URL prop to an unsafe scheme // (javascript:, data:text/html, …). Parse-time validation only sees the From ea8129489850a896b6b2a9b0f8443d028347c16b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Tue, 10 Nov 2026 13:56:51 +0000 Subject: [PATCH 5/9] fix: keep non-string tag values in frontmatter Amp-Thread-ID: https://ampcode.com/threads/T-01a1c5ae-b7dd-7541-b1b3-7f6a41881394 --- docs/content/4.plugins/1.built-in/security.md | 2 +- packages/comark/src/internal/sanitize.ts | 4 +++- packages/comark/test/plugins/security.test.ts | 8 ++++++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/content/4.plugins/1.built-in/security.md b/docs/content/4.plugins/1.built-in/security.md index f544fb23f..3e86cd416 100644 --- a/docs/content/4.plugins/1.built-in/security.md +++ b/docs/content/4.plugins/1.built-in/security.md @@ -114,7 +114,7 @@ Renderers hand bound props to components, and Vue treats a plain object with a ` - `as`, `is` and `tag` (and their bindings) that are not strings. - Any object or array at any depth with a `template`, `render`, `ssrRender`, `setup`, `extends` or `mixins` key, such as `:icon='{"extends": {"template": "..."}}'`. -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 the same way. +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 value to `as`, `is` or `tag` still has to be a string. ::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. diff --git a/packages/comark/src/internal/sanitize.ts b/packages/comark/src/internal/sanitize.ts index 29fcfb041..4bf1649f9 100644 --- a/packages/comark/src/internal/sanitize.ts +++ b/packages/comark/src/internal/sanitize.ts @@ -467,7 +467,9 @@ export function sanitizeData(data: unknown, options: SanitizeDataOptions = {}): if (key !== undefined) { if (isUnsafePropName(name)) return REJECTED_PROP if (tagSelectors.includes(name) && isUnsafeTagSelector(key, value, isFilteredTag)) return REJECTED_PROP - if (isComponentPropViolation(key, value)) return REJECTED_PROP + // Only component options: frontmatter keys such as `tag: [vue, nuxt]` are data, and a + // binding that hands one to a component goes through the renderer's type check. + if (hasComponentOptions(value)) return REJECTED_PROP } return typeof value === 'string' ? validateString(name, value, options) : value } diff --git a/packages/comark/test/plugins/security.test.ts b/packages/comark/test/plugins/security.test.ts index 4e6513d1a..57055f856 100644 --- a/packages/comark/test/plugins/security.test.ts +++ b/packages/comark/test/plugins/security.test.ts @@ -403,6 +403,14 @@ description: "javascript: tips and tricks" }) }) + it('keeps non-string `tag` data but strips component options', async () => { + const tree = await parseWithSecurity( + '---\ntitle: Page\ntag: [vue, nuxt]\nicon:\n extends:\n template: "x"\n---\n' + ) + + expect(tree.frontmatter).toEqual({ title: 'Page', tag: ['vue', 'nuxt'] }) + }) + it('leaves frontmatter alone with `frontmatter: false`', async () => { const tree = await parseWithSecurity(md, { blockedTags: ['script'], frontmatter: false }) From 440d15d2f4744b5bca64fe108020496da94aa44d Mon Sep 17 00:00:00 2001 From: Farnabaz Date: Tue, 10 Nov 2026 15:07:34 +0100 Subject: [PATCH 6/9] perf: check shared objects once when sanitizing props --- packages/comark/src/internal/sanitize.ts | 69 +++++++++++++++---- packages/comark/test/dos.test.ts | 22 ++++++ packages/comark/test/plugins/security.test.ts | 23 ++++++- 3 files changed, 99 insertions(+), 15 deletions(-) diff --git a/packages/comark/src/internal/sanitize.ts b/packages/comark/src/internal/sanitize.ts index 4bf1649f9..9cf2a6568 100644 --- a/packages/comark/src/internal/sanitize.ts +++ b/packages/comark/src/internal/sanitize.ts @@ -279,25 +279,58 @@ const componentOptionKeys = new Set(['template', 'render', 'ssrrender', 'setup', * component options. Applied to markdown-authored values only. */ export function isComponentPropViolation(attribute: string, value: unknown): boolean { - if (componentSelectors.includes(normalizePropName(attribute)) && typeof value !== 'string') return true - return hasComponentOptions(value) + return isComponentSelectorViolation(attribute, value) || hasComponentOptions(value) } +function isComponentSelectorViolation(attribute: string, value: unknown): boolean { + return componentSelectors.includes(normalizePropName(attribute)) && typeof value !== 'string' +} + +/** + * Whether `value` is an object with a component-option key of its own. Only one level: the + * sanitizers already walk every nested object, so checking subtrees here would make them quadratic. + */ +function ownsComponentOptions(value: unknown): boolean { + if (typeof value !== 'object' || value === null || Array.isArray(value)) return false + for (const key of Object.keys(value)) { + if (componentOptionKeys.has(key.toLowerCase())) return true + } + return false +} + +// Results for objects already scanned at render time. Many bindings can resolve to one +// frontmatter object (`:a="frontmatter.big"` repeated, or YAML aliases), so each is scanned once. +// Weak keys: entries go away with the document. A value mutated after its first scan keeps its +// first result; documents are not expected to change between renders. +const componentOptionsCache = new WeakMap() + function hasComponentOptions(value: unknown): boolean { + if (typeof value !== 'object' || value === null) return false + const cached = componentOptionsCache.get(value) + if (cached !== undefined) return cached + // Iterative with a visited set: cyclic or shared (YAML alias) values neither // overflow the stack nor get scanned twice. const seen = new Set() const pending: unknown[] = [value] - while (pending.length) { + let found = false + while (pending.length && !found) { const current = pending.pop() if (typeof current !== 'object' || current === null || seen.has(current)) continue - seen.add(current) - for (const [key, item] of Object.entries(current)) { - if (!Array.isArray(current) && componentOptionKeys.has(key.toLowerCase())) return true - pending.push(item) + const known = componentOptionsCache.get(current) + if (known !== undefined) { + found = known + continue } + seen.add(current) + if (ownsComponentOptions(current)) found = true + else for (const item of Object.values(current)) pending.push(item) } - return false + // Only the root's result is certain: on an early exit, the other visited objects were + // not all fully scanned, and a negative result holds only for a complete scan. + componentOptionsCache.set(value, found) + if (!found) for (const object of seen) componentOptionsCache.set(object, false) + return found } /** A filter for tag selectors: `unsafeTags` and `blockedTags`, or any tag outside `allowedTags` when set. */ @@ -343,7 +376,7 @@ export function validateProp(attribute: string, value: unknown, options: PropsVa } catch { // Not JSON — a dot-path binding or literal, validated as-is } - if (isComponentPropViolation(attribute, decoded)) return REJECTED_PROP + if (isComponentSelectorViolation(attribute, decoded)) return REJECTED_PROP if (typeof decoded === 'object' && decoded !== null) { const result = validateValue(name, decoded, options) return result === REJECTED_PROP ? REJECTED_PROP : JSON.stringify(result) @@ -354,7 +387,7 @@ export function validateProp(attribute: string, value: unknown, options: PropsVa return result === REJECTED_PROP ? REJECTED_PROP : value } - if (isComponentPropViolation(attribute, value)) return REJECTED_PROP + if (isComponentSelectorViolation(attribute, value)) return REJECTED_PROP return validateValue(name, value, options) } @@ -390,6 +423,7 @@ function validateValue(name: string, value: unknown, options: PropsValidationOpt // Object keys are validated like top-level props, at any depth: // `:links='[{"to":"javascript:…","labelHtml":""}]'`. if (typeof value === 'object' && value !== null) { + if (ownsComponentOptions(value)) return REJECTED_PROP const entries: Array<[string, unknown]> = [] for (const [key, item] of Object.entries(value)) { const validated = validateProp(key, item, options) @@ -461,16 +495,25 @@ export function sanitizeData(data: unknown, options: SanitizeDataOptions = {}): const removed: string[] = [] const seen = new WeakMap>() + // A YAML alias can put one object under many keys: check its own keys once. + const ownsOptions = new WeakMap() + const isComponentObject = (value: unknown): boolean => { + if (typeof value !== 'object' || value === null) return false + let result = ownsOptions.get(value) + if (result === undefined) ownsOptions.set(value, (result = ownsComponentOptions(value))) + return result + } // `key` is undefined for an array item: it inherits its array's name, as in `validateProp()`. const sanitizeEntry = (name: string, key: string | undefined, value: unknown): unknown => { if (key !== undefined) { if (isUnsafePropName(name)) return REJECTED_PROP if (tagSelectors.includes(name) && isUnsafeTagSelector(key, value, isFilteredTag)) return REJECTED_PROP - // Only component options: frontmatter keys such as `tag: [vue, nuxt]` are data, and a - // binding that hands one to a component goes through the renderer's type check. - if (hasComponentOptions(value)) return REJECTED_PROP } + // Only component options, not prop types: frontmatter keys such as `tag: [vue, nuxt]` are data, + // and a binding that hands one to a component goes through the renderer's type check. + // Own keys only, array items too (`[{ template }]`): `walk` visits every nested object itself. + if (isComponentObject(value)) return REJECTED_PROP return typeof value === 'string' ? validateString(name, value, options) : value } diff --git a/packages/comark/test/dos.test.ts b/packages/comark/test/dos.test.ts index c0d2876c4..a9760a16d 100644 --- a/packages/comark/test/dos.test.ts +++ b/packages/comark/test/dos.test.ts @@ -1,8 +1,30 @@ import { describe, expect, it } from 'vitest' import { parseMarkdown } from '../src/index' import { renderMarkdown } from '../src/render' +import security from '../src/plugins/security' +import { resolveAttributes } from '../src/internal/stringify/html-attributes' describe('denial-of-service hardening', () => { + it('sanitizes frontmatter that aliases one large object under many keys in linear time', async () => { + const big = Array.from({ length: 3000 }, (_, i) => ` k${i}: {x: 1}`).join('\n') + const refs = Array.from({ length: 3000 }, (_, i) => `r${i}: *a`).join('\n') + const start = performance.now() + const doc = await parseMarkdown(`---\nbig: &a\n${big}\n${refs}\n---\nhi`, { plugins: [security()] }) + expect(performance.now() - start).toBeLessThan(500) + expect(Object.keys(doc.frontmatter)).toHaveLength(3001) + }) + + it('checks a large bound object once when many bindings resolve to it', () => { + const big: Record = {} + for (let i = 0; i < 3000; i++) big[`k${i}`] = { x: 1 } + const renderData = { frontmatter: { big }, meta: {}, data: {}, props: {} } + const start = performance.now() + for (let i = 0; i < 3000; i++) { + expect(resolveAttributes({ ':a': 'frontmatter.big' }, renderData, { parseJson: true })).toEqual({ a: big }) + } + expect(performance.now() - start).toBeLessThan(500) + }) + it('parses thousands of unclosed nested inline HTML tags without stack overflow', async () => { const md = ''.repeat(10_000) const doc = await parseMarkdown(md) diff --git a/packages/comark/test/plugins/security.test.ts b/packages/comark/test/plugins/security.test.ts index 57055f856..84fed9ddf 100644 --- a/packages/comark/test/plugins/security.test.ts +++ b/packages/comark/test/plugins/security.test.ts @@ -699,10 +699,9 @@ describe('security plugin — component-like values', () => { } }) - it('strips a bound object carrying component options at any depth', async () => { + it('strips a bound object carrying component options', async () => { const tree = makeTree([ ['span', { ':icon': '{"extends":{"template":"x"}}' }, 'x'], - ['span', { ':items': '[{"render":"x"}]' }, 'x'], ['span', { ':config': '{"setup":1}' }, 'x'], ['span', { ':config': '{"mixins":[]}' }, 'x'], ]) @@ -713,6 +712,26 @@ describe('security plugin — component-like values', () => { } }) + it('strips only the nested object carrying component options, like other nested checks', async () => { + const tree = makeTree([ + ['span', { ':items': '[{"label":"a"},{"render":"x"}]' }, 'x'], + ['span', { ':config': '{"label":"a","icon":{"template":"x"}}' }, 'x'], + ]) + await runPlugin(tree) + expect((tree.nodes[0] as [string, any])[1]).toEqual({ ':items': '[{"label":"a"}]' }) + expect((tree.nodes[1] as [string, any])[1]).toEqual({ ':config': '{"label":"a"}' }) + }) + + it('strips component options from frontmatter, in arrays too', async () => { + const tree: MarkdownDocument = { + nodes: [], + frontmatter: { icon: { extends: { template: 'x' } }, items: [{ label: 'a' }, { render: 'x' }], name: 'ok' }, + meta: {}, + } + await runPlugin(tree) + expect(tree.frontmatter).toEqual({ items: [{ label: 'a' }], name: 'ok' }) + }) + it('keeps data-valued bound props', async () => { const tree = makeTree([['span', { ':items': '[{"label":"a"}]', ':options': '{"k":"v"}' }, 'x']]) await runPlugin(tree) From edcb892b398548c6f9f596f93d126cd391d20e72 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:24:22 +0000 Subject: [PATCH 7/9] test: update bundle size snapshot --- test/bundle.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 0eefda1b4..770c9d16c 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -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": "426k (169 files)", + "comark": "427k (169 files)", } `) }) From 739272d7a7c3b213e2e9fbaf7c0a09af58cb6461 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Tue, 10 Nov 2026 14:34:32 +0000 Subject: [PATCH 8/9] fix: check VNode markers in props and keep array tag values Amp-Thread-ID: https://ampcode.com/threads/T-01a1c5ae-b7dd-7541-b1b3-7f6a41881394 --- docs/content/4.plugins/1.built-in/security.md | 8 +++--- .../test/bound-component-props.test.ts | 23 ++++++++++++++++ packages/comark/src/internal/sanitize.ts | 26 +++++++++++++++---- .../src/internal/stringify/html-attributes.ts | 2 +- packages/comark/test/plugins/security.test.ts | 22 +++++++++++++--- test/bundle.test.ts | 2 +- 6 files changed, 69 insertions(+), 14 deletions(-) diff --git a/docs/content/4.plugins/1.built-in/security.md b/docs/content/4.plugins/1.built-in/security.md index 3e86cd416..8025968e6 100644 --- a/docs/content/4.plugins/1.built-in/security.md +++ b/docs/content/4.plugins/1.built-in/security.md @@ -109,12 +109,12 @@ Framework renderers (Vue, React, Svelte, Angular) never forward `innerHTML`, `da ### 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. Its template can then run during server rendering. These values are always dropped: +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 not strings. -- Any object or array at any depth with a `template`, `render`, `ssrRender`, `setup`, `extends` or `mixins` key, such as `:icon='{"extends": {"template": "..."}}'`. +- `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 value to `as`, `is` or `tag` still has to be a string. +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. diff --git a/packages/comark-vue/test/bound-component-props.test.ts b/packages/comark-vue/test/bound-component-props.test.ts index c57e86c3d..3a3fcdac1 100644 --- a/packages/comark-vue/test/bound-component-props.test.ts +++ b/packages/comark-vue/test/bound-component-props.test.ts @@ -2,6 +2,7 @@ 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 = '{{ 7 * 191 }}' @@ -82,6 +83,28 @@ describe('bound props cannot smuggle a component into a polymorphic slot', () => } }) + 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":""},"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(/(icon<\/span>|)<\/div>$/) + } + } + }) + it('keeps string tags for `as`', async () => { const html = await renderMarkdown('::poly{:as=\'"section"\'}\n::') expect(html).toContain('
    poly
    ') diff --git a/packages/comark/src/internal/sanitize.ts b/packages/comark/src/internal/sanitize.ts index 9cf2a6568..6ee346d32 100644 --- a/packages/comark/src/internal/sanitize.ts +++ b/packages/comark/src/internal/sanitize.ts @@ -265,17 +265,32 @@ export function isTagSelector(key: string): boolean { } /** - * Props whose value must be a string. `as` and `is` pick a component in the renderers. `tag` is only checked + * 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 a plain object a compiled Vue component. JSON can't carry functions, so a JSON object with these is never a legit component. */ -const componentOptionKeys = new Set(['template', 'render', 'ssrrender', 'setup', 'extends', 'mixins']) +/** + * 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. + */ +const componentOptionKeys = new Set([ + 'template', + 'render', + 'ssrrender', + 'setup', + 'extends', + 'mixins', + '__v_isvnode', + '__isteleport', + '__issuspense', + '__iskeepalive', +]) /** * Whether a decoded prop value could make a renderer treat it as a component: - * `as` / `is` / `tag` must be strings, and no object at any depth may carry + * `as` / `is` / `tag` must not be objects, and no object at any depth may carry * component options. Applied to markdown-authored values only. */ export function isComponentPropViolation(attribute: string, value: unknown): boolean { @@ -283,7 +298,8 @@ export function isComponentPropViolation(attribute: string, value: unknown): boo } function isComponentSelectorViolation(attribute: string, value: unknown): boolean { - return componentSelectors.includes(normalizePropName(attribute)) && typeof value !== 'string' + if (!componentSelectors.includes(normalizePropName(attribute))) return false + return typeof value === 'function' || (typeof value === 'object' && value !== null && !Array.isArray(value)) } /** diff --git a/packages/comark/src/internal/stringify/html-attributes.ts b/packages/comark/src/internal/stringify/html-attributes.ts index 23547ed2b..129b4091a 100644 --- a/packages/comark/src/internal/stringify/html-attributes.ts +++ b/packages/comark/src/internal/stringify/html-attributes.ts @@ -86,7 +86,7 @@ export function resolveAttributes( } // Hard floor: a prop must never hand a renderer a value it could treat as a - // component (`as` / `is` / `tag` strings only, no component options at any depth). + // component (`as` / `is` / `tag` never objects, no component options or VNode markers at any depth). // Unbound props count too: the parser decodes `as='{…}'` into an object. if (options.parseJson && isComponentPropViolation(outKey, outValue)) continue diff --git a/packages/comark/test/plugins/security.test.ts b/packages/comark/test/plugins/security.test.ts index 84fed9ddf..29cdc2d97 100644 --- a/packages/comark/test/plugins/security.test.ts +++ b/packages/comark/test/plugins/security.test.ts @@ -686,11 +686,11 @@ describe('security plugin — as prop', () => { }) describe('security plugin — component-like values', () => { - it('strips a non-string as or is or tag', async () => { + it('strips an object as or is or tag', async () => { const tree = makeTree([ ['span', { ':as': '{"template":"x"}' }, 'x'], - ['span', { ':is': '["a"]' }, 'x'], - ['span', { tag: 42 }, 'x'], + ['span', { ':is': '{"label":"a"}' }, 'x'], + ['span', { tag: { name: 'a' } }, 'x'], ]) await runPlugin(tree) for (const node of tree.nodes) { @@ -699,6 +699,22 @@ 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']]) + await runPlugin(tree) + expect((tree.nodes[0] as [string, any])[1]).toEqual({ ':tag': '["hello","world"]', ':is': '5', ':as': 'true' }) + }) + + it('strips a forged VNode at any depth', async () => { + const tree = makeTree([ + ['span', { ':icon': '{"__v_isVNode":true,"type":"script","shapeFlag":1}' }, 'x'], + ['span', { ':config': '{"label":"a","icon":{"__v_isVNode":true,"type":"script"}}' }, 'x'], + ]) + await runPlugin(tree, { blockedTags: ['script'] }) + expect((tree.nodes[0] as [string, any])[1]).toEqual({}) + expect((tree.nodes[1] as [string, any])[1]).toEqual({ ':config': '{"label":"a"}' }) + }) + it('strips a bound object carrying component options', async () => { const tree = makeTree([ ['span', { ':icon': '{"extends":{"template":"x"}}' }, 'x'], diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 770c9d16c..89f0f487e 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -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": "427k (169 files)", + "comark": "428k (169 files)", } `) }) From 4e60343afa27d8b355b203cb180172c078f3a948 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Tue, 10 Nov 2026 14:51:09 +0000 Subject: [PATCH 9/9] fix: drop object props holding innerHTML or textContent at any depth Amp-Thread-ID: https://ampcode.com/threads/T-01a1c5ae-b7dd-7541-b1b3-7f6a41881394 --- docs/content/4.plugins/1.built-in/security.md | 2 +- .../test/bound-component-props.test.ts | 50 +++++++++++++++++++ packages/comark/src/internal/sanitize.ts | 47 ++++++++++++----- .../src/internal/stringify/html-attributes.ts | 22 +++----- 4 files changed, 93 insertions(+), 28 deletions(-) diff --git a/docs/content/4.plugins/1.built-in/security.md b/docs/content/4.plugins/1.built-in/security.md index 8025968e6..de1dfbbb2 100644 --- a/docs/content/4.plugins/1.built-in/security.md +++ b/docs/content/4.plugins/1.built-in/security.md @@ -104,7 +104,7 @@ 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 diff --git a/packages/comark-vue/test/bound-component-props.test.ts b/packages/comark-vue/test/bound-component-props.test.ts index 3a3fcdac1..e3e4cb698 100644 --- a/packages/comark-vue/test/bound-component-props.test.ts +++ b/packages/comark-vue/test/bound-component-props.test.ts @@ -111,6 +111,56 @@ describe('bound props cannot smuggle a component into a polymorphic slot', () => }) }) +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 = '""' + 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(/ { + const html = await render(`::spread{:items='[{"class":"a"},{"title":"b"}]'}\n::`) + expect(html).toContain('
    • item
    • item
    ') + }) +}) + describe('data-valued bound props', () => { it('passes object and array data props through unchanged', async () => { const html = await renderMarkdown('::items{:items=\'[{"label":"a"}]\'}\n::') diff --git a/packages/comark/src/internal/sanitize.ts b/packages/comark/src/internal/sanitize.ts index 6ee346d32..ccc52c957 100644 --- a/packages/comark/src/internal/sanitize.ts +++ b/packages/comark/src/internal/sanitize.ts @@ -288,13 +288,27 @@ const componentOptionKeys = new Set([ '__iskeepalive', ]) +// DOM sinks that turn a string/object prop into raw markup (`innerHTML`, +// `dangerouslySetInnerHTML`) or overwrite an element's children +// (`textContent`). Framework renderers hand resolved attributes to +// `h()`/`createElement`/spreads verbatim, so these keys are never forwarded +// from document attributes — raw HTML has its own explicit path. +const htmlSinkProps = new Set(['innerhtml', 'dangerouslysetinnerhtml', 'textcontent']) + +/** Whether `key` writes an HTML sink. Vue's `.prop` / `^attr` prefixes still write the named DOM property. */ +export function isHtmlSinkKey(key: string): boolean { + return htmlSinkProps.has(key.replace(/^[.^]/, '').toLowerCase()) +} + /** - * Whether a decoded prop value could make a renderer treat it as a component: - * `as` / `is` / `tag` must not be objects, and no object at any depth may carry - * component options. Applied to markdown-authored values only. + * 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 + * 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. */ -export function isComponentPropViolation(attribute: string, value: unknown): boolean { - return isComponentSelectorViolation(attribute, value) || hasComponentOptions(value) +export function isUnsafeRendererProp(attribute: string, value: unknown): boolean { + return isComponentSelectorViolation(attribute, value) || hasUnsafeObjectKeys(value) } function isComponentSelectorViolation(attribute: string, value: unknown): boolean { @@ -314,15 +328,24 @@ function ownsComponentOptions(value: unknown): boolean { return false } +/** Whether `value` is an object with an HTML sink key of its own. */ +function ownsHtmlSink(value: object): boolean { + if (Array.isArray(value)) return false + for (const key of Object.keys(value)) { + if (isHtmlSinkKey(key)) return true + } + return false +} + // Results for objects already scanned at render time. Many bindings can resolve to one // frontmatter object (`:a="frontmatter.big"` repeated, or YAML aliases), so each is scanned once. // Weak keys: entries go away with the document. A value mutated after its first scan keeps its // first result; documents are not expected to change between renders. -const componentOptionsCache = new WeakMap() +const unsafeObjectKeysCache = new WeakMap() -function hasComponentOptions(value: unknown): boolean { +function hasUnsafeObjectKeys(value: unknown): boolean { if (typeof value !== 'object' || value === null) return false - const cached = componentOptionsCache.get(value) + const cached = unsafeObjectKeysCache.get(value) if (cached !== undefined) return cached // Iterative with a visited set: cyclic or shared (YAML alias) values neither @@ -333,19 +356,19 @@ function hasComponentOptions(value: unknown): boolean { while (pending.length && !found) { const current = pending.pop() if (typeof current !== 'object' || current === null || seen.has(current)) continue - const known = componentOptionsCache.get(current) + const known = unsafeObjectKeysCache.get(current) if (known !== undefined) { found = known continue } seen.add(current) - if (ownsComponentOptions(current)) found = true + if (ownsComponentOptions(current) || ownsHtmlSink(current)) found = true else for (const item of Object.values(current)) pending.push(item) } // Only the root's result is certain: on an early exit, the other visited objects were // not all fully scanned, and a negative result holds only for a complete scan. - componentOptionsCache.set(value, found) - if (!found) for (const object of seen) componentOptionsCache.set(object, false) + unsafeObjectKeysCache.set(value, found) + if (!found) for (const object of seen) unsafeObjectKeysCache.set(object, false) return found } diff --git a/packages/comark/src/internal/stringify/html-attributes.ts b/packages/comark/src/internal/stringify/html-attributes.ts index 129b4091a..236de57a1 100644 --- a/packages/comark/src/internal/stringify/html-attributes.ts +++ b/packages/comark/src/internal/stringify/html-attributes.ts @@ -1,5 +1,5 @@ import { escapeHtml, get } from '../../utils/index.ts' -import { isComponentPropViolation, isUnsafeUrlValue, isUrlPropKey } from '../sanitize.ts' +import { isHtmlSinkKey, isUnsafeRendererProp, isUnsafeUrlValue, isUrlPropKey } from '../sanitize.ts' import type { NodeRenderData } from '../../types.ts' export interface ResolveAttributesOptions { @@ -18,13 +18,6 @@ export interface ResolveAttributesOptions { parseJson?: boolean } -// DOM sinks that turn a string/object prop into raw markup (`innerHTML`, -// `dangerouslySetInnerHTML`) or overwrite an element's children -// (`textContent`). Framework renderers hand resolved attributes to -// `h()`/`createElement`/spreads verbatim, so these keys are never forwarded -// from document attributes — raw HTML has its own explicit path. -const HTML_SINK_PROPS = new Set(['innerhtml', 'dangerouslysetinnerhtml', 'textcontent']) - /** * Resolve `:prefixed` attributes against the render context. * @@ -50,10 +43,8 @@ export function resolveAttributes( const value = attrs[key] const isBinding = key.charCodeAt(0) === 58 /* ':' */ const outKey = isBinding ? key.slice(1) : key - // Vue's `.prop` / `^attr` prefixes still write the named DOM property - const lowerOutKey = outKey.replace(/^[.^]/, '').toLowerCase() - - if (HTML_SINK_PROPS.has(lowerOutKey)) continue + // HTML sinks are never forwarded from document attributes; see `isHtmlSinkKey` + if (isHtmlSinkKey(outKey)) continue let outValue: unknown let resultKey = key @@ -86,9 +77,10 @@ export function resolveAttributes( } // Hard floor: a prop must never hand a renderer a value it could treat as a - // component (`as` / `is` / `tag` never objects, no component options or VNode markers at any depth). - // Unbound props count too: the parser decodes `as='{…}'` into an object. - if (options.parseJson && isComponentPropViolation(outKey, outValue)) continue + // component (`as` / `is` / `tag` never objects, no component options or VNode markers at any depth), + // or an HTML sink nested in an object prop. Unbound props count too: the parser decodes `as='{…}'` + // into an object. + if (options.parseJson && isUnsafeRendererProp(outKey, outValue)) continue // Hard floor: a binding must never resolve a URL prop to an unsafe scheme // (javascript:, data:text/html, …). Parse-time validation only sees the