-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
203 lines (176 loc) · 5.39 KB
/
Copy pathbackground.js
File metadata and controls
203 lines (176 loc) · 5.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
const RULE_ID = 1;
const RULE_TYPES = [
"main_frame",
"sub_frame",
"xmlhttprequest",
"script",
"image",
"stylesheet",
"font",
"media",
"ping",
"object",
"other"
];
const MATCH_TYPES = ["all", "domain", "regex", "prefix"];
const defaults = {
enabled: true,
lang: "auto",
activeGroupId: "default",
groups: [
{
id: "default",
name: "debug",
matchType: "all",
matchValue: "",
headers: [{ name: "", value: "" }]
}
]
};
const HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
const LANGS = ["auto", "en", "zh"];
chrome.runtime.onInstalled.addListener(async () => {
const state = await getState();
await chrome.storage.local.set(state);
await applyActiveGroup(state);
});
chrome.runtime.onStartup.addListener(applyActiveGroup);
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
(async () => {
if (message?.type === "saveState") {
const state = await saveState(message.state);
await applyActiveGroup(state);
sendResponse();
return;
}
sendResponse(await getState());
})();
return true;
});
async function getState() {
return normalizeState(await chrome.storage.local.get(defaults));
}
async function saveState(next) {
const state = normalizeState(next);
await chrome.storage.local.set(state);
return state;
}
function normalizeState(state = defaults) {
const groups = normalizeGroups(state.groups);
const activeGroupId = groups.some(group => group.id === state.activeGroupId) ? state.activeGroupId : groups[0].id;
return {
enabled: state.enabled !== false,
lang: normalizeLang(state.lang),
activeGroupId,
groups
};
}
function normalizeGroups(groups) {
const cleaned = (Array.isArray(groups) ? groups : [])
.map(group => ({
id: group.id || crypto.randomUUID(),
name: String(group.name || "Group").trim().slice(0, 24) || "Group",
matchType: normalizeMatchType(group.matchType),
matchValue: String(group.matchValue ?? "").trim(),
headers: (Array.isArray(group.headers) ? group.headers : []).map(header => ({
name: String(header.name ?? ""),
value: String(header.value ?? "")
}))
}));
return cleaned.length ? cleaned : defaults.groups;
}
async function applyActiveGroup(nextState) {
const state = nextState || (await getState());
const group = activeGroup(state);
const rule = buildRule(state, group);
let ruleError = false;
try {
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [RULE_ID],
addRules: rule ? [rule] : []
});
} catch {
await chrome.declarativeNetRequest.updateDynamicRules({ removeRuleIds: [RULE_ID] });
ruleError = true;
}
const action = buildAction(state, group, rule, ruleError);
await Promise.all([
chrome.action.setBadgeText({ text: action.text }),
chrome.action.setBadgeBackgroundColor({ color: action.color }),
chrome.action.setTitle({ title: action.title })
]);
}
function buildRule(state, group = activeGroup(state)) {
if (!state.enabled) return null;
const requestHeaders = buildRequestHeaders(group.headers);
const condition = buildCondition(group);
if (!requestHeaders.length || !condition) return null;
return {
id: RULE_ID,
priority: 1,
action: {
type: "modifyHeaders",
requestHeaders
},
condition
};
}
function buildRequestHeaders(headers) {
const unique = new Map();
for (const header of headers) {
if (!HEADER_NAME_RE.test(header.name)) continue;
unique.set(header.name.toLowerCase(), {
header: header.name,
operation: "set",
value: header.value
});
}
return [...unique.values()];
}
function buildAction(state, group, rule, ruleError) {
return {
text: ruleError ? "!" : state.enabled ? badgeText(group.name) : "OFF",
color: ruleError ? "#dc2626" : rule ? "#2563eb" : "#64748b",
title: `HeaderHack: ${state.enabled ? group.name : offText(state.lang)}`
};
}
function buildCondition(group) {
const resourceTypes = RULE_TYPES;
const value = String(group.matchValue || "").trim();
if (group.matchType === "all") return { resourceTypes };
if (!value) return null;
if (group.matchType === "domain") {
const domain = normalizeDomain(value);
return domain ? { requestDomains: [domain], resourceTypes } : null;
}
const regexFilter = group.matchType === "prefix" ? `^${escapeRegex(value)}` : value;
return { regexFilter, isUrlFilterCaseSensitive: true, resourceTypes };
}
function normalizeDomain(value) {
try {
const url = new URL(value.includes("://") ? value : `https://${value}`);
const hostname = url.hostname.toLowerCase().replace(/^\*\./, "").replace(/\.$/, "");
return hostname.includes("*") ? "" : hostname;
} catch {
return "";
}
}
function escapeRegex(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function badgeText(name) {
return Array.from(String(name || "?").trim()).slice(0, 3).join("") || "?";
}
function activeGroup(state) {
return state.groups.find(group => group.id === state.activeGroupId) || state.groups[0];
}
function normalizeLang(lang) {
return LANGS.includes(lang) ? lang : "auto";
}
function normalizeMatchType(type) {
return MATCH_TYPES.includes(type) ? type : "all";
}
function offText(lang) {
const locale = lang === "zh" || (lang === "auto" && chrome.i18n.getUILanguage().startsWith("zh")) ? "zh" : "en";
return locale === "zh" ? "已关闭" : "Off";
}