Merge commit from fork
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(jsx): close server-side escaping bypasses * fix(jsx): escape array roots in DOM server * fix(jsx): escape untrusted boundary objects * fix(jsx): escape untrusted fallback and provider objects
authored by Taku Amano · committed by GitHub · parent cac0c4d · Browse files · 12 files·+537 added−54 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+537 added−54 removed
- tests:+435 added−0 removed
- other:+102 added−54 removed
Provenance
- Commit
2b8ed40- Tree
8445b68- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
cac0c4d
12 files changed+537 added−54 removed
modified:src/jsx/dom/server.test.tsx+71 added
123456789101113 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061626364656643 unmodified lines11011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915049 unmodified lines/** @jsxImportSource ../ */import { raw } from '../../helper/html'import { renderToReadableStream, renderToString } from './server'
const unsafeHtml = '<img src=x onerror=alert(1)>'const escapedUnsafeHtml = '<img src=x onerror=alert(1)>'
describe('renderToString', () => { it('Should be able to render HTML element', () => { expect(renderToString(<h1>Hello</h1>)).toBe('<h1>Hello</h1>') })13 unmodified lines it('Should be able to render string', () => { expect(renderToString('Hono')).toBe('Hono') })
it('Should escape a string root', () => { expect(renderToString(unsafeHtml)).toBe(escapedUnsafeHtml) })
it('Should preserve an explicitly trusted root', () => { expect(renderToString(raw('<strong>trusted</strong>'))).toBe('<strong>trusted</strong>') })
it('Should escape nested array roots without separators', () => { expect(renderToString([unsafeHtml, [unsafeHtml]])).toBe( `${escapedUnsafeHtml}${escapedUnsafeHtml}` ) })
it('Should preserve trusted content in an array root', () => { expect(renderToString([raw('<strong>trusted</strong>'), unsafeHtml])).toBe( `<strong>trusted</strong>${escapedUnsafeHtml}` ) })
it('Should reject an asynchronous array root', () => { expect(() => renderToString([Promise.resolve(unsafeHtml)])).toThrow( 'Async component is not supported in renderToString' ) })
it('Should keep non-string roots unchanged', () => { const object = { toString: () => 'plain-text' }
expect(renderToString(10n as never)).toBe('10') expect(renderToString(Symbol('value') as never)).toBe('Symbol(value)') expect(renderToString(object as never)).toBe('plain-text') })
it('Should omit options', () => { expect(renderToString('Hono', { identifierPrefix: 'test' })).toBe('Hono') })
43 unmodified lines it('Should be able to render string', async () => { expect(await getStringFromStream(await renderToReadableStream('Hono'))).toBe('Hono') })
it('Should escape a string root', async () => { expect(await getStringFromStream(await renderToReadableStream(unsafeHtml))).toBe( escapedUnsafeHtml ) })
it('Should preserve an explicitly trusted root', async () => { expect( await getStringFromStream(await renderToReadableStream(raw('<strong>trusted</strong>'))) ).toBe('<strong>trusted</strong>') })
it('Should escape synchronous and asynchronous array roots', async () => { expect( await getStringFromStream(await renderToReadableStream([unsafeHtml, [unsafeHtml]])) ).toBe(`${escapedUnsafeHtml}${escapedUnsafeHtml}`) expect( await getStringFromStream(await renderToReadableStream([Promise.resolve(unsafeHtml)])) ).toBe(escapedUnsafeHtml) })
it('Should preserve trusted content in an array root', async () => { expect( await getStringFromStream( await renderToReadableStream([raw('<strong>trusted</strong>'), unsafeHtml]) ) ).toBe(`<strong>trusted</strong>${escapedUnsafeHtml}`) })
it('Should keep non-string roots unchanged', async () => { expect(await getStringFromStream(await renderToReadableStream(10n as never))).toBe('10') })
it('Should be called `onError` if there is an error', async () => { const ErrorComponent = async () => { throw new Error('Server error') }49 unmodified linesmodified:src/jsx/dom/server.ts+7 added-1 removed
2 unmodified lines3 * This module provides APIs for `hono/jsx/server`, which is compatible with `react-dom/server`.4 */5 6 import type { HtmlEscapedString } from '../../utils/html'7+import { renderChildren } from '../base'8 import type { Child } from '../base'9 import { renderToReadableStream as renderToReadableStreamHono } from '../streaming'10 import version from './'11 12 export interface RenderToStringOptions {13 identifierPrefix?: string14 }15 16+const prepareRoot = (element: Child): Child =>17+ typeof element === 'string' || Array.isArray(element) ? renderChildren([element]) : element18+19 /**20 * Render JSX element to string.21 * @param element JSX element to render.22 * @param options Options for rendering.2 unmodified lines25 const renderToString = (element: Child, options: RenderToStringOptions = {}): string => {26 if (Object.keys(options).length > 0) {27 console.warn('options are not supported yet')28 }25- const res = element?.toString() ?? ''29+ element = prepareRoot(element)30+ const res = element instanceof Promise ? element : (element?.toString() ?? '')31 if (typeof res !== 'string') {32 throw new Error('Async component is not supported in renderToString')33 }34 return res24 unmodified lines59 if (Object.keys(options).some((key) => key !== 'onError')) {60 console.warn('options are not supported yet, except onError')61 }62 63+ element = prepareRoot(element)64 if (!element || typeof element !== 'object') {65 element = element?.toString() ?? ''66 }67 9 unmodified linesmodified:src/jsx/intrinsic-element/components.test.tsx+25 added
71 unmodified lines72 const html = await resolveCallback(rendered, HtmlEscapedCallbackPhase.Stringify, false, {})73 expect(html.toString()).toBe('<html><body><title>Hello</title><h1>World</h1></body></html>')74 expect(html.toString()).not.toContain('[object Promise]')75 })76+77+ it('should render a title with itemProp and async children', async () => {78+ const AsyncChild = async () => <>{'price < 100'}</>79+ const template = <title itemProp='name'>{<AsyncChild />}</title>80+81+ expect(String(await template.toString())).toBe(82+ '<title itemprop="name">price < 100</title>'83+ )84+ })85+86+ it('should not interpret replacement patterns in a hoisted title', async () => {87+ const template = (88+ <html>89+ <head></head>90+ <body>91+ <title>{'price $< 100'}</title>92+ </body>93+ </html>94+ )95+ const rendered = await template.toString()96+97+ expect(await resolveCallback(rendered, HtmlEscapedCallbackPhase.Stringify, false, {})).toBe(98+ '<html><head><title>price $< 100</title></head><body></body></html>'99+ )100+ })101 })102 103 describe('link element', () => {104 it('should be hoisted link tag', async () => {562 unmodified linesmodified:src/jsx/intrinsic-element/components.ts+3 added-3 removed
1 import { raw } from '../../helper/html'2 import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'3-import { JSXNode, getNameSpaceContext } from '../base'3+import { JSXNode, getNameSpaceContext, renderChildren } from '../base'4 import type { Child, Props } from '../base'5 import { toArray } from '../children'6 import { PERMALINK } from '../constants'7 import { useContext } from '../context'77 unmodified lines85 86 insertTags.forEach((tag) => {87 buffer[0] = buffer[0].replaceAll(tag, '')88 })89- buffer[0] = buffer[0].replace(/(?=<\/head>)/, insertTags.join(''))89+ buffer[0] = buffer[0].replace(/(?=<\/head>)/, () => insertTags.join(''))90 }91 }92 93 const returnWithoutSpecialBehavior = (tag: string, children: Child, props: Props) =>94- raw(new JSXNode(tag, props, toArray(children ?? [])).toString())94+ renderChildren([new JSXNode(tag, props, toArray(children ?? []))])95 96 const documentMetadataTag = (tag: string, children: Child, props: Props, sort: boolean) => {97 if ('itemProp' in props) {98 return returnWithoutSpecialBehavior(tag, children, props)112 unmodified linesmodified:src/jsx/base.test.tsx+21 added
1 /** @jsxImportSource ./ */2 3+import type { HtmlEscapedString } from '../utils/html'4 import type { Child, JSXNode } from './base'5 // eslint-disable-next-line @typescript-eslint/no-unused-vars6 import { cloneElement, jsx, Fragment } from './base'7 41 unmodified lines49 const child: Child = <span>inner</span>50 const element = jsx('div', null, child) as unknown as JSXNode51 expect(element.toString()).toBe('<div><span>inner</span></div>')52 })53+54+ it('should escape a string returned by an asynchronous component', async () => {55+ const Async = async () => '<img src=x onerror=alert(1)>' as unknown as HtmlEscapedString56+57+ expect(58+ String(59+ await (60+ <div>61+ <Async />62+ </div>63+ ).toString()64+ )65+ ).toBe('<div><img src=x onerror=alert(1)></div>')66+ })67+68+ it('should omit an unsupported object child', () => {69+ const object = { toString: () => 'plain-text' }70+71+ expect((<div>{object as never}</div>).toString()).toBe('<div></div>')72+ })73 })modified:src/jsx/base.ts+33 added-2 removed
116 unmodified lines117 result: Promise<string | JSXNode | Child[]>,118 suspendedContext?: SuspendedContext119 ): Promise<string> =>120 result.then((resolved) => {121- if (!Array.isArray(resolved) && !(resolved instanceof JSXNode)) {121+ if (122+ typeof resolved !== 'string' &&123+ !Array.isArray(resolved) &&124+ !(resolved instanceof JSXNode)125+ ) {126 return resolved127 }124- const children = Array.isArray(resolved) ? resolved : [resolved]128+ const children = Array.isArray(resolved) ? resolved : [resolved as Child]129 const render = () => {130 const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks131 childrenToStringToBuffer(children, buffer)132 return buffer.length === 138 unmodified lines171 | null172 | undefined173 | boolean174 | Child[]175+176+export const renderChildren = (children: Child[]): HtmlEscapedString | Promise<HtmlEscapedString> =>177+ runWithRenderContext(() => {178+ const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks179+ childrenToStringToBuffer(children, buffer)180+ return buffer.length === 1181+ ? raw(buffer[0], buffer.callbacks)182+ : stringBufferToString(buffer, buffer.callbacks)183+ })184+185+export const isUntrustedObject = (value: unknown): boolean =>186+ typeof value === 'object' &&187+ value !== null &&188+ !Array.isArray(value) &&189+ !(value instanceof JSXNode) &&190+ !(value instanceof Promise) &&191+ !(value as HtmlEscaped).isEscaped &&192+ typeof (value as { toString?: unknown }).toString === 'function'193+194+export const renderUntrustedObject = (195+ value: unknown196+): HtmlEscapedString | Promise<HtmlEscapedString> => {197+ const stringified = (value as { toString(): unknown }).toString()198+ const escape = (result: unknown) => renderChildren([String(result)])199+ return stringified instanceof Promise ? stringified.then(escape) : escape(stringified)200+}201+202 export class JSXNode implements HtmlEscaped {203 tag: string | Function204 props: Props205 key?: string285 unmodified linesmodified:src/jsx/components.test.tsx+135 added
5 unmodified lines6 import { HtmlEscapedCallbackPhase, resolveCallback as rawResolveCallback } from '../utils/html'7 import { ErrorBoundary } from './components'8 import { Suspense, renderToReadableStream, StreamingContext } from './streaming'9 10+const unsafeHtml = '<img src=x onerror=alert(1)>'11+const escapedUnsafeHtml = '<img src=x onerror=alert(1)>'12+13 function resolveCallback(template: string | HtmlEscapedString) {14 return rawResolveCallback(template, HtmlEscapedCallbackPhase.Stream, false, {})15 }16 2 unmodified lines19 document.querySelectorAll('template, script').forEach((e) => e.remove())20 return document.body.innerHTML21 }22 23+async function stringify(node: { toString(): string | Promise<string> }): Promise<string> {24+ return String(25+ await rawResolveCallback(await node.toString(), HtmlEscapedCallbackPhase.Stringify, false, {})26+ )27+}28+29+async function drainStream(stream: ReadableStream<Uint8Array>): Promise<string> {30+ const decoder = new TextDecoder()31+ let result = ''32+ for await (const chunk of stream) {33+ result += decoder.decode(chunk)34+ }35+ return result36+}37+38 const Fallback = () => <div>Out Of Service</div>39 40 describe('ErrorBoundary', () => {41 let errorBoundaryCounter = 0773 unmodified lines815 816 suspenseCounter--817 })818 })819+820+ describe('escaping', () => {821+ const Broken = () => {822+ throw new Error('boom')823+ }824+825+ it('escapes strings when an asynchronous sibling is present', async () => {826+ const Async = async () => <span>done</span>827+ const node = (828+ <ErrorBoundary fallback='error'>829+ {unsafeHtml}830+ <Async />831+ </ErrorBoundary>832+ )833+834+ expect(await stringify(node)).toBe(`${escapedUnsafeHtml}<span>done</span>`)835+ const streamed = await drainStream(renderToReadableStream(node))836+ expect(streamed).toContain(escapedUnsafeHtml)837+ expect(streamed).not.toContain(unsafeHtml)838+ })839+840+ it('escapes untrusted object fallbacks', async () => {841+ const object = { toString: () => unsafeHtml }842+ const asyncObject = { toString: async () => unsafeHtml }843+ const rawObject = { toString: () => raw(unsafeHtml) }844+845+ for (const fallback of [object, asyncObject, rawObject]) {846+ expect(847+ await stringify(848+ <ErrorBoundary fallback={fallback as never}>849+ <Broken />850+ </ErrorBoundary>851+ )852+ ).toBe(escapedUnsafeHtml)853+ }854+ })855+856+ it('preserves an explicitly trusted fallback', async () => {857+ expect(858+ await stringify(859+ <ErrorBoundary fallback={raw('<strong>trusted</strong>')}>860+ <Broken />861+ </ErrorBoundary>862+ )863+ ).toBe('<strong>trusted</strong>')864+ })865+866+ it('does not interpret replacement patterns in content', async () => {867+ const content = "literal $& $` $'"868+ const Async = async () => <span>done</span>869+870+ expect(871+ await stringify(872+ <ErrorBoundary fallback='error'>873+ {content}874+ <Async />875+ </ErrorBoundary>876+ )877+ ).toBe('literal $& $` $'<span>done</span>')878+ })879+880+ it('escapes untrusted object children', async () => {881+ const object = { toString: () => unsafeHtml }882+ const asyncObject = { toString: async () => unsafeHtml }883+ const rawObject = { toString: () => raw(unsafeHtml) }884+885+ for (const child of [object, asyncObject, rawObject]) {886+ const node = <ErrorBoundary fallback='error'>{child as never}</ErrorBoundary>887+ expect(await stringify(node)).toBe(escapedUnsafeHtml)888+ const streamed = await drainStream(renderToReadableStream(node))889+ expect(streamed).toContain(escapedUnsafeHtml)890+ expect(streamed).not.toContain(unsafeHtml)891+ }892+ })893+894+ it('preserves explicitly trusted children', async () => {895+ expect(896+ await stringify(897+ <ErrorBoundary fallback='error'>{raw('<strong>trusted</strong>')}</ErrorBoundary>898+ )899+ ).toBe('<strong>trusted</strong>')900+ })901+902+ it('keeps benign object stringification visible', async () => {903+ expect(await stringify(<ErrorBoundary fallback='error'>{{} as never}</ErrorBoundary>)).toBe(904+ '[object Object]'905+ )906+ })907+908+ it('escapes nested fallback arrays', async () => {909+ expect(910+ await stringify(911+ <ErrorBoundary fallback={[[unsafeHtml]]}>912+ <Broken />913+ </ErrorBoundary>914+ )915+ ).toBe(escapedUnsafeHtml)916+ })917+918+ it('keeps the existing falsy fallbackRender behavior', async () => {919+ expect(920+ await stringify(921+ <ErrorBoundary fallbackRender={() => 0}>922+ <Broken />923+ </ErrorBoundary>924+ )925+ ).toBe('')926+ })927+928+ it('keeps a direct Promise child unchanged', async () => {929+ expect(930+ await stringify(931+ <ErrorBoundary fallback='error'>{Promise.resolve('resolved')}</ErrorBoundary>932+ )933+ ).toBe('[object Promise]')934+ })935+ })936 })modified:src/jsx/components.ts+27 added-32 removed
1 import { raw } from '../helper/html'2 import type { HtmlEscapedCallback, HtmlEscapedString } from '../utils/html'3 import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'4-import { jsx, Fragment } from './base'4+import { jsx, Fragment, isUntrustedObject, renderChildren, renderUntrustedObject } from './base'5 import { DOM_RENDERER } from './constants'6 import { captureRenderContext, useContext } from './context'7 import { ErrorBoundary as ErrorBoundaryDomRenderer } from './dom/components'8 import type { HasRenderToDom } from './dom/render'3 unmodified lines12 let errorBoundaryCounter = 013 14 export const childrenToString = async (children: Child[]): Promise<HtmlEscapedString[]> => {15 try {16- return children17- .flat()18- .map((c) => (c == null || typeof c === 'boolean' ? '' : c.toString())) as HtmlEscapedString[]16+ return children.flat().map(resolveChildEarly) as HtmlEscapedString[]17 } catch (e) {18 if (e instanceof Promise) {19 // Capture before `await`: on the fallback path the render context is20 // only observable during this synchronous window.5 unmodified lines26 }27 }28 }29 32-const resolveChildEarly = (c: Child): HtmlEscapedString | Promise<HtmlEscapedString> => {33- if (c == null || typeof c === 'boolean') {30+const resolveChildEarly = (child: Child): HtmlEscapedString | Promise<HtmlEscapedString> => {31+ if (child == null || typeof child === 'boolean') {32 return '' as HtmlEscapedString35- } else if (typeof c === 'string') {36- return c as HtmlEscapedString33+ } else if (typeof child === 'string' || Array.isArray(child)) {34+ return renderChildren([child])35+ } else if (isUntrustedObject(child)) {36+ return renderUntrustedObject(child)37 } else {38- const str = c.toString()39- if (!(str instanceof Promise)) {40- return raw(str)41- } else {42- return str as Promise<HtmlEscapedString>43- }38+ const str = child.toString()39+ return str instanceof Promise ? (str as Promise<HtmlEscapedString>) : raw(str)40 }41 }42 43 export type ErrorHandler = (error: Error) => void27 unmodified lines71 let fallbackStrPromise: Promise<HtmlEscapedString | string | undefined> | undefined72 const resolveFallbackStr = (): Promise<HtmlEscapedString | string | undefined> =>73 (fallbackStrPromise ||= (async () => {74 const awaitedFallback = await fallback79- if (typeof awaitedFallback === 'string') {80- return awaitedFallback81- } else {82- const fallbackResult = await getResume()(() => awaitedFallback?.toString())83- if (typeof fallbackResult === 'string') {84- // Don't apply `raw` to undefined/null/boolean. Preserve callbacks from85- // the stringified result, or the original thenable for plain strings.86- return raw(87- fallbackResult,88- (fallbackResult as HtmlEscapedString).callbacks ||89- (awaitedFallback as unknown as HtmlEscapedString)?.callbacks90- )91- }75+ if (awaitedFallback === null || awaitedFallback === undefined) {76+ return77 }78+ if (typeof awaitedFallback === 'string' || Array.isArray(awaitedFallback)) {79+ return getResume()(() => renderChildren([awaitedFallback]))80+ }81+ if (isUntrustedObject(awaitedFallback)) {82+ return getResume()(() => renderUntrustedObject(awaitedFallback))83+ }84+ const fallbackResult = await getResume()(() => awaitedFallback.toString())85+ return raw(86+ fallbackResult,87+ (fallbackResult as HtmlEscapedString).callbacks ||88+ (awaitedFallback as unknown as HtmlEscapedString).callbacks89+ )90 })())91 const renderFallback = async (error: Error): Promise<HtmlEscapedString> => {92 const fallbackStr = await resolveFallbackStr()93 return getResume()(async () => {2 unmodified lines96 fallbackStr !== undefined97 ? fallbackStr98 : (fallbackRender && jsx(Fragment, {}, fallbackRender(error) as HtmlEscapedString)) || ''99 ) as HtmlEscapedString103- const fallbackResString = await Fragment({104- children: fallbackRes,105- }).toString()100+ const fallbackResString = await Fragment({ children: fallbackRes }).toString()101 return raw(102 fallbackResString,103 (fallbackResString as HtmlEscapedString).callbacks || fallbackRes.callbacks104 )31 unmodified lines136 137 const fallbackResString = await renderFallback(error)138 const fallbackCallbacks = fallbackResString.callbacks139 if (buffer) {145- buffer[0] = buffer[0].replace(replaceRe, fallbackResString)140+ buffer[0] = buffer[0].replace(replaceRe, () => fallbackResString)141 return fallbackCallbacks?.length ? raw('', fallbackCallbacks) : ''142 }143 return raw(144 `<template data-hono-target="E:${index}">${fallbackResString}</template><script>37 unmodified lines182 </script>`183 184 if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {185 if (buffer) {191- buffer[0] = buffer[0].replace(replaceRe, content)186+ buffer[0] = buffer[0].replace(replaceRe, () => content)187 }188 return html189 }190 67 unmodified linesmodified:src/jsx/context.ts+15 added-10 removed
1 import { raw } from '../helper/html'2 import type { HtmlEscapedString } from '../utils/html'3-import { JSXFragmentNode } from './base'3+import { isUntrustedObject, JSXFragmentNode, renderChildren, renderUntrustedObject } from './base'4 import { DOM_RENDERER } from './constants'5 import { createContextProviderFunction } from './dom/context'6 import type { FC, PropsWithChildren } from './'7 208 unmodified lines216 // Resolve the target array once, synchronously: the pop in `.finally()`217 // below may run later and must operate on the same array as the push.218 const contextValues = getContextValuesIn(getCurrentStore(), context)219 contextValues.push(props.value)220- let string220+ let rendered221 try {222- string = props.children223- ? (Array.isArray(props.children)224- ? new JSXFragmentNode('', {}, props.children)222+ rendered =223+ typeof props.children === 'string'224+ ? renderChildren([props.children])225+ : isUntrustedObject(props.children)226+ ? renderUntrustedObject(props.children)227 : props.children228+ ? (Array.isArray(props.children)229+ ? new JSXFragmentNode('', {}, props.children)230+ : props.children226- ).toString()227- : ''231+ ).toString()232+ : raw('')233 } catch (e) {234 contextValues.pop()235 throw e236 }237 233- if (string instanceof Promise) {234- return string238+ if (rendered instanceof Promise) {239+ return rendered240 .finally(() => contextValues.pop())241 .then((resString) => raw(resString, (resString as HtmlEscapedString).callbacks))242 } else {243 contextValues.pop()239- return raw(string)244+ return raw(rendered)245 }246 }) as Context<T>247 context.values = values248 context.Provider = context18 unmodified linesmodified:src/jsx/index.test.tsx+59 added
1177 unmodified lines1178 )1179 expect(template.toString()).toBe('<div><span>dark</span>!</div><div><span>dark</span>!</div>')1180 })1181 1182+ it('escapes a single string child', async () => {1183+ const template = (1184+ <ThemeContext.Provider value='dark'>{'<img src=x onerror=alert(1)>'}</ThemeContext.Provider>1185+ )1186+1187+ expect(String(await template.toString())).toBe('<img src=x onerror=alert(1)>')1188+ })1189+1190+ it('escapes a string returned by an asynchronous child', async () => {1191+ const Async = async () => '<img src=x onerror=alert(1)>' as any1192+ const template = (1193+ <ThemeContext.Provider value='dark'>1194+ <Async />1195+ </ThemeContext.Provider>1196+ )1197+1198+ expect(String(await template.toString())).toBe('<img src=x onerror=alert(1)>')1199+ })1200+1201+ it('preserves explicitly trusted content', async () => {1202+ const template = (1203+ <ThemeContext.Provider value='dark'>1204+ {raw('<strong>trusted</strong>')}1205+ </ThemeContext.Provider>1206+ )1207+1208+ expect(await template.toString()).toBe('<strong>trusted</strong>')1209+ })1210+1211+ it('escapes untrusted object stringification', async () => {1212+ const object = { toString: () => '<img src=x onerror=alert(1)>' }1213+ const asyncObject = { toString: async () => '<img src=x onerror=alert(1)>' }1214+ const rawObject = { toString: () => raw('<img src=x onerror=alert(1)>') }1215+1216+ for (const child of [object, asyncObject, rawObject]) {1217+ const template = (1218+ <ThemeContext.Provider value='dark'>{child as never}</ThemeContext.Provider>1219+ )1220+ expect(String(await template.toString())).toBe('<img src=x onerror=alert(1)>')1221+ }1222+ })1223+1224+ it('continues to omit unsupported objects in child arrays', async () => {1225+ const object = { toString: () => '<img src=x onerror=alert(1)>' }1226+ const template = (1227+ <ThemeContext.Provider value='dark'>{[object as never, 'safe']}</ThemeContext.Provider>1228+ )1229+1230+ expect(await template.toString()).toBe('safe')1231+ })1232+1233+ it('keeps a direct Promise child unchanged', async () => {1234+ const template = (1235+ <ThemeContext.Provider value='dark'>{Promise.resolve('resolved')}</ThemeContext.Provider>1236+ )1237+1238+ expect(await template.toString()).toBe('[object Promise]')1239+ })1240+1241 it('nested', () => {1242 const template = (1243 <ThemeContext.Provider value='dark'>1244 <Consumer />501 unmodified linesmodified:src/jsx/streaming.test.tsx+124 added
7 unmodified lines8 import { buildDataStack } from './dom/render'9 import { use } from './hooks'10 import { Suspense, renderToReadableStream, StreamingContext } from './streaming'11 12+const unsafeHtml = '<img src=x onerror=alert(1)>'13+const escapedUnsafeHtml = '<img src=x onerror=alert(1)>'14+15 function replacementResult(html: string) {16 const document = new JSDOM(html, { runScripts: 'dangerously' }).window.document17 document.querySelectorAll('template, script').forEach((e) => e.remove())18 return document.body.innerHTML7 unmodified lines26 }27 return html28 }29 30+async function stringify(node: { toString(): string | Promise<string> }): Promise<string> {31+ return String(32+ await resolveCallback(await node.toString(), HtmlEscapedCallbackPhase.Stringify, false, {})33+ )34+}35+36+async function readInitialSuspenseChunk(fallback: unknown): Promise<string> {37+ let resolve!: () => void38+ const promise = new Promise<void>((done) => (resolve = done))39+ const Async = async () => {40+ await promise41+ return <span>done</span>42+ }43+ const reader = renderToReadableStream(44+ <Suspense fallback={fallback}>45+ <Async />46+ </Suspense>47+ ).getReader()48+49+ const first = await reader.read()50+ resolve()51+ while (!(await reader.read()).done) {52+ // Drain the retry so it cannot outlive the test.53+ }54+ return new TextDecoder().decode(first.value)55+}56+57 describe('Streaming', () => {58 let suspenseCounter = 059 afterEach(() => {60 suspenseCounter++1122 unmodified lines1183 expect(adminHtml).not.toContain('role:guest')1184 expect(guestHtml).toContain('role:guest')1185 expect(guestHtml).not.toContain('role:admin')1186 })1187+1188+ describe('escaping', () => {1189+ it('escapes string children with an asynchronous sibling', async () => {1190+ const Async = async () => <span>done</span>1191+ const node = (1192+ <Suspense fallback='loading'>1193+ {unsafeHtml}1194+ <Async />1195+ </Suspense>1196+ )1197+1198+ expect(await stringify(node)).toBe(`${escapedUnsafeHtml}<span>done</span>`)1199+ const streamed = await drainStream(renderToReadableStream(node))1200+ expect(streamed).toContain(escapedUnsafeHtml)1201+ expect(streamed).not.toContain(unsafeHtml)1202+ })1203+1204+ it('escapes nested array strings', async () => {1205+ expect(await stringify(<Suspense fallback='loading'>{[[[unsafeHtml]]]}</Suspense>)).toBe(1206+ escapedUnsafeHtml1207+ )1208+ })1209+1210+ it('escapes a primitive fallback in the initial stream chunk', async () => {1211+ const initialChunk = await readInitialSuspenseChunk(unsafeHtml)1212+1213+ expect(initialChunk).toContain(escapedUnsafeHtml)1214+ expect(initialChunk).not.toContain(unsafeHtml)1215+ })1216+1217+ it('escapes untrusted object fallbacks', async () => {1218+ const object = { toString: () => unsafeHtml }1219+ const asyncObject = { toString: async () => unsafeHtml }1220+ const rawObject = { toString: () => raw(unsafeHtml) }1221+1222+ for (const fallback of [object, asyncObject, rawObject]) {1223+ const initialChunk = await readInitialSuspenseChunk(fallback)1224+ expect(initialChunk).toContain(escapedUnsafeHtml)1225+ expect(initialChunk).not.toContain(unsafeHtml)1226+ }1227+ })1228+1229+ it('preserves an explicitly trusted fallback', async () => {1230+ expect(await readInitialSuspenseChunk(raw('<strong>trusted</strong>'))).toContain(1231+ '<strong>trusted</strong>'1232+ )1233+ })1234+1235+ it('does not interpret replacement patterns in content', async () => {1236+ const content = "literal $& $` $'"1237+ const Async = async () => <span>done</span>1238+1239+ expect(1240+ await stringify(1241+ <Suspense fallback='loading'>1242+ {content}1243+ <Async />1244+ </Suspense>1245+ )1246+ ).toBe('literal $& $` $'<span>done</span>')1247+ })1248+1249+ it('escapes untrusted object children', async () => {1250+ const object = { toString: () => unsafeHtml }1251+ const asyncObject = { toString: async () => unsafeHtml }1252+ const rawObject = { toString: () => raw(unsafeHtml) }1253+1254+ for (const child of [object, asyncObject, rawObject]) {1255+ const node = <Suspense fallback='loading'>{child as never}</Suspense>1256+ expect(await stringify(node)).toBe(escapedUnsafeHtml)1257+ const streamed = await drainStream(renderToReadableStream(node))1258+ expect(streamed).toContain(escapedUnsafeHtml)1259+ expect(streamed).not.toContain(unsafeHtml)1260+ }1261+ })1262+1263+ it('preserves explicitly trusted children', async () => {1264+ expect(1265+ await stringify(<Suspense fallback='loading'>{raw('<strong>trusted</strong>')}</Suspense>)1266+ ).toBe('<strong>trusted</strong>')1267+ })1268+1269+ it('keeps benign object stringification visible', async () => {1270+ expect(await stringify(<Suspense fallback='loading'>{{} as never}</Suspense>)).toBe(1271+ '[object Object]'1272+ )1273+ })1274+1275+ it('keeps a direct Promise child unchanged', async () => {1276+ expect(1277+ await stringify(<Suspense fallback='loading'>{Promise.resolve('resolved')}</Suspense>)1278+ ).toBe('[object Promise]')1279+ })1280+ })1281 })modified:src/jsx/streaming.ts+17 added-6 removed
4 unmodified lines5 6 import { raw } from '../helper/html'7 import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'8 import type { HtmlEscapedString } from '../utils/html'9-import { JSXNode } from './base'9+import { isUntrustedObject, JSXNode, renderChildren, renderUntrustedObject } from './base'10 import { childrenToString } from './components'11 import { DOM_RENDERER, DOM_STASH } from './constants'12 import { captureRenderContext, createContext, useContext } from './context'13 import { Suspense as SuspenseDomRenderer } from './dom/components'18 unmodified lines32 } | null>(null)33 34 let suspenseCounter = 035 36+const serializeBoundaryChild = (child: Child): string | Promise<string> =>37+ typeof child === 'string' || Array.isArray(child)38+ ? renderChildren([child])39+ : child == null || typeof child === 'boolean'40+ ? ''41+ : isUntrustedObject(child)42+ ? renderUntrustedObject(child)43+ : child.toString()44+45 /**46 * @experimental47 * `Suspense` is an experimental feature.48 * The API might be changed.19 unmodified lines68 69 try {70 stackNode[DOM_STASH][0] = 071 buildDataStack.push([[], stackNode])63- resArray = children.map((c) =>64- c == null || typeof c === 'boolean' ? '' : c.toString()65- ) as HtmlEscapedString[]72+ resArray = children.map(serializeBoundaryChild) as HtmlEscapedString[]73 } catch (e) {74 if (e instanceof Promise) {75 // Capture before deferring: on the fallback path the render context is76 // observable here but not in the `.then()` below.15 unmodified lines92 }93 94 if (resArray.some((res) => (res as {}) instanceof Promise)) {95 const index = suspenseCounter++89- const fallbackStr = await fallback.toString()96+ const fallbackStr = await (typeof fallback === 'string' || Array.isArray(fallback)97+ ? renderChildren([fallback])98+ : isUntrustedObject(fallback)99+ ? renderUntrustedObject(fallback)100+ : fallback.toString())101 return raw(`<template id="H:${index}"></template>${fallbackStr}<!--/$-->`, [102 ...(fallbackStr.callbacks || []),103 ({ phase, buffer, context }) => {104 if (phase === HtmlEscapedCallbackPhase.BeforeStream) {4 unmodified lines109 const content = htmlArray.join('')110 if (buffer) {111 buffer[0] = buffer[0].replace(112 new RegExp(`<template id="H:${index}"></template>.*?<!--/\\$-->`),102- content113+ () => content114 )115 }116 let html = buffer117 ? ''114 unmodified lines