Skip to content

Commit

Permalink
Merge pull request #1371 from Datawheel/sanitization-location
Browse files Browse the repository at this point in the history
Sanitize location attributes in store
  • Loading branch information
jhmullen authored Aug 24, 2022
2 parents 20f22e0 + 232d118 commit a226875
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
24 changes: 24 additions & 0 deletions packages/core/src/helpers/stripHTML.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Internal list of HTML entities for escaping.
const entities = {
"&": "&",
"&lt;": "<",
"&gt;": ">",
"&quot;": "\"",
"&#x27;": "'",
"&#x60;": "`",
"&nbsp;": ""
};

const source = `(?:${ Object.keys(entities).join("|") })`;
const testRegexp = RegExp(source);
const replaceRegexp = RegExp(source, "g");

/**
* Converts html tags to spaces, then removes redundant spaces
*/
function stripHTML(n) {
const s = String(n).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
return testRegexp.test(s) ? s.replace(replaceRegexp, match => entities[match]) : s;
}

module.exports = stripHTML;
16 changes: 12 additions & 4 deletions packages/core/src/server.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {initialState as appInitialState} from "$app/store";
import preRenderMiddleware from "./middlewares/preRenderMiddleware";
import pretty from "pretty";
import maybeRedirect from "./helpers/maybeRedirect";
import stripHTML from "./helpers/stripHTML";
import {servicesAvailable, servicesBody, servicesScript, servicesHeadTags} from "./helpers/services";
import yn from "yn";

Expand All @@ -32,6 +33,13 @@ const baseTag = process.env.CANON_BASE_URL === undefined ? ""
: `
<base href='${BASE_URL}'>`;


const getCleanedParams = queryParams => {
return Object.keys(queryParams).reduce((params, paramKey) => {
params[stripHTML(paramKey)] = stripHTML(queryParams[paramKey]);
return params;
}, {})
}
/**
Returns the default server logic for rendering a page.
*/
Expand All @@ -46,13 +54,13 @@ export default function(defaultStore = appInitialState, headerConfig, reduxMiddl
basename,
host: req.headers.host,
hostname: req.headers.host.split(":")[0],
href: `${req.protocol}://${req.headers.host}${req.url}`,
href: `${req.protocol}://${stripHTML(`${req.headers.host}${req.url}`)}`,
origin: `${req.protocol}://${req.headers.host}`,
pathname: req.url.split("?")[0],
pathname: stripHTML(req.url.split("?")[0]),
port: req.headers.host.includes(":") ? req.headers.host.split(":")[1] : "80",
protocol: `${req.protocol}:`,
query: req.query,
search: req.url.includes("?") ? `?${req.url.split("?")[1]}` : ""
query: getCleanedParams(req.query),
search: req.url.includes("?") ? `?${stripHTML(req.url.split("?")[1])}` : ""
};

const location = req.url.replace(BASE_URL, "");
Expand Down

0 comments on commit a226875

Please sign in to comment.