Skip to content

Commit 6cbe361

Browse files
usualomandycode
andauthored
fix(jsx): escape element and object attribute values (#5512)
* fix(jsx): escape element and object attribute values Render JSX nodes and other objects as escaped attribute text, including promised values and asynchronous toString results. Mark precompiled JSX templates so their child-content escaping is not trusted inside attributes. Keep raw() and html values explicitly trusted, and prevent callbacks from escaped nodes from propagating into the outer stream. Cover both runtimes and the Deno precompile transform. Co-authored-by: Taku Amano <[email protected]> * perf(jsx): use a set for boolean attribute lookup Use Set.has for boolean attribute membership without changing the accepted attribute names or their rendering. * fix(jsx): serialize boolean attributes in precompiled JSX Omit false boolean attributes and emit an empty value for true ones in jsxAttr, matching JSXNode. Preserve true/false text for non-boolean names. * feat(jsx): support declarative Shadow DOM boolean attributes Recognize shadowrootclonable, shadowrootdelegatesfocus, and shadowrootserializable as boolean attributes. Cover true and false values in both attribute serializers. Co-authored-by: Taku Amano <[email protected]> * fix(jsx): omit null style attributes Skip null style values before traversing the style object in both JSXNode and jsxAttr. Cover null and undefined omission. Co-authored-by: Taku Amano <[email protected]> * fix(jsx): validate function attributes in precompiled JSX Skip on-prefixed event handlers and ref callbacks in jsxAttr. Reject functions on other attributes with the same rule as JSXNode, including when the Deno precompile transform calls jsxAttr. Co-authored-by: Taku Amano <[email protected]> * refactor(jsx): share attribute serialization between JSXNode and jsxAttr Use attributeToBuffer for both render paths so attribute handling cannot drift between them. Keep the explicit string conversion required by the buffer type. Handle dangerouslySetInnerHTML separately when the value is an object with __html; other values follow the normal attribute serializer. * perf(jsx): add a string fast path to jsxAttr Escape string values directly in jsxAttr instead of going through attributeToBuffer. Strings are the common case in precompiled JSX, and the shared serializer made them about 50% slower on Deno. * fix(jsx): resolve function form actions in precompiled JSX Functions passed to action and formaction threw in jsxAttr, while the form, input and button intrinsic elements accept them when rendered through JSXNode. Resolve them in the same way: use the permalink when one is attached and omit the attribute otherwise. * fix(jsx): escape async render results used as attribute values An asynchronous JSXNode.toString() resolves to an HtmlEscapedString that contains markup. It was trusted as an attribute value, while the string from a synchronous render was escaped. Mark it in the same way as a precompiled template so that both are escaped. * refactor(jsx): rename JSX_TEMPLATE to RENDERED_JSX The mark is no longer specific to precompiled templates; asynchronous JSXNode render results carry it too. Rename the symbol and its helper to match. No behavior change. --------- Co-authored-by: Neil <[email protected]>
1 parent 8b7f9e9 commit 6cbe361

6 files changed

Lines changed: 358 additions & 68 deletions

File tree

‎runtime-tests/deno-jsx/jsx.test.tsx‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/** @jsxImportSource ../../src/jsx */
2-
import { assertEquals } from '@std/assert'
2+
import { assertEquals, assertThrows } from '@std/assert'
33
import { Style, css } from '../../src/helper/css/index.ts'
44
import { Suspense, renderToReadableStream } from '../../src/jsx/streaming.ts'
55
import type { HtmlEscapedString } from '../../src/utils/html.ts'
@@ -187,3 +187,50 @@ Deno.test('JSX: style', async () => {
187187
const html = <div style={{ fontSize: '12px', color: null }}></div>
188188
assertEquals(html.toString(), '<div style="font-size:12px"></div>')
189189
})
190+
191+
Deno.test('JSX: escape elements used as attribute values', async () => {
192+
const input = 'x onmouseover=alert(1)//'
193+
const node = <span data-label={input}>label</span>
194+
const Async = async () => <span data-label={input}>label</span>
195+
const values = [
196+
node,
197+
Promise.resolve(node),
198+
<span data-label={Promise.resolve(input) as never}>label</span>,
199+
<Async />,
200+
(<Async />).toString(),
201+
]
202+
const expected =
203+
'<div title="&lt;span data-label=&quot;x onmouseover=alert(1)//&quot;&gt;label&lt;/span&gt;">outer</div>'
204+
205+
for (const value of values) {
206+
// A spread makes the precompile transform use JSXNode for the outer element.
207+
for (const element of [
208+
<div title={value as never}>outer</div>,
209+
<div {...{ title: value as never }}>outer</div>,
210+
]) {
211+
assertEquals(String(await (await element).toString()), expected)
212+
}
213+
}
214+
})
215+
216+
Deno.test('JSX: reject function values for non-event attributes', () => {
217+
const handler = () => 'source'
218+
assertThrows(
219+
() => (<div data-value={handler}>outer</div>).toString(),
220+
Error,
221+
"Invalid prop 'data-value' of type 'function'"
222+
)
223+
})
224+
225+
Deno.test('JSX: function form actions', () => {
226+
const action = () => {}
227+
const html = (
228+
<form action={action}>
229+
<button formAction={action}>go</button>
230+
</form>
231+
)
232+
233+
// react-jsx : <form><button>
234+
// precompile : <form ><button >
235+
assertEquals(html.toString().replace(/ >/g, '>'), '<form><button>go</button></form>')
236+
})

‎src/jsx/base.test.tsx‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,59 @@ describe('createElement', () => {
9595
expect((<div>{object as never}</div>).toString()).toBe('<div></div>')
9696
})
9797
})
98+
99+
describe('attribute value escaping', () => {
100+
it('should escape a JSX node used as an attribute value', () => {
101+
const element = <div title={(<img src='y' onerror='alert(1)' />) as never}>x</div>
102+
expect(element.toString()).toBe(
103+
'<div title="&lt;img src=&quot;y&quot; onerror=&quot;alert(1)&quot;/&gt;">x</div>'
104+
)
105+
})
106+
107+
it('should escape a JSX node resolved from a promise attribute', async () => {
108+
const element = (
109+
<div title={Promise.resolve(<img src='y' onerror='alert(1)' />) as never}>x</div>
110+
)
111+
expect(String(await element.toString())).toBe(
112+
'<div title="&lt;img src=&quot;y&quot; onerror=&quot;alert(1)&quot;/&gt;">x</div>'
113+
)
114+
})
115+
116+
it('should escape an async component node used as an attribute value', async () => {
117+
const Async = async () => <img src='y' onerror='alert(1)' />
118+
const element = <div title={(<Async />) as never}>x</div>
119+
expect(String(await element.toString())).toBe(
120+
'<div title="&lt;img src=&quot;y&quot; onerror=&quot;alert(1)&quot;/&gt;">x</div>'
121+
)
122+
})
123+
124+
it('should escape an async render result used as an attribute value', async () => {
125+
const Async = async () => <img src='y' onerror='alert(1)' />
126+
const rendered = await (<Async />).toString()
127+
expect((<div title={rendered}>x</div>).toString()).toBe(
128+
'<div title="&lt;img src=&quot;y&quot; onerror=&quot;alert(1)&quot;/&gt;">x</div>'
129+
)
130+
expect((<div>{rendered}</div>).toString()).toBe('<div><img src="y" onerror="alert(1)"/></div>')
131+
})
132+
133+
it('should escape a plain object resolved from a promise attribute', async () => {
134+
const element = <div title={Promise.resolve({ toString: () => '<b>x</b>' }) as never}>x</div>
135+
expect(String(await element.toString())).toBe('<div title="&lt;b&gt;x&lt;/b&gt;">x</div>')
136+
})
137+
})
138+
139+
describe('declarative Shadow DOM boolean attributes', () => {
140+
it.each(['shadowrootclonable', 'shadowrootdelegatesfocus', 'shadowrootserializable'])(
141+
'should render %s only when true',
142+
(key) => {
143+
expect((<template {...{ [key]: true }} />).toString()).toBe(`<template ${key}=""></template>`)
144+
expect((<template {...{ [key]: false }} />).toString()).toBe('<template></template>')
145+
}
146+
)
147+
})
148+
149+
describe('style attributes', () => {
150+
it.each([null, undefined])('should omit a %s style attribute', (style) => {
151+
expect((<div style={style as never} />).toString()).toBe('<div></div>')
152+
})
153+
})

