feat: csp list

This commit is contained in:
Gabe Yuan
2024-03-26 12:00:09 +08:00
parent b3cb4049ed
commit 6fa183dc56
6 changed files with 94 additions and 4 deletions

View File

@@ -12,6 +12,8 @@ import {
MSG_COMMAND_SHORTCUTS,
MSG_INJECT_JS,
MSG_INJECT_CSS,
MSG_UPDATE_CSP,
DEFAULT_CSPLIST,
CMD_TOGGLE_TRANSLATE,
CMD_TOGGLE_STYLE,
CMD_OPEN_OPTIONS,
@@ -26,9 +28,17 @@ import { tryClearCaches } from "./libs";
import { saveRule } from "./libs/rules";
import { getCurTabId } from "./libs/msg";
import { injectInlineJs, injectInternalCss } from "./libs/injector";
import { kissLog } from "./libs/log";
globalThis.ContextType = "BACKGROUND";
const REMOVE_HEADERS = [
`content-security-policy`,
`content-security-policy-report-only`,
`x-webkit-csp`,
`x-content-security-policy`,
];
/**
* 添加右键菜单
*/
@@ -79,6 +89,41 @@ async function addContextMenus(contextMenuType = 1) {
}
}
/**
* 更新CSP策略
* @param {*} csplist
*/
async function updateCspRules(csplist = DEFAULT_CSPLIST.join(",\n")) {
try {
const newRules = csplist
.split(/\n|,/)
.map((url) => url.trim())
.filter(Boolean)
.map((url, idx) => ({
id: idx + 1,
action: {
type: "modifyHeaders",
responseHeaders: REMOVE_HEADERS.map((header) => ({
operation: "remove",
header,
})),
},
condition: {
urlFilter: url,
resourceTypes: ["main_frame", "sub_frame"],
},
}));
const oldRules = await browser.declarativeNetRequest.getDynamicRules();
const oldRuleIds = oldRules.map((rule) => rule.id);
await browser.declarativeNetRequest.updateDynamicRules({
removeRuleIds: oldRuleIds,
addRules: newRules,
});
} catch (err) {
kissLog(err, "update csp rules");
}
}
/**
* 插件安装
*/
@@ -87,6 +132,9 @@ browser.runtime.onInstalled.addListener(() => {
// 右键菜单
addContextMenus();
// 禁用CSP
updateCspRules();
});
/**
@@ -143,8 +191,10 @@ browser.runtime.onMessage.addListener(async ({ action, args }) => {
args: [args],
world: "MAIN",
});
case MSG_UPDATE_CSP:
return await updateCspRules(args);
case MSG_CONTEXT_MENUS:
return await addContextMenus(args.contextMenuType);
return await addContextMenus(args);
case MSG_COMMAND_SHORTCUTS:
return await browser.commands.getAll();
default: