diff --git a/scripts/csp.json b/scripts/csp.json new file mode 100644 index 000000000..1c203c79b --- /dev/null +++ b/scripts/csp.json @@ -0,0 +1,13 @@ +{ + "default-src": [ + "'self'" + ], + "script-src": [ + "'self'", + "https://rum.hlx.page/" + ], + "connect-src": [ + "'self'", + "https://rum.hlx.page/" + ] +} \ No newline at end of file diff --git a/scripts/scripts.js b/scripts/scripts.js index 7609d1412..1f42805bd 100644 --- a/scripts/scripts.js +++ b/scripts/scripts.js @@ -72,11 +72,29 @@ async function loadEager(doc) { } } +/** + * sets the Content-Security-Policy meta tag to the document based on JSON file + */ + +async function setCSP() { + const resp = await fetch(`${window.hlx.codeBasePath}/scripts/csp.json`); + const json = await resp.json(); + const directives = Object.keys(json); + const policy = directives.map((directive) => `${directive} ${json[directive].join(' ')}`).join('; '); + const meta = document.createElement('meta'); + meta.setAttribute('http-equiv', 'Content-Security-Policy'); + meta.setAttribute('content', policy); + document.addEventListener('securitypolicyviolation', (e) => sampleRUM('csperror', { source: `${e.documentURI}:${e.lineNumber}:${e.columnNumber}`, target: e.blockedURI })); + document.head.appendChild(meta); +} + /** * Loads everything that doesn't need to be delayed. * @param {Element} doc The container element */ async function loadLazy(doc) { + await setCSP(); + const main = doc.querySelector('main'); await loadBlocks(main);