src/jsx/jsx-runtime.test.tsx+143 −1
@@ -1,7 +1,13 @@ /** @jsxRuntime automatic **/ /** @jsxImportSource . **/++import { html, raw } from '../helper/html' import { Hono } from '../hono'-import { jsxAttr } from './jsx-runtime'+import { HtmlEscapedCallbackPhase } from '../utils/html'+import type { HtmlEscapedCallback } from '../utils/html'+import { PERMALINK } from './constants'+import { jsxAttr, jsxTemplate } from './jsx-runtime'+import { renderToReadableStream } from './streaming' describe('jsx-runtime', () => { let app: Hono@@ -32,6 +38,7 @@ describe('jsx-runtime', () => { expect(String(jsxAttr(invalidKey, { fontSize: 10 }))).toBe('') expect(String(await jsxAttr(invalidKey, Promise.resolve('/docs?q=1&lang=en')))).toBe('')+ expect(String(jsxAttr(invalidKey, (() => 'x') as never))).toBe('') }) it('Should render valid attribute values in jsxAttr()', async () => {@@ -43,6 +50,141 @@ describe('jsx-runtime', () => { ) }) + it('Should render nothing for a null style object in jsxAttr()', () => {+ expect(String(jsxAttr('style', null as never))).toBe('')+ })++ it('Should handle boolean attributes in jsxAttr()', () => {+ expect(String(jsxAttr('disabled', false as never))).toBe('')+ expect(String(jsxAttr('disabled', true as never))).toBe('disabled=""')+ // non-boolean attributes keep their value, matching JSXNode rendering+ expect(String(jsxAttr('data-flag', false as never))).toBe('data-flag="false"')+ })++ it.each(['shadowrootclonable', 'shadowrootdelegatesfocus', 'shadowrootserializable'])(+ 'Should render %s only when true in jsxAttr()',+ (key) => {+ expect(String(jsxAttr(key, true as never))).toBe(`${key}=""`)+ expect(String(jsxAttr(key, false as never))).toBe('')+ }+ )++ it('Should skip event handlers and ref callbacks in jsxAttr()', () => {+ const handler = () => 'source'+ expect(String(jsxAttr('onclick', handler as never))).toBe('')+ expect(String(jsxAttr('onClick', handler as never))).toBe('')+ expect(String(jsxAttr('ref', handler as never))).toBe('')+ })++ it.each(['title', 'data-x'])('Should reject function values for %s in jsxAttr()', (key) => {+ expect(() => jsxAttr(key, (() => 'source') as never)).toThrow(+ `Invalid prop '${key}' of type 'function'`+ )+ })++ it.each(['action', 'formaction'])('Should resolve function values for %s in jsxAttr()', (key) => {+ expect(String(jsxAttr(key, (() => {}) as never))).toBe('')+ const action = Object.assign(() => {}, { [PERMALINK]: '/permalink?a=1&b=2' })+ expect(String(jsxAttr(key, action as never))).toBe(`${key}="/permalink?a=1&b=2"`)+ })++ it('Should escape a JSX node resolved from a promise attribute in jsxAttr()', async () => {+ expect(String(await jsxAttr('title', Promise.resolve(<img src='y' />) as never))).toBe(+ 'title="<img src="y"/>"'+ )+ })++ it('Should escape an async render result in jsxAttr()', async () => {+ const Async = async () => <img src='y' />+ expect(String(jsxAttr('title', await (<Async />).toString()))).toBe(+ 'title="<img src="y"/>"'+ )+ })++ describe('precompiled JSX attribute values', () => {+ const input = 'x onmouseover=alert(1)//'+ const expected =+ 'title="<span data-label="x onmouseover=alert(1)//">label</span>"'++ it.each([+ ['a template', () => jsxTemplate`<span data-label="${input}">label</span>`],+ [+ 'a promised template',+ () => Promise.resolve(jsxTemplate`<span data-label="${input}">label</span>`),+ ],+ [+ 'an asynchronous template',+ () => jsxTemplate`<span data-label="${Promise.resolve(input)}">label</span>`,+ ],+ ])('Should escape %s in both attribute serializers', async (_name, createValue) => {+ const value = createValue()+ expect(String(await jsxAttr('title', value))).toBe(expected)+ expect(String(await (<div title={value as never}>outer</div>).toString())).toBe(+ `<div ${expected}>outer</div>`+ )+ })++ it('Should keep templates unescaped when rendered as children', async () => {+ const child = jsxTemplate`<span>${Promise.resolve('<label>')}</span>`+ expect(String(await jsxTemplate`<div>${child}</div>`)).toBe(+ '<div><span><label></span></div>'+ )+ expect(String(await (<div>{child}</div>).toString())).toBe(+ '<div><span><label></span></div>'+ )+ })++ it.each(['JSX node', 'precompiled template'])(+ 'Should not propagate callbacks from a promised %s attribute',+ async (kind) => {+ const callback = vi.fn<HtmlEscapedCallback>(({ phase }) =>+ phase === HtmlEscapedCallbackPhase.Stream+ ? Promise.resolve('<b>callback output</b>')+ : undefined+ )+ const Async = async () => raw('inner', [callback])+ const value = Promise.resolve(+ kind === 'JSX node' ? (+ <span>+ <Async />+ </span>+ ) : (+ jsxTemplate`<span>${<Async />}</span>`+ )+ )++ for (const element of [+ <div title={value as never}>outer</div>,+ jsxTemplate`<div ${jsxAttr('title', value)}>outer</div>`,+ ]) {+ const output = await new Response(renderToReadableStream(element)).text()+ expect(callback).not.toHaveBeenCalled()+ expect(output).toBe('<div title="<span>inner</span>">outer</div>')+ }++ // The same value must retain its callbacks when used as child content.+ const output = await new Response(renderToReadableStream(<div>{value}</div>)).text()+ expect(output).toBe('<div><span>inner</span></div><b>callback output</b>')+ expect(callback.mock.calls.map(([{ phase }]) => phase)).toEqual([+ HtmlEscapedCallbackPhase.BeforeStream,+ HtmlEscapedCallbackPhase.Stream,+ ])+ }+ )++ it.each([raw('<label>'), html`${'<label>'}`])(+ 'Should preserve explicitly escaped attribute values',+ async (value) => {+ for (const attribute of [value, Promise.resolve(value)]) {+ expect(String(await jsxAttr('title', attribute))).toBe('title="<label>"')+ expect(String(await (<div title={attribute as never} />).toString())).toBe(+ '<div title="<label>"></div>'+ )+ }+ }+ )+ })+ it('Should drop style values containing ";" in jsxAttr() to prevent CSS injection', () => { expect( String(jsxAttr('style', { color: 'red;background:blue', backgroundColor: 'white' }))src/jsx/base.ts+92 −40
@@ -1,7 +1,12 @@ import { raw } from '../helper/html' import { escapeToBuffer, resolveCallbackSync, stringBufferToString } from '../utils/html'-import type { HtmlEscaped, HtmlEscapedString, StringBufferWithCallbacks } from '../utils/html'-import { DOM_RENDERER, DOM_MEMO } from './constants'+import type {+ HtmlEscaped,+ HtmlEscapedString,+ StringBuffer,+ StringBufferWithCallbacks,+} from '../utils/html'+import { DOM_RENDERER, DOM_MEMO, RENDERED_JSX } from './constants' import { captureRenderContext, createContext,@@ -82,7 +87,7 @@ const emptyTags = [ 'track', 'wbr', ]-export const booleanAttributes = [+export const booleanAttributes = new Set([ 'allowfullscreen', 'async', 'autofocus',@@ -109,7 +114,10 @@ export const booleanAttributes = [ 'required', 'reversed', 'selected',-]+ 'shadowrootclonable',+ 'shadowrootdelegatesfocus',+ 'shadowrootserializable',+]) type SuspendedContext = <T>(callback: () => T) => T @@ -136,6 +144,78 @@ const resolveFunctionComponentResult = ( return suspendedContext ? suspendedContext(render) : runWithRenderContext(render) }) +// Rendered JSX is escaped for use as child content, but still contains markup.+export const markRenderedJSX = (value: HtmlEscapedString): HtmlEscapedString => {+ ;(value as unknown as Record<symbol, boolean>)[RENDERED_JSX] = true+ return value+}++const isEscapedAttribute = (value: unknown): value is HtmlEscapedString =>+ value instanceof String && (value as unknown as HtmlEscaped).isEscaped && !(RENDERED_JSX in value)++const objectToAttributeString = (v: object): string | Promise<string> => {+ const s = v.toString() as string | Promise<string>+ return s instanceof Promise ? s.then(String) : String(s)+}++export const attributeToBuffer = (+ buffer: StringBuffer,+ prefix: string,+ key: string,+ v: unknown,+ tag?: string+): void => {+ if (v === null || v === undefined) {+ return+ }+ if (typeof v === 'boolean' && booleanAttributes.has(key)) {+ if (v) {+ buffer[0] += `${prefix}${key}=""`+ }+ return+ }+ if (typeof v === 'function') {+ if (!key.startsWith('on') && key !== 'ref') {+ throw new Error(+ `Invalid prop '${key}' of type 'function' supplied to ${tag ? `'${tag}'` : 'a JSX element'}.`+ )+ }+ // maybe event handler for client components, just ignore in server components+ return+ }++ buffer[0] += `${prefix}${key}="`+ if (key === 'style' && typeof v === 'object') {+ // object to style strings+ let styleStr = ''+ styleObjectForEach(v as Record<string, unknown>, (property, value) => {+ if (value != null) {+ styleStr += `${styleStr ? ';' : ''}${property}:${value}`+ }+ })+ escapeToBuffer(styleStr, buffer)+ } else if (typeof v === 'string') {+ escapeToBuffer(v, buffer)+ } else if (typeof v === 'number' || isEscapedAttribute(v)) {+ buffer[0] += `${v}`+ } else {+ const s =+ v instanceof Promise+ ? v.then((r) =>+ typeof r === 'object' && r !== null && !isEscapedAttribute(r)+ ? objectToAttributeString(r)+ : r+ )+ : objectToAttributeString(v as object)+ if (s instanceof Promise) {+ buffer.unshift('"', s)+ return+ }+ escapeToBuffer(s, buffer)+ }+ buffer[0] += '"'+}+ const childrenToStringToBuffer = (children: Child[], buffer: StringBufferWithCallbacks): void => { for (let i = 0, len = children.length; i < len; i++) { const child = children[i]@@ -232,7 +312,7 @@ export class JSXNode implements HtmlEscaped { ? 'callbacks' in buffer ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString() : buffer[0]- : stringBufferToString(buffer, buffer.callbacks)+ : stringBufferToString(buffer, buffer.callbacks).then(markRenderedJSX) } return runWithRenderContext(render) }@@ -255,47 +335,19 @@ export class JSXNode implements HtmlEscaped { } if (key === 'children') { // skip children- } else if (key === 'style' && typeof v === 'object') {- // object to style strings- let styleStr = ''- styleObjectForEach(v, (property, value) => {- if (value != null) {- styleStr += `${styleStr ? ';' : ''}${property}:${value}`- }- })- buffer[0] += ' style="'- escapeToBuffer(styleStr, buffer)- buffer[0] += '"'- } else if (typeof v === 'string') {- buffer[0] += ` ${key}="`- escapeToBuffer(v, buffer)- buffer[0] += '"'- } else if (v === null || v === undefined) {- // Do nothing- } else if (typeof v === 'number' || (v as HtmlEscaped).isEscaped) {- buffer[0] += ` ${key}="${v}"`- } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {- if (v) {- buffer[0] += ` ${key}=""`- }- } else if (key === 'dangerouslySetInnerHTML') {+ } else if (+ key === 'dangerouslySetInnerHTML' &&+ typeof v === 'object' &&+ v !== null &&+ '__html' in v+ ) { if (children.length > 0) { throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.') } children = [raw(v.__html)]- } else if (v instanceof Promise) {- buffer[0] += ` ${key}="`- buffer.unshift('"', v)- } else if (typeof v === 'function') {- if (!key.startsWith('on') && key !== 'ref') {- throw new Error(`Invalid prop '${key}' of type 'function' supplied to '${tag}'.`)- }- // maybe event handler for client components, just ignore in server components } else {- buffer[0] += ` ${key}="`- escapeToBuffer(v.toString(), buffer)- buffer[0] += '"'+ attributeToBuffer(buffer, ' ', key, v, tag) } } src/jsx/base.test.tsx+56 −0
@@ -77,3 +77,59 @@ describe('createElement', () => { expect((<div>{object as never}</div>).toString()).toBe('<div></div>') }) })++describe('attribute value escaping', () => {+ it('should escape a JSX node used as an attribute value', () => {+ const element = <div title={(<img src='y' onerror='alert(1)' />) as never}>x</div>+ expect(element.toString()).toBe(+ '<div title="<img src="y" onerror="alert(1)"/>">x</div>'+ )+ })++ it('should escape a JSX node resolved from a promise attribute', async () => {+ const element = (+ <div title={Promise.resolve(<img src='y' onerror='alert(1)' />) as never}>x</div>+ )+ expect(String(await element.toString())).toBe(+ '<div title="<img src="y" onerror="alert(1)"/>">x</div>'+ )+ })++ it('should escape an async component node used as an attribute value', async () => {+ const Async = async () => <img src='y' onerror='alert(1)' />+ const element = <div title={(<Async />) as never}>x</div>+ expect(String(await element.toString())).toBe(+ '<div title="<img src="y" onerror="alert(1)"/>">x</div>'+ )+ })++ it('should escape an async render result used as an attribute value', async () => {+ const Async = async () => <img src='y' onerror='alert(1)' />+ const rendered = await (<Async />).toString()+ expect((<div title={rendered}>x</div>).toString()).toBe(+ '<div title="<img src="y" onerror="alert(1)"/>">x</div>'+ )+ expect((<div>{rendered}</div>).toString()).toBe('<div><img src="y" onerror="alert(1)"/></div>')+ })++ it('should escape a plain object resolved from a promise attribute', async () => {+ const element = <div title={Promise.resolve({ toString: () => '<b>x</b>' }) as never}>x</div>+ expect(String(await element.toString())).toBe('<div title="<b>x</b>">x</div>')+ })+})++describe('declarative Shadow DOM boolean attributes', () => {+ it.each(['shadowrootclonable', 'shadowrootdelegatesfocus', 'shadowrootserializable'])(+ 'should render %s only when true',+ (key) => {+ expect((<template {...{ [key]: true }} />).toString()).toBe(`<template ${key}=""></template>`)+ expect((<template {...{ [key]: false }} />).toString()).toBe('<template></template>')+ }+ )+})++describe('style attributes', () => {+ it.each([null, undefined])('should omit a %s style attribute', (style) => {+ expect((<div style={style as never} />).toString()).toBe('<div></div>')+ })+})runtime-tests/deno-jsx/jsx.test.tsx+48 −1
@@ -1,5 +1,5 @@ /** @jsxImportSource ../../src/jsx */-import { assertEquals } from '@std/assert'+import { assertEquals, assertThrows } from '@std/assert' import { Style, css } from '../../src/helper/css/index.ts' import { Suspense, renderToReadableStream } from '../../src/jsx/streaming.ts' import type { HtmlEscapedString } from '../../src/utils/html.ts'@@ -187,3 +187,50 @@ Deno.test('JSX: style', async () => { const html = <div style={{ fontSize: '12px', color: null }}></div> assertEquals(html.toString(), '<div style="font-size:12px"></div>') })++Deno.test('JSX: escape elements used as attribute values', async () => {+ const input = 'x onmouseover=alert(1)//'+ const node = <span data-label={input}>label</span>+ const Async = async () => <span data-label={input}>label</span>+ const values = [+ node,+ Promise.resolve(node),+ <span data-label={Promise.resolve(input) as never}>label</span>,+ <Async />,+ (<Async />).toString(),+ ]+ const expected =+ '<div title="<span data-label="x onmouseover=alert(1)//">label</span>">outer</div>'++ for (const value of values) {+ // A spread makes the precompile transform use JSXNode for the outer element.+ for (const element of [+ <div title={value as never}>outer</div>,+ <div {...{ title: value as never }}>outer</div>,+ ]) {+ assertEquals(String(await (await element).toString()), expected)+ }+ }+})++Deno.test('JSX: reject function values for non-event attributes', () => {+ const handler = () => 'source'+ assertThrows(+ () => (<div data-value={handler}>outer</div>).toString(),+ Error,+ "Invalid prop 'data-value' of type 'function'"+ )+})++Deno.test('JSX: function form actions', () => {+ const action = () => {}+ const html = (+ <form action={action}>+ <button formAction={action}>go</button>+ </form>+ )++ // react-jsx : <form><button>+ // precompile : <form ><button >+ assertEquals(html.toString().replace(/ >/g, '>'), '<form><button>go</button></form>')+})src/jsx/jsx-runtime.ts+18 −26
@@ -7,11 +7,16 @@ export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime' export { jsxDEV as jsxs } from './jsx-dev-runtime' export type { JSX } from './jsx-dev-runtime' import { html, raw } from '../helper/html'-import type { HtmlEscapedString, StringBuffer, HtmlEscaped } from '../utils/html'+import type { HtmlEscapedString, StringBuffer } from '../utils/html' import { escapeToBuffer, stringBufferToString } from '../utils/html'-import { isValidAttributeName, styleObjectForEach } from './utils'+import { attributeToBuffer, markRenderedJSX } from './base'+import { PERMALINK } from './constants'+import { isValidAttributeName } from './utils' -export { html as jsxTemplate }+export const jsxTemplate: typeof html = (strings, ...values) => {+ const result = html(strings, ...values)+ return result instanceof Promise ? result.then(markRenderedJSX) : markRenderedJSX(result)+} export const jsxAttr = ( key: string,@@ -20,31 +25,18 @@ export const jsxAttr = ( if (!isValidAttributeName(key)) { return raw('') }- const buffer: StringBuffer = [`${key}="`] as StringBuffer- if (key === 'style' && typeof v === 'object') {- // object to style strings- let styleStr = ''- styleObjectForEach(v as Record<string, string | number>, (property, value) => {- if (value != null) {- styleStr += `${styleStr ? ';' : ''}${property}:${value}`- }- })- escapeToBuffer(styleStr, buffer)- buffer[0] += '"'- } else if (typeof v === 'string') {+ if (typeof v === 'string') {+ const buffer: StringBuffer = [`${key}="`] escapeToBuffer(v, buffer)- buffer[0] += '"'- } else if (v === null || v === undefined) {- return raw('')- } else if (typeof v === 'number' || (v as unknown as HtmlEscaped).isEscaped) {- buffer[0] += `${v}"`- } else if (v instanceof Promise) {- buffer.unshift('"', v)- } else {- escapeToBuffer(v.toString(), buffer)- buffer[0] += '"'+ return raw(buffer[0] + '"') }-+ let value: unknown = v+ if (typeof value === 'function' && (key === 'action' || key === 'formaction')) {+ // resolved in the same way as the form, input and button intrinsic elements+ value = PERMALINK in value ? value[PERMALINK] : undefined+ }+ const buffer: StringBuffer = ['']+ attributeToBuffer(buffer, '', key, value) return buffer.length === 1 ? raw(buffer[0]) : stringBufferToString(buffer, undefined) } src/jsx/constants.ts+1 −0
@@ -4,3 +4,4 @@ export const DOM_STASH = Symbol('STASH') export const DOM_INTERNAL_TAG = Symbol('INTERNAL') export const DOM_MEMO = Symbol('MEMO') export const PERMALINK = Symbol('PERMALINK')+export const RENDERED_JSX = Symbol('RENDERED_JSX')