diff --git a/docs/content/4.plugins/1.built-in/security.md b/docs/content/4.plugins/1.built-in/security.md index f2df50b2..de1dfbbb 100644 --- a/docs/content/4.plugins/1.built-in/security.md +++ b/docs/content/4.plugins/1.built-in/security.md @@ -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 diff --git a/packages/comark-angular/src/components/markdown-node.component.ts b/packages/comark-angular/src/components/markdown-node.component.ts index d40c030b..314afd67 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 ca38cca2..68039aef 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 00000000..8e471f27 --- /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-vue/src/components/MarkdownDocument.ts b/packages/comark-vue/src/components/MarkdownDocument.ts index ddaae93e..cc84beb9 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 00000000..e3e4cb69 --- /dev/null +++ b/packages/comark-vue/test/bound-component-props.test.ts @@ -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 = '{{ 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('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('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
') + }) +}) + +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::') + expect(html).toContain('
  • a
  • ') + }) +}) diff --git a/packages/comark/src/internal/sanitize.ts b/packages/comark/src/internal/sanitize.ts index 2babe9e2..ccc52c95 100644 --- a/packages/comark/src/internal/sanitize.ts +++ b/packages/comark/src/internal/sanitize.ts @@ -264,6 +264,114 @@ 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. + */ +const componentOptionKeys = new Set([ + 'template', + 'render', + 'ssrrender', + 'setup', + 'extends', + 'mixins', + '__v_isvnode', + '__isteleport', + '__issuspense', + '__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 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 isUnsafeRendererProp(attribute: string, value: unknown): boolean { + return isComponentSelectorViolation(attribute, value) || hasUnsafeObjectKeys(value) +} + +function isComponentSelectorViolation(attribute: string, value: unknown): boolean { + if (!componentSelectors.includes(normalizePropName(attribute))) return false + return typeof value === 'function' || (typeof value === 'object' && value !== null && !Array.isArray(value)) +} + +/** + * 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 +} + +/** 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 unsafeObjectKeysCache = new WeakMap() + +function hasUnsafeObjectKeys(value: unknown): boolean { + if (typeof value !== 'object' || value === null) return false + const cached = unsafeObjectKeysCache.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] + let found = false + while (pending.length && !found) { + const current = pending.pop() + if (typeof current !== 'object' || current === null || seen.has(current)) continue + const known = unsafeObjectKeysCache.get(current) + if (known !== undefined) { + found = known + continue + } + seen.add(current) + 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. + unsafeObjectKeysCache.set(value, found) + if (!found) for (const object of seen) unsafeObjectKeysCache.set(object, false) + return found +} + /** 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 +415,7 @@ export function validateProp(attribute: string, value: unknown, options: PropsVa } catch { // Not JSON — a dot-path binding or literal, validated as-is } + 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) @@ -317,6 +426,7 @@ export function validateProp(attribute: string, value: unknown, options: PropsVa return result === REJECTED_PROP ? REJECTED_PROP : value } + if (isComponentSelectorViolation(attribute, value)) return REJECTED_PROP return validateValue(name, value, options) } @@ -352,6 +462,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) @@ -423,6 +534,14 @@ 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 => { @@ -430,6 +549,10 @@ export function sanitizeData(data: unknown, options: SanitizeDataOptions = {}): if (isUnsafePropName(name)) return REJECTED_PROP if (tagSelectors.includes(name) && isUnsafeTagSelector(key, value, isFilteredTag)) 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/src/internal/stringify/html-attributes.ts b/packages/comark/src/internal/stringify/html-attributes.ts index 36dbbfc3..236de57a 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 { 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 @@ -85,6 +76,12 @@ export function resolveAttributes( outValue = value } + // 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), + // 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 // literal path, so the resolved value is checked here — even when the diff --git a/packages/comark/test/dos.test.ts b/packages/comark/test/dos.test.ts index c0d2876c..a9760a16 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 189380d4..29cdc2d9 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 }) @@ -677,6 +685,77 @@ describe('security plugin — as prop', () => { }) }) +describe('security plugin — component-like values', () => { + it('strips an object as or is or tag', async () => { + const tree = makeTree([ + ['span', { ':as': '{"template":"x"}' }, 'x'], + ['span', { ':is': '{"label":"a"}' }, 'x'], + ['span', { tag: { name: 'a' } }, 'x'], + ]) + await runPlugin(tree) + for (const node of tree.nodes) { + const el = node as [string, any] + expect(el[1]).toEqual({}) + } + }) + + 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'], + ['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('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) + 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' }]]) diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 83183dd2..89f0f487 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": "428k (169 files)", } `) })