Skip to content

Commit

Permalink
Merge pull request #262 from webpack-contrib/proper-js-escape
Browse files Browse the repository at this point in the history
Properly escape embedded JS/JSON
  • Loading branch information
th0r committed Apr 11, 2019
2 parents 81ec8b3 + 5385936 commit 3ce1b8c
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 7 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Expand Up @@ -14,6 +14,9 @@ _Note: Gaps between patch versions are faulty, broken or test releases._

<!-- Add changelog entries for new changes under this section -->

* **Improvements**
* Properly escape embedded JS/JSON ([#262](https://github.com/webpack-contrib/webpack-bundle-analyzer/pull/262))

* **Bug Fix**
* Fix showing help message on `-h` flag ([#260](https://github.com/webpack-contrib/webpack-bundle-analyzer/pull/260), fixes [#239](https://github.com/webpack-contrib/webpack-bundle-analyzer/issues/239))

Expand Down
17 changes: 14 additions & 3 deletions src/viewer.js
Expand Up @@ -53,7 +53,9 @@ async function startServer(bundleStats, opts) {
mode: 'server',
get chartData() { return JSON.stringify(chartData) },
defaultSizes: JSON.stringify(defaultSizes),
enableWebSocket: true
enableWebSocket: true,
// Helpers
escapeScript
});
});

Expand Down Expand Up @@ -131,9 +133,11 @@ async function generateReport(bundleStats, opts) {
{
mode: 'static',
chartData: JSON.stringify(chartData),
assetContent: getAssetContent,
defaultSizes: JSON.stringify(defaultSizes),
enableWebSocket: false
enableWebSocket: false,
// Helpers
assetContent: getAssetContent,
escapeScript
},
(err, reportHtml) => {
try {
Expand Down Expand Up @@ -168,6 +172,13 @@ function getAssetContent(filename) {
return fs.readFileSync(`${projectRoot}/public/${filename}`, 'utf8');
}

/**
* Escapes `<` characters in the string to safely use it in `<script>` tag.
*/
function escapeScript(value) {
return String(value).replace(/</gu, '\\u003c');
}

function getChartData(analyzerOpts, ...args) {
let chartData;
const {logger} = analyzerOpts;
Expand Down
2 changes: 1 addition & 1 deletion views/script.ejs
@@ -1,7 +1,7 @@
<% if (mode === 'static') { %>
<!-- <%= filename %> -->
<script>
<%- assetContent(filename) %>
<%- escapeScript(assetContent(filename)) %>
</script>
<% } else { %>
<script src="/<%= filename %>"></script>
Expand Down
6 changes: 3 additions & 3 deletions views/viewer.ejs
Expand Up @@ -11,9 +11,9 @@
<body>
<div id="app"></div>
<script>
window.chartData = <%- chartData %>;
window.defaultSizes = <%- defaultSizes %>;
window.enableWebSocket = <%- enableWebSocket %>;
window.chartData = <%- escapeScript(chartData) %>;
window.defaultSizes = <%- escapeScript(defaultSizes) %>;
window.enableWebSocket = <%- escapeScript(enableWebSocket) %>;
</script>
</body>
</html>

0 comments on commit 3ce1b8c

Please sign in to comment.