I have a need to to create and attach a script
tag to DOM at runtime.
The script is a remote webpack bundle (via a Module Federation plugin). I would like to be able to change the URL to that hosted remote bundle at runtime (for A/B testing and debugging purposes). This is my own code, and I trust it as far as not having malicious code in it.
The code would look something like this
var myScript = document.createElement('script');
myScript.src = 'https://my.remote.domain.com/path/to/myScript.js';
document.head.appendChild(myScript);
... other code to make the webpack bundle run
My questions are:
Is it safe to allow passing the
https://my.remote.domain.com/path/to/myScript.js
as a URL query param. Ex:https://my.site.com?scriptUrl=https://my.remote.domain.com/path/to/myScript.js
? The code would look like this:var urlParams = new URLSearchParams(window.location.search); var myScript = document.createElement('script'); myScript.src = urlParams.get('post'); document.head.appendChild(myScript);
It feels like this could open up a hole for an attacker to pass in a URL to an attacker script and execute it on my page. Am I on the right track here, or is this not a concern?
What are the ways to secure the code above and allow the dynamic script attachments?
If this code is an issue, what are the specific attacks that could happen here?