Skip to content

Commit 73f06e0

Browse files
Merge pull request #1 from HakordiaNetwork/alert-autofix-17
Potential fix for code scanning alert no. 17: Code injection
2 parents 462d08f + 9459f54 commit 73f06e0

File tree

1 file changed

+27
-15
lines changed

1 file changed

+27
-15
lines changed

fixtures/dom/src/react-loader.js

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -39,27 +39,39 @@ function loadScript(src) {
3939
function loadModules(SymbolSrcPairs) {
4040
let firstScript = document.getElementsByTagName('script')[0];
4141

42-
let imports = '';
43-
SymbolSrcPairs.map(([symbol, src]) => {
44-
imports += `import ${symbol} from "${src}";\n`;
45-
imports += `window.${symbol} = ${symbol};\n`;
46-
});
47-
4842
return new Promise((resolve, reject) => {
4943
const timeout = setTimeout(
5044
() => reject(new Error('Timed out loading react modules over esm')),
5145
5000
5246
);
53-
window.__loaded = () => {
54-
clearTimeout(timeout);
55-
resolve();
56-
};
57-
58-
const moduleScript = document.createElement('script');
59-
moduleScript.type = 'module';
60-
moduleScript.textContent = imports + 'window.__loaded();';
6147

62-
firstScript.parentNode.insertBefore(moduleScript, firstScript);
48+
let loadedCount = 0;
49+
const totalModules = SymbolSrcPairs.length;
50+
51+
SymbolSrcPairs.forEach(([symbol, src]) => {
52+
if (typeof symbol !== 'string' || typeof src !== 'string' || !/^https?:\/\//.test(src)) {
53+
reject(new Error(`Invalid module specification: ${symbol}, ${src}`));
54+
return;
55+
}
56+
57+
const scriptNode = document.createElement('script');
58+
scriptNode.type = 'module';
59+
scriptNode.src = src;
60+
scriptNode.onload = () => {
61+
window[symbol] = window[symbol] || {}; // Ensure the symbol is available globally
62+
loadedCount++;
63+
if (loadedCount === totalModules) {
64+
clearTimeout(timeout);
65+
resolve();
66+
}
67+
};
68+
scriptNode.onerror = () => {
69+
clearTimeout(timeout);
70+
reject(new Error(`Failed to load module: ${src}`));
71+
};
72+
73+
firstScript.parentNode.insertBefore(scriptNode, firstScript);
74+
});
6375
});
6476
}
6577

0 commit comments

Comments
 (0)