-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
990 lines (900 loc) · 28.1 KB
/
Copy pathbackground.js
File metadata and controls
990 lines (900 loc) · 28.1 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
import {
dnrRegexForMatchPattern,
dnrRegexForUserAgentTargets,
matchesUrl,
normalizeRule,
parseResourceUrl,
permissionPatternFor,
permissionPatternForUserAgentHost,
ruleDisplayName,
ruleHasContent,
ruleHasJavaScript,
ruleHasUserAgent,
selectUserAgentRule,
sortUserAgentRulesByPriority
} from "./rules.mjs";
const RULES_KEY = "rules";
const APPLIED_KEY_PREFIX = "appliedStyles:";
const MATCH_BADGE_COLOR = "#22C55E";
const MATCH_BADGE_TEXT_COLOR = "#FFFFFF";
const USER_AGENT_SCRIPT_ID = "pagepatch-user-agent";
const USER_AGENT_DYNAMIC_RULE_START = 1000000;
const USER_AGENT_DYNAMIC_RULE_END = 1999999;
const USER_AGENT_SESSION_RULE_START = 1500000000;
const USER_AGENT_SESSION_RULE_LIMIT = 1000000;
const USER_AGENT_SESSION_MAP_KEY = "userAgentSessionRuleIds";
const USER_AGENT_CLIENT_HINT_HEADERS = [
"Sec-CH-UA",
"Sec-CH-UA-Arch",
"Sec-CH-UA-Bitness",
"Sec-CH-UA-Form-Factors",
"Sec-CH-UA-Full-Version",
"Sec-CH-UA-Full-Version-List",
"Sec-CH-UA-Mobile",
"Sec-CH-UA-Model",
"Sec-CH-UA-Platform",
"Sec-CH-UA-Platform-Version",
"Sec-CH-UA-WoW64"
];
const tabLocks = new Map();
const tabGenerations = new Map();
let userAgentConfigurationLock = Promise.resolve();
let userAgentSessionLock = Promise.resolve();
function runUserAgentConfigurationTask(task) {
const current = userAgentConfigurationLock
.catch(() => {})
.then(task);
userAgentConfigurationLock = current;
return current;
}
function runUserAgentSessionTask(task) {
const current = userAgentSessionLock
.catch(() => {})
.then(task);
userAgentSessionLock = current;
return current;
}
function appliedKey(tabId) {
return `${APPLIED_KEY_PREFIX}${tabId}`;
}
function cssForRule(rule) {
return rule.css
? `/* page-patch-rule:${rule.id} */\n${rule.css}`
: "";
}
function removePagePatchStyleLinks(ruleId) {
for (const link of document.querySelectorAll("link[data-page-patch-rule]")) {
if (!ruleId || link.dataset.pagePatchRule === ruleId) {
link.remove();
}
}
}
async function insertPagePatchStyleLinks(ruleId, urls) {
for (const link of document.querySelectorAll("link[data-page-patch-rule]")) {
if (link.dataset.pagePatchRule === ruleId) {
link.remove();
}
}
const parent = document.head || document.documentElement;
const pending = urls.map((url, index) => {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
link.dataset.pagePatchRule = ruleId;
link.dataset.pagePatchIndex = String(index);
const loaded = new Promise((resolve) => {
link.addEventListener("load", () => resolve({ url, ok: true }), { once: true });
link.addEventListener("error", () => {
link.remove();
resolve({ url, ok: false });
}, { once: true });
});
parent.appendChild(link);
return loaded;
});
const results = await Promise.all(pending);
return {
loadedUrls: results.filter((result) => result.ok).map((result) => result.url),
failedUrls: results.filter((result) => !result.ok).map((result) => result.url)
};
}
function appendError(errors, message, error, details = {}) {
const detail = error?.message || String(error || "");
const fullMessage = detail ? `${message}: ${detail}` : message;
errors.push({ message: fullMessage, ...details });
console.warn(message, error);
}
async function signatureForRule(rule) {
const input = new TextEncoder().encode(JSON.stringify([rule.jsWorld, rule.jsUrls, rule.js]));
const digest = await crypto.subtle.digest("SHA-256", input);
return [...new Uint8Array(digest)]
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
async function getRules() {
const result = await chrome.storage.local.get(RULES_KEY);
return Array.isArray(result[RULES_KEY])
? result[RULES_KEY].map(normalizeRule)
: [];
}
function userAgentHeaderChanges(userAgent) {
return [
{
operation: "set",
header: "User-Agent",
value: userAgent
},
...USER_AGENT_CLIENT_HINT_HEADERS.map((header) => ({
operation: "remove",
header
}))
];
}
function isUserAgentDynamicRule(rule) {
return rule.id >= USER_AGENT_DYNAMIC_RULE_START
&& rule.id <= USER_AGENT_DYNAMIC_RULE_END;
}
async function grantedUserAgentRules(rules) {
const candidates = rules.filter((rule) =>
rule.id
&& rule.enabled
&& ruleHasUserAgent(rule)
);
const granted = await Promise.all(candidates.map(async (rule) => {
try {
const origin = rule.match ? rule.match : "";
const pattern = origin && permissionPatternFor(origin);
return pattern && await chrome.permissions.contains({ origins: [pattern] });
} catch {
return false;
}
}));
const activeRules = candidates.filter((_rule, index) => granted[index]);
return Promise.all(activeRules.map(async (rule) => {
const hosts = Array.isArray(rule.userAgentHosts) ? rule.userAgentHosts : [];
const hostPermissions = await Promise.all(hosts.map(async (host) => {
try {
return await chrome.permissions.contains({
origins: [permissionPatternForUserAgentHost(host)]
});
} catch {
return false;
}
}));
return {
...rule,
userAgentHosts: hosts.filter((_host, index) => hostPermissions[index])
};
}));
}
function applyPagePatchUserAgent(userAgent) {
const stateKey = Symbol.for("PagePatch.userAgentState");
const prototype = Navigator.prototype;
let state = globalThis[stateKey];
if (!state) {
state = {
userAgent: Object.getOwnPropertyDescriptor(prototype, "userAgent"),
userAgentData: Object.getOwnPropertyDescriptor(prototype, "userAgentData")
};
Object.defineProperty(globalThis, stateKey, {
value: state,
configurable: false,
enumerable: false,
writable: false
});
}
if (!userAgent) {
if (state.userAgent) {
Object.defineProperty(prototype, "userAgent", state.userAgent);
} else {
delete prototype.userAgent;
}
if (state.userAgentData) {
Object.defineProperty(prototype, "userAgentData", state.userAgentData);
} else {
delete prototype.userAgentData;
}
return;
}
Object.defineProperty(prototype, "userAgent", {
configurable: true,
enumerable: state.userAgent?.enumerable ?? true,
get: () => userAgent
});
try {
if (delete prototype.userAgentData) {
return;
}
} catch {
// Fall through to the getter override when deletion is rejected.
}
try {
Object.defineProperty(prototype, "userAgentData", {
configurable: true,
get: () => undefined
});
} catch {
// A non-configurable browser descriptor cannot be hidden without debugger access.
}
}
function installPagePatchUserAgent(entries) {
const url = location.href.split("#", 1)[0];
let userAgent = "";
for (const entry of entries) {
if (new RegExp(entry.regex).test(url)) {
userAgent = entry.userAgent;
}
}
applyPagePatchUserAgent(userAgent);
}
function registeredUserAgentScript(rules) {
const orderedRules = sortUserAgentRulesByPriority(rules);
const entries = orderedRules.map((rule) => ({
regex: dnrRegexForMatchPattern(rule.match),
userAgent: rule.userAgent
}));
return {
id: USER_AGENT_SCRIPT_ID,
matches: [...new Set(orderedRules.map((rule) => rule.match))],
js: [{
code: `${applyPagePatchUserAgent.toString()}\n${installPagePatchUserAgent.toString()}\ninstallPagePatchUserAgent(${JSON.stringify(entries)});`
}],
runAt: "document_start",
world: "MAIN",
allFrames: false
};
}
async function syncRegisteredUserAgentScript(rules) {
if (!chrome.userScripts?.getScripts) {
if (rules.length > 0) {
throw new Error("User Scripts are disabled; User-Agent rules were skipped");
}
return;
}
let existing;
try {
existing = await chrome.userScripts.getScripts({ ids: [USER_AGENT_SCRIPT_ID] });
} catch (error) {
if (rules.length > 0) {
throw error;
}
return;
}
if (rules.length === 0) {
if (existing.length > 0) {
await chrome.userScripts.unregister({ ids: [USER_AGENT_SCRIPT_ID] });
}
return;
}
const script = registeredUserAgentScript(rules);
if (existing.length > 0) {
await chrome.userScripts.update([script]);
} else {
await chrome.userScripts.register([script]);
}
}
async function syncDynamicUserAgentRules(rules) {
const existing = await chrome.declarativeNetRequest.getDynamicRules();
const removeRuleIds = existing.filter(isUserAgentDynamicRule).map((rule) => rule.id);
const orderedRules = sortUserAgentRulesByPriority(rules);
const addRules = orderedRules.map((rule, index) => ({
id: USER_AGENT_DYNAMIC_RULE_START + index,
priority: index + 1,
action: {
type: "modifyHeaders",
requestHeaders: userAgentHeaderChanges(rule.userAgent)
},
condition: {
regexFilter: dnrRegexForMatchPattern(rule.match),
isUrlFilterCaseSensitive: true,
resourceTypes: ["main_frame"]
}
}));
await chrome.declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules });
}
async function synchronizeUserAgentConfiguration(rules) {
return runUserAgentConfigurationTask(async () => {
const currentRules = rules ?? await getRules();
const activeRules = await grantedUserAgentRules(currentRules);
try {
await syncRegisteredUserAgentScript(activeRules);
} catch (error) {
await syncDynamicUserAgentRules([]);
throw error;
}
await syncDynamicUserAgentRules(activeRules);
return activeRules;
});
}
async function getUserAgentSessionRuleMap() {
const stored = await chrome.storage.session.get(USER_AGENT_SESSION_MAP_KEY);
const value = stored[USER_AGENT_SESSION_MAP_KEY];
if (!value || typeof value !== "object" || Array.isArray(value)) {
return {};
}
return Object.fromEntries(Object.entries(value).filter(([_tabId, ruleId]) =>
Number.isInteger(ruleId)
&& ruleId >= USER_AGENT_SESSION_RULE_START
&& ruleId < USER_AGENT_SESSION_RULE_START + USER_AGENT_SESSION_RULE_LIMIT
));
}
async function setUserAgentSessionRuleMap(map) {
await chrome.storage.session.set({ [USER_AGENT_SESSION_MAP_KEY]: map });
}
function allocateUserAgentSessionRuleId(map, tabId) {
const existing = map[tabId];
if (Number.isInteger(existing)) {
return existing;
}
const used = new Set(Object.values(map));
const start = Math.abs(tabId) % USER_AGENT_SESSION_RULE_LIMIT;
for (let offset = 0; offset < USER_AGENT_SESSION_RULE_LIMIT; offset += 1) {
const id = USER_AGENT_SESSION_RULE_START
+ ((start + offset) % USER_AGENT_SESSION_RULE_LIMIT);
if (!used.has(id)) {
return id;
}
}
throw new Error("No User-Agent session rule IDs are available");
}
async function removeTabUserAgentRule(tabId) {
return runUserAgentSessionTask(async () => {
const map = await getUserAgentSessionRuleMap();
const ruleId = map[tabId];
if (!Number.isInteger(ruleId)) {
return false;
}
await chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: [ruleId]
});
delete map[tabId];
await setUserAgentSessionRuleMap(map);
return true;
});
}
async function syncTabUserAgent(tabId, tab, rules, applyToPage = true) {
const url = tab?.pendingUrl || tab?.url || "";
const selected = selectUserAgentRule(rules, url);
const userAgent = await runUserAgentSessionTask(async () => {
const map = await getUserAgentSessionRuleMap();
const previousRuleId = map[tabId];
const removeRuleIds = Number.isInteger(previousRuleId) ? [previousRuleId] : [];
if (!selected) {
if (removeRuleIds.length > 0) {
await chrome.declarativeNetRequest.updateSessionRules({ removeRuleIds });
delete map[tabId];
await setUserAgentSessionRuleMap(map);
}
return "";
}
const ruleId = allocateUserAgentSessionRuleId(map, tabId);
map[tabId] = ruleId;
await chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds,
addRules: [{
id: ruleId,
priority: 1,
action: {
type: "modifyHeaders",
requestHeaders: userAgentHeaderChanges(selected.userAgent)
},
condition: {
tabIds: [tabId],
regexFilter: dnrRegexForUserAgentTargets(url, selected.userAgentHosts),
isUrlFilterCaseSensitive: true,
excludedResourceTypes: ["main_frame"]
}
}]
});
await setUserAgentSessionRuleMap(map);
return selected.userAgent;
});
if (applyToPage && /^https?:\/\//.test(url)) {
await chrome.scripting.executeScript({
target: { tabId },
world: "MAIN",
injectImmediately: true,
func: applyPagePatchUserAgent,
args: [userAgent]
});
}
return userAgent;
}
async function synchronizeOpenTabUserAgents(rules, applyToPage = true) {
const tabs = await chrome.tabs.query({});
const openTabIds = new Set(tabs.map((tab) => String(tab.id)));
await runUserAgentSessionTask(async () => {
const map = await getUserAgentSessionRuleMap();
const staleEntries = Object.entries(map)
.filter(([tabId]) => !openTabIds.has(tabId));
if (staleEntries.length === 0) {
return;
}
await chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: staleEntries.map(([_tabId, ruleId]) => ruleId)
});
staleEntries.forEach(([tabId]) => delete map[tabId]);
await setUserAgentSessionRuleMap(map);
});
for (const tab of tabs) {
await syncTabUserAgent(tab.id, tab, rules, applyToPage);
}
}
async function countUserAgentReloadRequired(previousRules, currentRules) {
if (!Array.isArray(previousRules)) {
return 0;
}
const previous = previousRules.map(normalizeRule);
const tabs = await chrome.tabs.query({});
return tabs.filter((tab) => {
const url = tab.url || tab.pendingUrl || "";
const oldRule = selectUserAgentRule(previous, url);
const newRule = selectUserAgentRule(currentRules, url);
const oldValue = JSON.stringify([
oldRule?.userAgent || "",
oldRule?.userAgentHosts || []
]);
const newValue = JSON.stringify([
newRule?.userAgent || "",
newRule?.userAgentHosts || []
]);
return oldValue !== newValue;
}).length;
}
function normalizeAppliedState(value) {
// Migrate the previous CSS-only session format without touching persistent
// rules. A full navigation will naturally replace these snapshots.
if (Array.isArray(value)) {
return {
styles: value.filter((item) => item?.id && item?.injectedCss),
scripts: []
};
}
return {
styles: Array.isArray(value?.styles) ? value.styles : [],
scripts: Array.isArray(value?.scripts) ? value.scripts : []
};
}
async function getApplied(tabId) {
const key = appliedKey(tabId);
const result = await chrome.storage.session.get(key);
return normalizeAppliedState(result[key]);
}
async function setApplied(tabId, state) {
const key = appliedKey(tabId);
if (state.styles.length === 0 && state.scripts.length === 0) {
await chrome.storage.session.remove(key);
return;
}
await chrome.storage.session.set({ [key]: state });
}
async function clearApplied(tabId) {
await chrome.storage.session.remove(appliedKey(tabId));
}
async function updateMatchBadge(tabId, matchCount) {
const text = matchCount > 0 ? String(matchCount) : "";
try {
if (text) {
await chrome.action.setBadgeBackgroundColor({
color: MATCH_BADGE_COLOR,
tabId
});
await chrome.action.setBadgeTextColor({
color: MATCH_BADGE_TEXT_COLOR,
tabId
});
}
await chrome.action.setBadgeText({
text,
tabId
});
} catch (error) {
console.warn("Could not update match badge", error);
}
}
async function removeStyleLinks(tabId, ruleId, errors) {
try {
await chrome.scripting.executeScript({
target: { tabId },
func: removePagePatchStyleLinks,
args: [ruleId]
});
} catch (error) {
appendError(errors, `Could not remove CSS links for rule ${ruleId}`, error);
}
}
async function clearAllStyleLinks(tabId, errors) {
try {
await chrome.scripting.executeScript({
target: { tabId },
func: removePagePatchStyleLinks,
args: [null]
});
} catch (error) {
appendError(errors, "Could not clear old CSS links", error);
}
}
async function removeStyle(tabId, snapshot, errors) {
if (snapshot.injectedCss) {
try {
await chrome.scripting.removeCSS({
target: { tabId },
css: snapshot.injectedCss,
origin: "AUTHOR"
});
} catch (error) {
appendError(errors, `Could not remove CSS rule ${snapshot.id}`, error);
}
}
if (snapshot.linkUrls?.length > 0) {
await removeStyleLinks(tabId, snapshot.id, errors);
}
}
async function insertStyle(tabId, rule, errors) {
const css = cssForRule(rule);
let injectedCss = "";
let loadedLinkUrls = [];
if (rule.cssUrls.length > 0) {
try {
const results = await chrome.scripting.executeScript({
target: { tabId },
func: insertPagePatchStyleLinks,
args: [rule.id, rule.cssUrls]
});
const result = results[0]?.result || { loadedUrls: [], failedUrls: rule.cssUrls };
for (const url of result.failedUrls) {
appendError(
errors,
`Could not load CSS links for rule ${rule.id}`,
new Error(url),
{
code: "cssLinkLoadFailed",
rule: ruleDisplayName(rule),
url
}
);
}
loadedLinkUrls = result.loadedUrls;
} catch (error) {
appendError(errors, `Could not inject CSS links for rule ${rule.id}`, error);
}
}
if (css) {
try {
await chrome.scripting.insertCSS({
target: { tabId },
css,
origin: "AUTHOR"
});
injectedCss = css;
} catch (error) {
appendError(errors, `Could not inject CSS rule ${rule.id}`, error);
}
}
return loadedLinkUrls.length > 0 || injectedCss
? { id: rule.id, linkUrls: loadedLinkUrls, injectedCss }
: null;
}
function stylesAreEqual(previous, desired) {
return previous.length === desired.length
&& previous.every((snapshot, index) =>
snapshot.id === desired[index].id
&& snapshot.injectedCss === desired[index].injectedCss
&& JSON.stringify(snapshot.linkUrls || []) === JSON.stringify(desired[index].linkUrls)
);
}
async function reconcileStyles(tabId, previous, desiredRules, errors) {
const desired = desiredRules
.map((rule) => ({
id: rule.id,
linkUrls: [...rule.cssUrls],
injectedCss: cssForRule(rule),
rule
}))
.filter((item) => item.linkUrls.length > 0 || item.injectedCss);
if (stylesAreEqual(previous, desired)) {
return previous;
}
for (const snapshot of previous) {
await removeStyle(tabId, snapshot, errors);
}
await clearAllStyleLinks(tabId, errors);
const inserted = [];
for (const item of desired) {
const snapshot = await insertStyle(tabId, item.rule, errors);
if (snapshot) {
inserted.push(snapshot);
}
}
return inserted;
}
function withSourceUrl(code, sourceUrl) {
return `${code}\n//# sourceURL=${sourceUrl.replace(/[\r\n]/g, "")}`;
}
async function scriptSourcesFor(rule, errors) {
const sources = [];
for (const value of rule.jsUrls) {
const url = parseResourceUrl(value);
try {
const response = await fetch(url, { cache: "default" });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const code = await response.text();
sources.push({
kind: "link",
label: url,
url,
js: { code: withSourceUrl(code, url) }
});
} catch (error) {
appendError(
errors,
`Could not fetch JS URL for rule ${rule.id}: ${url}`,
error,
{
code: "jsLinkFetchFailed",
rule: ruleDisplayName(rule),
url,
reason: error?.message || String(error)
}
);
}
}
if (rule.js) {
sources.push({
kind: "inline",
label: `inline JavaScript for rule ${rule.id}`,
js: { code: withSourceUrl(rule.js, `page-patch-rule-${rule.id}.user.js`) }
});
}
return sources;
}
async function executeRuleScript(tabId, rule, isCurrentDocument, errors) {
if (!chrome.userScripts?.execute) {
appendError(errors, "User Scripts are disabled; JavaScript rules were skipped");
return false;
}
const sources = await scriptSourcesFor(rule, errors);
if (sources.length === 0 || !isCurrentDocument()) {
return false;
}
let attempted = false;
for (const source of sources) {
if (!isCurrentDocument()) {
break;
}
attempted = true;
try {
const results = await chrome.userScripts.execute({
target: { tabId },
js: [source.js],
world: rule.jsWorld,
injectImmediately: true
});
const failures = results.filter((result) => result.error);
if (failures.length > 0) {
throw new Error(failures.map((result) => result.error).join("; "));
}
} catch (error) {
appendError(
errors,
`Could not execute ${source.label}`,
error,
source.kind === "link"
? {
code: "jsLinkExecuteFailed",
rule: ruleDisplayName(rule),
url: source.url,
reason: error?.message || String(error)
}
: {
code: "customJsExecuteFailed",
rule: ruleDisplayName(rule),
reason: error?.message || String(error)
}
);
}
}
return attempted;
}
async function reconcileScripts(tabId, previous, allRules, desiredRules, isCurrentDocument, errors) {
const currentJsIds = new Set(
allRules.filter((rule) => rule.id && ruleHasJavaScript(rule)).map((rule) => rule.id)
);
const executedById = new Map(
previous
.filter((snapshot) => currentJsIds.has(snapshot.id))
.map((snapshot) => [snapshot.id, snapshot])
);
for (const rule of desiredRules) {
if (!isCurrentDocument()) {
break;
}
if (!ruleHasJavaScript(rule)) {
continue;
}
const signature = await signatureForRule(rule);
if (executedById.get(rule.id)?.signature === signature) {
continue;
}
if (await executeRuleScript(tabId, rule, isCurrentDocument, errors)) {
executedById.set(rule.id, { id: rule.id, signature });
}
}
return allRules
.filter((rule) => executedById.has(rule.id))
.map((rule) => executedById.get(rule.id));
}
async function reconcileTabUnlocked(tabId, suppliedTab) {
const generation = tabGenerations.get(tabId) || 0;
const isCurrentDocument = () => (tabGenerations.get(tabId) || 0) === generation;
let tab = suppliedTab;
try {
tab ??= await chrome.tabs.get(tabId);
} catch {
await clearApplied(tabId);
return;
}
const previous = await getApplied(tabId);
const url = tab.url || tab.pendingUrl || "";
const errors = [];
const rules = await getRules();
const desiredRules = rules.filter((rule) =>
rule.id
&& rule.enabled
&& ruleHasContent(rule)
&& matchesUrl(rule.match, url)
);
await updateMatchBadge(tabId, desiredRules.length);
const styles = await reconcileStyles(tabId, previous.styles, desiredRules, errors);
const scripts = await reconcileScripts(
tabId,
previous.scripts,
rules,
desiredRules,
isCurrentDocument,
errors
);
if (!isCurrentDocument()) {
return;
}
await setApplied(tabId, { styles, scripts });
if (errors.length > 0) {
const error = new Error(`${url}\n${errors.map((item) => item.message).join("\n")}`);
error.issues = errors.map((item) => ({ ...item, tabUrl: url }));
throw error;
}
}
function runTabTask(tabId, task) {
const previous = tabLocks.get(tabId) || Promise.resolve();
const current = previous
.catch(() => {})
.then(task);
tabLocks.set(tabId, current);
const cleanup = () => {
if (tabLocks.get(tabId) === current) {
tabLocks.delete(tabId);
}
};
void current.then(cleanup, cleanup);
return current;
}
function reconcileTab(tabId, suppliedTab) {
return runTabTask(tabId, () => reconcileTabUnlocked(tabId, suppliedTab));
}
function reconcileTabUserAgent(tabId, suppliedTab, applyToPage = true) {
return runTabTask(tabId, async () => {
let tab = suppliedTab;
try {
tab ??= await chrome.tabs.get(tabId);
} catch {
await removeTabUserAgentRule(tabId);
return;
}
const rules = await getRules();
const activeRules = await grantedUserAgentRules(rules);
await syncTabUserAgent(tabId, tab, activeRules, applyToPage);
});
}
function resetTab(tabId, clearBadge = true) {
return runTabTask(tabId, async () => {
await clearApplied(tabId);
if (clearBadge) {
await updateMatchBadge(tabId, 0);
}
});
}
async function reconcileAllTabs() {
const tabs = await chrome.tabs.query({});
const results = await Promise.allSettled(tabs.map((tab) => reconcileTab(tab.id, tab)));
const failures = results
.filter((result) => result.status === "rejected")
.map((result) => result.reason);
if (failures.length > 0) {
const error = new Error(
failures.map((failure) => failure?.message || String(failure)).join("\n\n")
);
error.issues = failures.flatMap((failure) => failure?.issues || []);
throw error;
}
}
async function initializeRuntime() {
const rules = await getRules();
try {
const activeUserAgentRules = await synchronizeUserAgentConfiguration(rules);
await synchronizeOpenTabUserAgents(activeUserAgentRules);
} catch (error) {
console.warn("Could not initialize User-Agent rules", error);
}
await reconcileAllTabs();
}
chrome.action.onClicked.addListener(() => {
chrome.runtime.openOptionsPage();
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "loading") {
// A full navigation discards injected content with the old document.
tabGenerations.set(tabId, (tabGenerations.get(tabId) || 0) + 1);
void updateMatchBadge(tabId, 0);
void reconcileTabUserAgent(tabId, tab, false)
.catch((error) => console.warn("Could not prepare tab User-Agent", error));
void resetTab(tabId).catch((error) => console.warn("Could not reset tab state", error));
return;
}
if (changeInfo.status === "complete" || (changeInfo.url && tab.status === "complete")) {
void reconcileTabUserAgent(tabId, tab)
.catch((error) => console.warn("Could not reconcile tab User-Agent", error));
void reconcileTab(tabId, tab).catch((error) => console.warn("Could not reconcile tab", error));
}
});
chrome.tabs.onRemoved.addListener((tabId) => {
tabGenerations.set(tabId, (tabGenerations.get(tabId) || 0) + 1);
void runTabTask(tabId, async () => {
await clearApplied(tabId);
await removeTabUserAgentRule(tabId);
})
.catch((error) => console.warn("Could not clear closed tab state", error))
.finally(() => tabGenerations.delete(tabId));
});
chrome.runtime.onStartup.addListener(() => {
void initializeRuntime().catch((error) =>
console.warn("Could not initialize tabs at startup", error)
);
});
chrome.runtime.onInstalled.addListener(() => {
void initializeRuntime().catch((error) =>
console.warn("Could not initialize tabs after installation", error)
);
});
function handleHostPermissionsChanged() {
void synchronizeUserAgentConfiguration()
.then((activeRules) => synchronizeOpenTabUserAgents(activeRules))
.catch((error) => console.warn("Could not refresh User-Agent permissions", error));
}
chrome.permissions.onAdded.addListener(handleHostPermissionsChanged);
chrome.permissions.onRemoved.addListener(handleHostPermissionsChanged);
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type !== "rules-changed") {
return undefined;
}
const previousRules = message.previousRules;
getRules()
.then(async (rules) => {
const activeUserAgentRules = await synchronizeUserAgentConfiguration(rules);
const uaReloadRequiredCount = await countUserAgentReloadRequired(previousRules, rules);
await synchronizeOpenTabUserAgents(activeUserAgentRules);
await reconcileAllTabs();
return uaReloadRequiredCount;
})
.then((uaReloadRequiredCount) => sendResponse({
ok: true,
uaReloadRequiredCount
}))
.catch((error) => sendResponse({
ok: false,
error: error.message,
issues: error.issues || []
}));
return true;
});