‎src/jsx/base.ts‎

Lines changed: 92 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import { raw } from '../helper/html'
22
import { escapeToBuffer, resolveCallbackSync, stringBufferToString } from '../utils/html'
3-
import type { HtmlEscaped, HtmlEscapedString, StringBufferWithCallbacks } from '../utils/html'
4-
import { DOM_RENDERER, DOM_MEMO } from './constants'
3+
import type {
4+
HtmlEscaped,
5+
HtmlEscapedString,
6+
StringBuffer,
7+
StringBufferWithCallbacks,
8+
} from '../utils/html'
9+
import { DOM_RENDERER, DOM_MEMO, RENDERED_JSX } from './constants'
510
import {
611
captureRenderContext,
712
createContext,
@@ -82,7 +87,7 @@ const emptyTags = [
8287
'track',
8388
'wbr',
8489
]
85-
export const booleanAttributes = [
90+
export const booleanAttributes = new Set([
8691
'allowfullscreen',
8792
'async',
8893
'autofocus',
@@ -109,7 +114,10 @@ export const booleanAttributes = [
109114
'required',
110115
'reversed',
111116
'selected',
112-
]
117+
'shadowrootclonable',
118+
'shadowrootdelegatesfocus',
119+
'shadowrootserializable',
120+
])
113121

114122
type SuspendedContext = <T>(callback: () => T) => T
115123

@@ -136,6 +144,78 @@ const resolveFunctionComponentResult = (
136144
return suspendedContext ? suspendedContext(render) : runWithRenderContext(render)
137145
})
138146

147+
// Rendered JSX is escaped for use as child content, but still contains markup.
148+
export const markRenderedJSX = (value: HtmlEscapedString): HtmlEscapedString => {
149+
;(value as unknown as Record<symbol, boolean>)[RENDERED_JSX] = true
150+
return value
151+
}
152+
153+
const isEscapedAttribute = (value: unknown): value is HtmlEscapedString =>
154+
value instanceof String && (value as unknown as HtmlEscaped).isEscaped && !(RENDERED_JSX in value)
155+
156+
const objectToAttributeString = (v: object): string | Promise<string> => {
157+
const s = v.toString() as string | Promise<string>
158+
return s instanceof Promise ? s.then(String) : String(s)
159+
}
160+
161+
export const attributeToBuffer = (
162+
buffer: StringBuffer,
163+
prefix: string,
164+
key: string,
165+
v: unknown,
166+
tag?: string
167+
): void => {
168+
if (v === null || v === undefined) {
169+
return
170+
}
171+
if (typeof v === 'boolean' && booleanAttributes.has(key)) {
172+
if (v) {
173+
buffer[0] += `${prefix}${key}=""`
174+
}
175+
return
176+
}
177+
if (typeof v === 'function') {
178+
if (!key.startsWith('on') && key !== 'ref') {
179+
throw new Error(
180+
`Invalid prop '${key}' of type 'function' supplied to ${tag ? `'${tag}'` : 'a JSX element'}.`
181+
)
182+
}
183+
// maybe event handler for client components, just ignore in server components
184+
return
185+
}
186+
187+
buffer[0] += `${prefix}${key}="`
188+
if (key === 'style' && typeof v === 'object') {
189+
// object to style strings
190+
let styleStr = ''
191+
styleObjectForEach(v as Record<string, unknown>, (property, value) => {
192+
if (value != null) {
193+
styleStr += `${styleStr ? ';' : ''}${property}:${value}`
194+
}
195+
})
196+
escapeToBuffer(styleStr, buffer)
197+
} else if (typeof v === 'string') {
198+
escapeToBuffer(v, buffer)
199+
} else if (typeof v === 'number' || isEscapedAttribute(v)) {
200+
buffer[0] += `${v}`
201+
} else {
202+
const s =
203+
v instanceof Promise
204+
? v.then((r) =>
205+
typeof r === 'object' && r !== null && !isEscapedAttribute(r)
206+
? objectToAttributeString(r)
207+
: r
208+
)
209+
: objectToAttributeString(v as object)
210+
if (s instanceof Promise) {
211+
buffer.unshift('"', s)
212+
return
213+
}
214+
escapeToBuffer(s, buffer)
215+
}
216+
buffer[0] += '"'
217+
}
218+
139219
const childrenToStringToBuffer = (children: Child[], buffer: StringBufferWithCallbacks): void => {
140220
for (let i = 0, len = children.length; i < len; i++) {
141221
const child = children[i]
@@ -232,7 +312,7 @@ export class JSXNode implements HtmlEscaped {
232312
? 'callbacks' in buffer
233313
? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString()
234314
: buffer[0]
235-
: stringBufferToString(buffer, buffer.callbacks)
315+
: stringBufferToString(buffer, buffer.callbacks).then(markRenderedJSX)
236316
}
237317
return runWithRenderContext(render)
238318
}
@@ -255,47 +335,19 @@ export class JSXNode implements HtmlEscaped {
255335
}
256336
if (key === 'children') {
257337
// skip children
258-
} else if (key === 'style' && typeof v === 'object') {
259-
// object to style strings
260-
let styleStr = ''
261-
styleObjectForEach(v, (property, value) => {
262-
if (value != null) {
263-
styleStr += `${styleStr ? ';' : ''}${property}:${value}`
264-
}
265-
})
266-
buffer[0] += ' style="'
267-
escapeToBuffer(styleStr, buffer)
268-
buffer[0] += '"'
269-
} else if (typeof v === 'string') {
270-
buffer[0] += ` ${key}="`
271-
escapeToBuffer(v, buffer)
272-
buffer[0] += '"'
273-
} else if (v === null || v === undefined) {
274-
// Do nothing
275-
} else if (typeof v === 'number' || (v as HtmlEscaped).isEscaped) {
276-
buffer[0] += ` ${key}="${v}"`
277-
} else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {
278-
if (v) {
279-
buffer[0] += ` ${key}=""`
280-
}
281-
} else if (key === 'dangerouslySetInnerHTML') {
338+
} else if (
339+
key === 'dangerouslySetInnerHTML' &&
340+
typeof v === 'object' &&
341+
v !== null &&
342+
'__html' in v
343+
) {
282344
if (children.length > 0) {
283345
throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.')
284346
}
285347

286348
children = [raw(v.__html)]
287-
} else if (v instanceof Promise) {
288-
buffer[0] += ` ${key}="`
289-
buffer.unshift('"', v)
290-
} else if (typeof v === 'function') {
291-
if (!key.startsWith('on') && key !== 'ref') {
292-
throw new Error(`Invalid prop '${key}' of type 'function' supplied to '${tag}'.`)
293-
}
294-
// maybe event handler for client components, just ignore in server components
295349
} else {
296-
buffer[0] += ` ${key}="`
297-
escapeToBuffer(v.toString(), buffer)
298-
buffer[0] += '"'
350+
attributeToBuffer(buffer, ' ', key, v, tag)
299351
}
300352
}
301353

‎src/jsx/constants.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ export const DOM_STASH = Symbol('STASH')
44
export const DOM_INTERNAL_TAG = Symbol('INTERNAL')
55
export const DOM_MEMO = Symbol('MEMO')
66
export const PERMALINK = Symbol('PERMALINK')
7+
export const RENDERED_JSX = Symbol('RENDERED_JSX')

0 commit comments

Comments
 (0)