Last active
June 21, 2024 18:50
-
-
Save tw3/8f5aba15588dea162d5c25c93a68f86a to your computer and use it in GitHub Desktop.
Parse Content Security Policy (CSP)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Playground here: https://codepen.io/tw3/pen/eYaMPOZ | |
function parseCsp(csp) { | |
const result = []; | |
const cspArr = csp.split(';'); | |
cspArr.forEach((x) => { | |
const vals = x.trim().split(' ').filter(Boolean); | |
let idx = 0; | |
const entryArr = []; | |
entryArr.push(vals[idx++]); // resource, e.g. default-src | |
const isTarget = vals[idx]?.startsWith("'"); | |
if (isTarget) { | |
entryArr.push(vals[idx++]); // target, e.g. 'self' | |
} | |
const domains = vals.slice(idx++); | |
entryArr.push(domains); | |
result.push(entryArr); | |
}); | |
return result; | |
} | |
var cspStr = "default-src 'self'; script-src 'unsafe-eval' scripts.com; object-src; style-src styles.biz"; | |
var result = parseCsp(cspStr); | |
console.log('result', result); | |
/* | |
result = [ | |
[ 'default-src', "'self'", [] ], | |
[ 'script-src', "'unsafe-eval'", [ 'scripts.com' ] ], | |
[ 'object-src', [] ], | |
[ 'style-src', [ 'styles.biz' ] ] | |
] | |
*/ | |
// You can modify the parsed result and convert back to a string as follows: | |
var newCspStr = result.map((entryArr) => entryArr.map((val) => Array.isArray(val) ? val.join(' ') : val).filter(Boolean).join(' ')).join('; '); | |
console.log('newCspStr', newCspStr); // "default-src 'self'; script-src 'unsafe-eval' scripts.com; object-src; style-src styles.biz" | |
console.log(newCspStr === cspStr); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment