Skip to content
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

Escape bootstrapScriptContent for javascript embedding into HTML #24385

Merged
merged 5 commits into from
Apr 16, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Escape bootstrapScriptContent for javascript embedding into HTML
The previous escape was for Text into HTML and breaks script contents. The new escaping ensures that the script contents cannot prematurely close the host script tag by escaping script open and close string sequences using a unicode escape substitution.
  • Loading branch information
gnoff committed Apr 15, 2022
commit 11483ce903381d35004969611cc56a3d76e9e7bf
107 changes: 107 additions & 0 deletions packages/react-dom/src/__tests__/escapeScriptForBrowser-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/

'use strict';

let React;
let ReactDOMFizzServer;
let Stream;

function getTestWritable() {
const writable = new Stream.PassThrough();
writable.setEncoding('utf8');
const output = {result: '', error: undefined};
writable.on('data', chunk => {
output.result += chunk;
});
writable.on('error', error => {
output.error = error;
});
const completed = new Promise(resolve => {
writable.on('finish', () => {
resolve();
});
writable.on('error', () => {
resolve();
});
});
return {writable, completed, output};
}

describe('escapeScriptForBrowser', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOMFizzServer = require('react-dom/server');
Stream = require('stream');
});

it('"<[Ss]cript" strings are replaced with unicode escaped lowercase s or S depending on case', () => {
const {writable, output} = getTestWritable();
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<div />, {
bootstrapScriptContent:
'"prescription pre<scription preScription pre<Scription"',
});
pipe(writable);
jest.runAllTimers();
expect(output.result).toMatch(
'<div></div><script>"prescription pre<\\u0073cription preScription pre<\\u0053cription"</script>',
gnoff marked this conversation as resolved.
Show resolved Hide resolved
);
});

it('"</[Ss]cript" strings are replaced with encoded lowercase s or S depending on case', () => {
const {writable, output} = getTestWritable();
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<div />, {
bootstrapScriptContent:
'"prescription pre</scription preScription pre</Scription"',
});
pipe(writable);
jest.runAllTimers();
expect(output.result).toMatch(
'<div></div><script>"prescription pre</\\u0073cription preScription pre</\\u0053cription"</script>',
);
});

it('"[Ss]cript", "/[Ss]cript", "<[Ss]crip", "</[Ss]crip" strings are not escaped', () => {
const {writable, output} = getTestWritable();
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<div />, {
bootstrapScriptContent:
'"Script script /Script /script <Scrip <scrip </Scrip </scrip"',
});
pipe(writable);
jest.runAllTimers();
expect(output.result).toMatch(
'<div></div><script>"Script script /Script /script <Scrip <scrip </Scrip </scrip"</script>',
);
});

it('matches case insensitively', () => {
const {writable, output} = getTestWritable();
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<div />, {
bootstrapScriptContent: '"<sCrIpT <ScripT </scrIPT </SCRIpT"',
});
pipe(writable);
jest.runAllTimers();
expect(output.result).toMatch(
'<div></div><script>"<\\u0073CrIpT <\\u0053cripT </\\u0073crIPT </\\u0053CRIpT"</script>',
);
});

it('does not escape <, >, &, \\u2028, or \\u2029 characters', () => {
gnoff marked this conversation as resolved.
Show resolved Hide resolved
const {writable, output} = getTestWritable();
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<div />, {
bootstrapScriptContent: '"<, >, &, \u2028, or \u2029"',
});
pipe(writable);
jest.runAllTimers();
expect(output.result).toMatch(
'<div></div><script>"<, >, &, \u2028, or \u2029"</script>',
);
});
});
3 changes: 2 additions & 1 deletion packages/react-dom/src/server/ReactDOMServerFormatConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import {validateProperties as validateUnknownProperties} from '../shared/ReactDO
import warnValidStyle from '../shared/warnValidStyle';

import escapeTextForBrowser from './escapeTextForBrowser';
import escapeScriptForBrowser from './escapeScriptForBrowser';
import hyphenateStyleName from '../shared/hyphenateStyleName';
import hasOwnProperty from 'shared/hasOwnProperty';
import sanitizeURL from '../shared/sanitizeURL';
Expand Down Expand Up @@ -102,7 +103,7 @@ export function createResponseState(
if (bootstrapScriptContent !== undefined) {
bootstrapChunks.push(
inlineScriptWithNonce,
stringToChunk(escapeTextForBrowser(bootstrapScriptContent)),
stringToChunk(escapeScriptForBrowser(bootstrapScriptContent)),
endInlineScript,
);
}
Expand Down
37 changes: 37 additions & 0 deletions packages/react-dom/src/server/escapeScriptForBrowser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {checkHtmlStringCoercion} from 'shared/CheckStringCoercion';

const scriptRegex = /(<\/|<)(s)(cript)/gi;
const scriptReplacer = (match, prefix, s, suffix) =>
`${prefix}${substitutions[s]}${suffix}`;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's make this an inline condition instead of going through a whole hidden class check and fake-map look up.

Copy link
Collaborator

@sebmarkbage sebmarkbage Apr 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant s === 's' ? '\\u0073' : '\\u0053'

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

const substitutions = {
s: '\\u0073',
S: '\\u0053',
};

/**
* Escapes javascript for embedding into HTML.
*
* @param {*} scriptText Text value to escape.
* @return {string} An escaped string.
*/
function escapeScriptForBrowser(scriptText) {
gnoff marked this conversation as resolved.
Show resolved Hide resolved
if (typeof scriptText === 'boolean' || typeof scriptText === 'number') {
// this shortcircuit helps perf for types that we know will never have
// special characters, especially given that this function is used often
// for numeric dom ids.
return '' + scriptText;
gnoff marked this conversation as resolved.
Show resolved Hide resolved
}
if (__DEV__) {
checkHtmlStringCoercion(scriptText);
}
return ('' + scriptText).replace(scriptRegex, scriptReplacer);
}

export default escapeScriptForBrowser;