Skip to content

Commit

Permalink
feat: Log unclean HTML for future troubleshooting
Browse files Browse the repository at this point in the history
  • Loading branch information
DafyddLlyr committed Jan 4, 2024
1 parent 18d0f05 commit 2e5e0aa
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions api.planx.uk/modules/webhooks/service/validateInput/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { isObject } from "lodash";
import { JSDOM } from "jsdom";
import createDOMPurify from "dompurify";
import { userContext } from "../../../auth/middleware";

// Setup JSDOM and DOMPurify
const window = new JSDOM("").window;
Expand Down Expand Up @@ -39,19 +40,33 @@ export const isCleanHTML = (input: unknown): boolean => {
if (typeof input !== "string") return true;

const cleanHTML = DOMPurify.sanitize(input, { ADD_ATTR: ["target"] });

// DOMPurify has not removed any attributes or values
const isClean =
cleanHTML.length === input.length ||
unescapeHTML(cleanHTML).length === unescapeHTML(input).length;

if (!isClean) {
console.log("CLEAN HTML: ", cleanHTML);
console.log("INPUT HTML: ", input);
console.log("UNESCAPED HTML: ", unescapeHTML(input));
}
if (!isClean) logUncleanHTMLError(input, cleanHTML);

return isClean;
};

/**
* Explicity log error when unsafe HTML is encountered
* This is very likely a content / sanitation error as opposed to a security issue
* Logging this should help us identify and resolve these
*/
const logUncleanHTMLError = (input: string, cleanHTML: string) => {
const userId = userContext.getStore()?.user.sub;

console.error({
message: `Warning: Unclean HTML submitted!`,
userId,
input,
cleanHTML,
});
};

const unescapeHTML = (input: string): string =>
input
.replace(/"/gi, '"')
Expand Down

0 comments on commit 2e5e0aa

Please sign in to comment.