Skip to content

Commit

Permalink
Trusted Types sanitize URL from XSS
Browse files Browse the repository at this point in the history
  • Loading branch information
melloware committed Jan 12, 2022
1 parent ad9f8e2 commit 2e2a0e4
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 4 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@melloware/csp-webpack-plugin",
"version": "6.0.2",
"version": "6.0.3",
"description": "A plugin which, when combined with HTMLWebpackPlugin, adds CSP tags to the HTML output",
"main": "plugin.js",
"types": "plugin.d.ts",
Expand Down
5 changes: 4 additions & 1 deletion plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const webpack = require('webpack');
const { SubresourceIntegrityPlugin } = require('webpack-subresource-integrity');
const InjectPlugin = require('webpack-inject-plugin').default;

/* eslint-disable no-useless-escape */

// Attempt to load HtmlWebpackPlugin@4
// Borrowed from https://github.com/waysact/webpack-subresource-integrity/blob/master/index.js
let HtmlWebpackPlugin;
Expand Down Expand Up @@ -402,10 +404,11 @@ class CspHtmlWebpackPlugin {
this.cspPluginPolicy['require-trusted-types-for']
) {
const purifyScript = `import DOMPurify from 'dompurify';
var invalidProtocolRegex=/^([^\w]*)(javascript|data|vbscript)/im,ctrlCharactersRegex=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim,urlSchemeRegex=/^([^:]+):/gm,relativeFirstCharacters=[".","/"];function isRelativeUrlWithoutProtocol(r){return relativeFirstCharacters.indexOf(r[0])>-1}function sanitizeUrl(r){if(!r)return"about:blank";var e=r.replace(ctrlCharactersRegex,"").trim();if(isRelativeUrlWithoutProtocol(e))return e;var t=e.match(urlSchemeRegex);if(!t)return e;var a=t[0];return invalidProtocolRegex.test(a)?"about:blank":e}
if (window.trustedTypes && window.trustedTypes.createPolicy) { // Feature testing
window.trustedTypes.createPolicy('default', {
createHTML: (string) => DOMPurify.sanitize(string, {RETURN_TRUSTED_TYPE: true}),
createScriptURL: string => string, // allow scripts
createScriptURL: string => sanitizeUrl(string),
createScript: string => string // allow scripts
});
}`;
Expand Down

0 comments on commit 2e2a0e4

Please sign in to comment.