-
Notifications
You must be signed in to change notification settings - Fork 26.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix broken HTML inlining of non UTF-8 decodable binary data from Flight payload #65664
Merged
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7af075b
support inlining binary flight payload
shuding 596f012
improve inlining
shuding d0416ce
add test
shuding 15160d0
fix inlining decoding function
shuding 3bf3976
revert leftover edit
shuding 6c519d4
Separate app router cache entries from pages and use buffer (#65808)
ijjk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,6 +9,7 @@ const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' | |
const INLINE_FLIGHT_PAYLOAD_BOOTSTRAP = 0 | ||
const INLINE_FLIGHT_PAYLOAD_DATA = 1 | ||
const INLINE_FLIGHT_PAYLOAD_FORM_STATE = 2 | ||
const INLINE_FLIGHT_PAYLOAD_BINARY = 3 | ||
|
||
const flightResponses = new WeakMap<BinaryStreamOf<any>, Promise<any>>() | ||
const encoder = new TextEncoder() | ||
|
@@ -78,6 +79,25 @@ export async function flightRenderComplete( | |
} | ||
} | ||
|
||
const decoder = new TextDecoder('utf-8', { fatal: true }) | ||
|
||
/** | ||
* This function will attempt to decode a Uint8Array as a UTF-8 string. If the | ||
* data is not valid UTF-8 it will return null. | ||
* | ||
* @param value A Uint8Array that can contain arbitrary data. | ||
*/ | ||
function tryDecodeAsUtf8String( | ||
value: Uint8Array, | ||
stream: boolean | ||
): string | null { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You're really better off inlining this manually and do the different code paths based on code flow instead of the temporary value. The compiler can't optimize this without knowing whether whatever |
||
try { | ||
return decoder.decode(value, { stream }) | ||
} catch { | ||
return null | ||
} | ||
} | ||
|
||
/** | ||
* Creates a ReadableStream provides inline script tag chunks for writing hydration | ||
* data to the client outside the React render itself. | ||
|
@@ -96,9 +116,6 @@ export function createInlinedDataReadableStream( | |
? `<script nonce=${JSON.stringify(nonce)}>` | ||
: '<script>' | ||
|
||
const decoder = new TextDecoder('utf-8', { fatal: true }) | ||
const decoderOptions = { stream: true } | ||
|
||
const flightReader = flightStream.getReader() | ||
|
||
const readable = new ReadableStream({ | ||
|
@@ -114,15 +131,21 @@ export function createInlinedDataReadableStream( | |
async pull(controller) { | ||
try { | ||
const { done, value } = await flightReader.read() | ||
if (done) { | ||
const tail = decoder.decode(value, { stream: false }) | ||
if (tail.length) { | ||
writeFlightDataInstruction(controller, startScriptTag, tail) | ||
|
||
if (value) { | ||
const decoded = tryDecodeAsUtf8String(value, !done) | ||
|
||
if (decoded === null) { | ||
// The chunk cannot be decoded as valid UTF-8 string as it might | ||
// have arbitrary binary data. | ||
writeFlightDataInstruction(controller, startScriptTag, value) | ||
} else if (decoded.length) { | ||
writeFlightDataInstruction(controller, startScriptTag, decoded) | ||
} | ||
} | ||
|
||
if (done) { | ||
controller.close() | ||
} else { | ||
const chunkAsString = decoder.decode(value, decoderOptions) | ||
writeFlightDataInstruction(controller, startScriptTag, chunkAsString) | ||
} | ||
} catch (error) { | ||
// There was a problem in the upstream reader or during decoding or enqueuing | ||
|
@@ -154,13 +177,28 @@ function writeInitialInstructions( | |
function writeFlightDataInstruction( | ||
controller: ReadableStreamDefaultController, | ||
scriptStart: string, | ||
chunkAsString: string | ||
chunk: string | Uint8Array | ||
) { | ||
let htmlInlinedData: string | ||
|
||
if (typeof chunk === 'string') { | ||
htmlInlinedData = htmlEscapeJsonString( | ||
JSON.stringify([INLINE_FLIGHT_PAYLOAD_DATA, chunk]) | ||
) | ||
} else { | ||
// The chunk cannot be embedded as a UTF-8 string in the script tag. | ||
// Instead let's inline it in base64. | ||
// Credits to Devon Govett (devongovett) for the technique. | ||
// https://github.com/devongovett/rsc-html-stream | ||
const base64 = btoa(String.fromCodePoint(...chunk)) | ||
htmlInlinedData = htmlEscapeJsonString( | ||
JSON.stringify([INLINE_FLIGHT_PAYLOAD_BINARY, base64]) | ||
) | ||
} | ||
|
||
controller.enqueue( | ||
encoder.encode( | ||
`${scriptStart}self.__next_f.push(${htmlEscapeJsonString( | ||
JSON.stringify([INLINE_FLIGHT_PAYLOAD_DATA, chunkAsString]) | ||
)})</script>` | ||
`${scriptStart}self.__next_f.push(${htmlInlinedData})</script>` | ||
) | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
'use client' | ||
|
||
import { useEffect, useState } from 'react' | ||
|
||
export function Client({ binary, arbitrary }) { | ||
const [hydrated, setHydrated] = useState(false) | ||
|
||
useEffect(() => { | ||
setHydrated(true) | ||
}, []) | ||
|
||
return ( | ||
<> | ||
<div>utf8 binary: {new TextDecoder().decode(binary)}</div> | ||
<div>arbitrary binary: {String(arbitrary)}</div> | ||
<div>hydrated: {String(hydrated)}</div> | ||
</> | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
export const metadata = { | ||
title: 'Next.js', | ||
description: 'Generated by Next.js', | ||
} | ||
|
||
export default function RootLayout({ children }) { | ||
return ( | ||
<html lang="en"> | ||
<body>{children}</body> | ||
</html> | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import { Client } from './client' | ||
|
||
export default function Page() { | ||
const binaryData = new Uint8Array([104, 101, 108, 108, 111]) | ||
const nonUtf8BinaryData = new Uint8Array([0xff, 0, 1, 2, 3]) | ||
|
||
return <Client binary={binaryData} arbitrary={nonUtf8BinaryData} /> | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
module.exports = { | ||
experimental: { | ||
// This ensures that we're running the experimental React. | ||
taint: true, | ||
}, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { nextTestSetup } from 'e2e-utils' | ||
import { check } from 'next-test-utils' | ||
|
||
describe('RSC binary serialization', () => { | ||
const { next, skipped } = nextTestSetup({ | ||
files: __dirname, | ||
skipDeployment: true, | ||
dependencies: { | ||
react: '19.0.0-beta-4508873393-20240430', | ||
'react-dom': '19.0.0-beta-4508873393-20240430', | ||
'server-only': 'latest', | ||
}, | ||
}) | ||
if (skipped) return | ||
|
||
afterEach(async () => { | ||
await next.stop() | ||
}) | ||
|
||
it('should correctly encode/decode binaries and hydrate', async function () { | ||
const browser = await next.browser('/') | ||
await check(async () => { | ||
const content = await browser.elementByCss('body').text() | ||
|
||
return content.includes('utf8 binary: hello') && | ||
content.includes('arbitrary binary: 255,0,1,2,3') && | ||
content.includes('hydrated: true') | ||
? 'success' | ||
: 'fail' | ||
}, 'success') | ||
}) | ||
}) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is not safe because there can be multiple streams at the same time interleaving and because the streaming mode is used, there's a buffer stored inside this object for partial bytes received from previous chunks which can conflict.
This needs to be a new one per stream like it was before.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Makes total sense!