Skip to content
Myr

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

12 files+537 added−54 removed

modified:src/jsx/dom/server.test.tsx+71 added
modified:src/jsx/dom/server.ts+7 added-1 removed
2 unmodified lines
3 * This module provides APIs for `hono/jsx/server`, which is compatible with `react-dom/server`.4 */56import type { HtmlEscapedString } from '../../utils/html'7import { renderChildren } from '../base'8import type { Child } from '../base'9import { renderToReadableStream as renderToReadableStreamHono } from '../streaming'10import version from './'1112export interface RenderToStringOptions {13 identifierPrefix?: string14}1516const prepareRoot = (element: Child): Child =>17 typeof element === 'string' || Array.isArray(element) ? renderChildren([element]) : element1819/**20 * Render JSX element to string.21 * @param element JSX element to render.22 * @param options Options for rendering.
2 unmodified lines
25const 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 res
24 unmodified lines
59 if (Object.keys(options).some((key) => key !== 'onError')) {60 console.warn('options are not supported yet, except onError')61 }6263 element = prepareRoot(element)64 if (!element || typeof element !== 'object') {65 element = element?.toString() ?? ''66 }67
9 unmodified lines
modified:src/jsx/intrinsic-element/components.test.tsx+25 added
71 unmodified lines
72 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 })7677 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>8081 expect(String(await template.toString())).toBe(82 '<title itemprop="name">price &lt; 100</title>'83 )84 })8586 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()9697 expect(await resolveCallback(rendered, HtmlEscapedCallbackPhase.Stringify, false, {})).toBe(98 '<html><head><title>price $&lt; 100</title></head><body></body></html>'99 )100 })101 })102103 describe('link element', () => {104 it('should be hoisted link tag', async () => {
562 unmodified lines
modified:src/jsx/intrinsic-element/components.ts+3 added-3 removed
1import { raw } from '../../helper/html'2import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'3import { JSXNode, getNameSpaceContext } from '../base'3import { JSXNode, getNameSpaceContext, renderChildren } from '../base'4import type { Child, Props } from '../base'5import { toArray } from '../children'6import { PERMALINK } from '../constants'7import { useContext } from '../context'
77 unmodified lines
8586 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 }9293const returnWithoutSpecialBehavior = (tag: string, children: Child, props: Props) =>94 raw(new JSXNode(tag, props, toArray(children ?? [])).toString())94 renderChildren([new JSXNode(tag, props, toArray(children ?? []))])9596const documentMetadataTag = (tag: string, children: Child, props: Props, sort: boolean) => {97 if ('itemProp' in props) {98 return returnWithoutSpecialBehavior(tag, children, props)
112 unmodified lines
modified:src/jsx/base.test.tsx+21 added
1/** @jsxImportSource ./ */23import type { HtmlEscapedString } from '../utils/html'4import type { Child, JSXNode } from './base'5// eslint-disable-next-line @typescript-eslint/no-unused-vars6import { cloneElement, jsx, Fragment } from './base'7
41 unmodified lines
49 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 })5354 it('should escape a string returned by an asynchronous component', async () => {55 const Async = async () => '<img src=x onerror=alert(1)>' as unknown as HtmlEscapedString5657 expect(58 String(59 await (60 <div>61 <Async />62 </div>63 ).toString()64 )65 ).toBe('<div>&lt;img src=x onerror=alert(1)&gt;</div>')66 })6768 it('should omit an unsupported object child', () => {69 const object = { toString: () => 'plain-text' }7071 expect((<div>{object as never}</div>).toString()).toBe('<div></div>')72 })73})
modified:src/jsx/base.ts+33 added-2 removed
116 unmodified lines
117 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 === 1
38 unmodified lines
171 | null172 | undefined173 | boolean174 | Child[]175176export 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 })184185export 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'193194export 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}201202export class JSXNode implements HtmlEscaped {203 tag: string | Function204 props: Props205 key?: string
285 unmodified lines
modified:src/jsx/components.test.tsx+135 added
5 unmodified lines
6import { HtmlEscapedCallbackPhase, resolveCallback as rawResolveCallback } from '../utils/html'7import { ErrorBoundary } from './components'8import { Suspense, renderToReadableStream, StreamingContext } from './streaming'910const unsafeHtml = '<img src=x onerror=alert(1)>'11const escapedUnsafeHtml = '&lt;img src=x onerror=alert(1)&gt;'1213function resolveCallback(template: string | HtmlEscapedString) {14 return rawResolveCallback(template, HtmlEscapedCallbackPhase.Stream, false, {})15}16
2 unmodified lines
19 document.querySelectorAll('template, script').forEach((e) => e.remove())20 return document.body.innerHTML21}2223async function stringify(node: { toString(): string | Promise<string> }): Promise<string> {24 return String(25 await rawResolveCallback(await node.toString(), HtmlEscapedCallbackPhase.Stringify, false, {})26 )27}2829async 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}3738const Fallback = () => <div>Out Of Service</div>3940describe('ErrorBoundary', () => {41 let errorBoundaryCounter = 0
773 unmodified lines
815816 suspenseCounter--817 })818 })819820 describe('escaping', () => {821 const Broken = () => {822 throw new Error('boom')823 }824825 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 )833834 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 })839840 it('escapes untrusted object fallbacks', async () => {841 const object = { toString: () => unsafeHtml }842 const asyncObject = { toString: async () => unsafeHtml }843 const rawObject = { toString: () => raw(unsafeHtml) }844845 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 })855856 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 })865866 it('does not interpret replacement patterns in content', async () => {867 const content = "literal $& $` $'"868 const Async = async () => <span>done</span>869870 expect(871 await stringify(872 <ErrorBoundary fallback='error'>873 {content}874 <Async />875 </ErrorBoundary>876 )877 ).toBe('literal $&amp; $` $&#39;<span>done</span>')878 })879880 it('escapes untrusted object children', async () => {881 const object = { toString: () => unsafeHtml }882 const asyncObject = { toString: async () => unsafeHtml }883 const rawObject = { toString: () => raw(unsafeHtml) }884885 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 })893894 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 })901902 it('keeps benign object stringification visible', async () => {903 expect(await stringify(<ErrorBoundary fallback='error'>{{} as never}</ErrorBoundary>)).toBe(904 '[object Object]'905 )906 })907908 it('escapes nested fallback arrays', async () => {909 expect(910 await stringify(911 <ErrorBoundary fallback={[[unsafeHtml]]}>912 <Broken />913 </ErrorBoundary>914 )915 ).toBe(escapedUnsafeHtml)916 })917918 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 })927928 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
1import { raw } from '../helper/html'2import type { HtmlEscapedCallback, HtmlEscapedString } from '../utils/html'3import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'4import { jsx, Fragment } from './base'4import { jsx, Fragment, isUntrustedObject, renderChildren, renderUntrustedObject } from './base'5import { DOM_RENDERER } from './constants'6import { captureRenderContext, useContext } from './context'7import { ErrorBoundary as ErrorBoundaryDomRenderer } from './dom/components'8import type { HasRenderToDom } from './dom/render'
3 unmodified lines
12let errorBoundaryCounter = 01314export 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 lines
26 }27 }28}2932const resolveChildEarly = (c: Child): HtmlEscapedString | Promise<HtmlEscapedString> => {33 if (c == null || typeof c === 'boolean') {30const 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}4243export type ErrorHandler = (error: Error) => void
27 unmodified lines
71 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 lines
96 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 lines
136137 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 lines
182</script>`183184 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 lines
modified:src/jsx/context.ts+15 added-10 removed
1import { raw } from '../helper/html'2import type { HtmlEscapedString } from '../utils/html'3import { JSXFragmentNode } from './base'3import { isUntrustedObject, JSXFragmentNode, renderChildren, renderUntrustedObject } from './base'4import { DOM_RENDERER } from './constants'5import { createContextProviderFunction } from './dom/context'6import type { FC, PropsWithChildren } from './'7
208 unmodified lines
216 // 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 }237233 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 = context
18 unmodified lines
modified:src/jsx/index.test.tsx+59 added
1177 unmodified lines
1178 )1179 expect(template.toString()).toBe('<div><span>dark</span>!</div><div><span>dark</span>!</div>')1180 })11811182 it('escapes a single string child', async () => {1183 const template = (1184 <ThemeContext.Provider value='dark'>{'<img src=x onerror=alert(1)>'}</ThemeContext.Provider>1185 )11861187 expect(String(await template.toString())).toBe('&lt;img src=x onerror=alert(1)&gt;')1188 })11891190 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 )11971198 expect(String(await template.toString())).toBe('&lt;img src=x onerror=alert(1)&gt;')1199 })12001201 it('preserves explicitly trusted content', async () => {1202 const template = (1203 <ThemeContext.Provider value='dark'>1204 {raw('<strong>trusted</strong>')}1205 </ThemeContext.Provider>1206 )12071208 expect(await template.toString()).toBe('<strong>trusted</strong>')1209 })12101211 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)>') }12151216 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('&lt;img src=x onerror=alert(1)&gt;')1221 }1222 })12231224 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 )12291230 expect(await template.toString()).toBe('safe')1231 })12321233 it('keeps a direct Promise child unchanged', async () => {1234 const template = (1235 <ThemeContext.Provider value='dark'>{Promise.resolve('resolved')}</ThemeContext.Provider>1236 )12371238 expect(await template.toString()).toBe('[object Promise]')1239 })12401241 it('nested', () => {1242 const template = (1243 <ThemeContext.Provider value='dark'>1244 <Consumer />
501 unmodified lines
modified:src/jsx/streaming.test.tsx+124 added
7 unmodified lines
8import { buildDataStack } from './dom/render'9import { use } from './hooks'10import { Suspense, renderToReadableStream, StreamingContext } from './streaming'1112const unsafeHtml = '<img src=x onerror=alert(1)>'13const escapedUnsafeHtml = '&lt;img src=x onerror=alert(1)&gt;'1415function 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.innerHTML
7 unmodified lines
26 }27 return html28}2930async function stringify(node: { toString(): string | Promise<string> }): Promise<string> {31 return String(32 await resolveCallback(await node.toString(), HtmlEscapedCallbackPhase.Stringify, false, {})33 )34}3536async 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()4849 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}5657describe('Streaming', () => {58 let suspenseCounter = 059 afterEach(() => {60 suspenseCounter++
1122 unmodified lines
1183 expect(adminHtml).not.toContain('role:guest')1184 expect(guestHtml).toContain('role:guest')1185 expect(guestHtml).not.toContain('role:admin')1186 })11871188 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 )11971198 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 })12031204 it('escapes nested array strings', async () => {1205 expect(await stringify(<Suspense fallback='loading'>{[[[unsafeHtml]]]}</Suspense>)).toBe(1206 escapedUnsafeHtml1207 )1208 })12091210 it('escapes a primitive fallback in the initial stream chunk', async () => {1211 const initialChunk = await readInitialSuspenseChunk(unsafeHtml)12121213 expect(initialChunk).toContain(escapedUnsafeHtml)1214 expect(initialChunk).not.toContain(unsafeHtml)1215 })12161217 it('escapes untrusted object fallbacks', async () => {1218 const object = { toString: () => unsafeHtml }1219 const asyncObject = { toString: async () => unsafeHtml }1220 const rawObject = { toString: () => raw(unsafeHtml) }12211222 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 })12281229 it('preserves an explicitly trusted fallback', async () => {1230 expect(await readInitialSuspenseChunk(raw('<strong>trusted</strong>'))).toContain(1231 '<strong>trusted</strong>'1232 )1233 })12341235 it('does not interpret replacement patterns in content', async () => {1236 const content = "literal $& $` $'"1237 const Async = async () => <span>done</span>12381239 expect(1240 await stringify(1241 <Suspense fallback='loading'>1242 {content}1243 <Async />1244 </Suspense>1245 )1246 ).toBe('literal $&amp; $` $&#39;<span>done</span>')1247 })12481249 it('escapes untrusted object children', async () => {1250 const object = { toString: () => unsafeHtml }1251 const asyncObject = { toString: async () => unsafeHtml }1252 const rawObject = { toString: () => raw(unsafeHtml) }12531254 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 })12621263 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 })12681269 it('keeps benign object stringification visible', async () => {1270 expect(await stringify(<Suspense fallback='loading'>{{} as never}</Suspense>)).toBe(1271 '[object Object]'1272 )1273 })12741275 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 lines
56import { raw } from '../helper/html'7import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'8import type { HtmlEscapedString } from '../utils/html'9import { JSXNode } from './base'9import { isUntrustedObject, JSXNode, renderChildren, renderUntrustedObject } from './base'10import { childrenToString } from './components'11import { DOM_RENDERER, DOM_STASH } from './constants'12import { captureRenderContext, createContext, useContext } from './context'13import { Suspense as SuspenseDomRenderer } from './dom/components'
18 unmodified lines
32} | null>(null)3334let suspenseCounter = 03536const 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()4445/**46 * @experimental47 * `Suspense` is an experimental feature.48 * The API might be changed.
19 unmodified lines
6869 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 lines
92 }9394 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 lines
109 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