correctly extend existing CSP + cosmetics

This commit is contained in:
tophf 2020-11-16 09:42:08 +03:00
parent b8322ecf01
commit c83594519b

View File

@ -3,19 +3,20 @@
// eslint-disable-next-line no-unused-expressions // eslint-disable-next-line no-unused-expressions
CHROME && (async () => { CHROME && (async () => {
const idCsp = 'patchCsp'; const idCSP = 'patchCsp';
const idOff = 'disableAll'; const idOFF = 'disableAll';
const idXhr = 'styleViaXhr'; const idXHR = 'styleViaXhr';
const rxHOST = /^('none'|(https?:\/\/)?[^']+?[^:'])$/; // strips CSP sources covered by *
const blobUrlPrefix = 'blob:' + chrome.runtime.getURL('/'); const blobUrlPrefix = 'blob:' + chrome.runtime.getURL('/');
const stylesToPass = {}; const stylesToPass = {};
const enabled = {}; const enabled = {};
await prefs.initializing; await prefs.initializing;
prefs.subscribe([idXhr, idOff, idCsp], toggle, {now: true}); prefs.subscribe([idXHR, idOFF, idCSP], toggle, {now: true});
function toggle() { function toggle() {
const csp = prefs.get(idCsp) && !prefs.get(idOff); const csp = prefs.get(idCSP) && !prefs.get(idOFF);
const xhr = prefs.get(idXhr) && !prefs.get(idOff) && Boolean(chrome.declarativeContent); const xhr = prefs.get(idXHR) && !prefs.get(idOFF) && Boolean(chrome.declarativeContent);
if (xhr === enabled.xhr && csp === enabled.csp) { if (xhr === enabled.xhr && csp === enabled.csp) {
return; return;
} }
@ -45,10 +46,10 @@ CHROME && (async () => {
function toggleEarlyInjection() { function toggleEarlyInjection() {
const api = chrome.declarativeContent; const api = chrome.declarativeContent;
if (!api) return; if (!api) return;
api.onPageChanged.removeRules([idXhr], async () => { api.onPageChanged.removeRules([idXHR], async () => {
if (enabled.xhr) { if (enabled.xhr) {
api.onPageChanged.addRules([{ api.onPageChanged.addRules([{
id: idXhr, id: idXHR,
conditions: [ conditions: [
new api.PageStateMatcher({ new api.PageStateMatcher({
pageUrl: {urlContains: '://'}, pageUrl: {urlContains: '://'},
@ -115,10 +116,15 @@ CHROME && (async () => {
} }
function addToCsp(src, name, ...values) { function addToCsp(src, name, ...values) {
const list = src[name] || (src[name] = []); let def = src['default-src'];
const def = src['default-src'] || []; let list = src[name];
list.push(...values.filter(v => !list.includes(v) && !def.includes(v))); if (def || list) {
if (!list.length) delete src[name]; if (!def) def = [];
if (!list) list = [...def];
if (values.includes('*')) list = src[name] = list.filter(v => !rxHOST.test(v));
list.push(...values.filter(v => !list.includes(v) && !def.includes(v)));
if (!list.length) delete src[name];
}
} }
function cleanUp(key) { function cleanUp(key) {