-
Notifications
You must be signed in to change notification settings - Fork 323
Expand file tree
/
Copy pathruntime.ts
More file actions
1459 lines (1334 loc) · 52.4 KB
/
runtime.ts
File metadata and controls
1459 lines (1334 loc) · 52.4 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
991
992
993
994
995
996
997
998
999
1000
import type { EmitEventRequest, ScriptLoadInfo, ScriptMatchInfo, ScriptMenu } from "./types";
import type { IMessageQueue } from "@Packages/message/message_queue";
import type { Group, IGetSender } from "@Packages/message/server";
import type { ExtMessageSender, MessageSend } from "@Packages/message/types";
import { ScriptCodeDAONew, type TClientPageLoadInfo } from "@App/app/repo/scripts";
import type { Script, ScriptDAO, ScriptRunResource, ScriptSite, TScriptInfo } from "@App/app/repo/scripts";
import { SCRIPT_STATUS_DISABLE, SCRIPT_STATUS_ENABLE, SCRIPT_TYPE_NORMAL } from "@App/app/repo/scripts";
import { type ValueService } from "./value";
import GMApi, { GMExternalDependencies } from "./gm_api/gm_api";
import type { TDeleteScript, TEnableScript, TInstallScript, TScriptValueUpdate, TSortedScript } from "../queue";
import { type ScriptService } from "./script";
import { runScript, stopScript } from "../offscreen/client";
import {
buildScriptRunResourceBasic,
compileInjectionCode,
getUserScriptRegister,
scriptURLPatternResults,
} from "./utils";
import {
checkUserScriptsAvailable,
getMetadataStr,
getUserConfigStr,
obtainBlackList,
sourceMapTo,
} from "@App/pkg/utils/utils";
import { BrowserType, getBrowserInstalledVersion, getBrowserType, isPermissionOk } from "@App/pkg/utils/utils";
import { cacheInstance } from "@App/app/cache";
import { UrlMatch } from "@App/pkg/utils/match";
import { ExtensionContentMessageSend } from "@Packages/message/extension_message";
import { sendMessage } from "@Packages/message/client";
import type { CompileScriptCodeResource } from "../content/utils";
import {
compileInjectScriptByFlag,
compileScriptCodeByResource,
compileScriptletCode,
isEarlyStartScript,
isInjectIntoContent,
isScriptletUnwrap,
trimScriptInfo,
} from "../content/utils";
import LoggerCore from "@App/app/logger/core";
import PermissionVerify from "./permission_verify";
import { type SystemConfig } from "@App/pkg/config/config";
import { type ResourceService } from "./resource";
import { type LocalStorageDAO } from "@App/app/repo/localStorage";
import Logger from "@App/app/logger/logger";
import type { GMInfoEnv } from "../content/types";
import { initLocalesPromise, localePath } from "@App/locales/locales";
import { DocumentationSite } from "@App/app/const";
import { extractUrlPatterns, RuleType, type URLRuleEntry } from "@App/pkg/utils/url_matcher";
import { parseUserConfig } from "@App/pkg/utils/yaml";
import type { CompiledResource, ResourceType } from "@App/app/repo/resource";
import { CompiledResourceDAO } from "@App/app/repo/resource";
import { setOnTabURLChanged } from "./url_monitor";
import { scriptToMenu, type TPopupPageLoadInfo } from "./popup_scriptmenu";
const ORIGINAL_URLMATCH_SUFFIX = "{ORIGINAL}"; // 用于标记原始URLPatterns的后缀
const RuntimeRegisterCode = {
UNSET: 0,
REGISTER_DONE: 1,
UNREGISTER_DONE: 2,
} as const;
type RuntimeRegisterCode = ValueOf<typeof RuntimeRegisterCode>;
const runtimeGlobal = {
registerState: RuntimeRegisterCode.UNSET,
messageFlag: "PENDING",
} as {
registerState: RuntimeRegisterCode;
messageFlag: string;
};
export type TTabInfo = {
url: string;
tabId: number | undefined;
frameId: number | undefined;
};
export type TScriptsForTab = {
injectScriptList: TScriptInfo[];
contentScriptList: TScriptInfo[];
envInfo: GMInfoEnv;
scriptmenus: ScriptMenu[];
} | null;
export class RuntimeService {
scriptMatchEnable: UrlMatch<string> = new UrlMatch<string>();
scriptMatchDisable: UrlMatch<string> = new UrlMatch<string>();
blackMatch: UrlMatch<string> = new UrlMatch<string>();
logger: Logger;
// 当前扩充是否允许执行 UserScripts API (例如是否已打开开发者模式,或已给予 userScripts 权限)
// 在未初始化前,预设 false。一般情况初始化值会很快被替换
isUserScriptsAvailable = false;
// 当前扩充是否开启了启用脚本
// 在未初始化前,预设 true。一般情况初始化值会很快被替换
isLoadScripts = true;
// 当前扩充的userAgentData
// 在未初始化前,预设 {}。一般情况初始化值会很快被替换
// 注意:即使没有使用 Object.freeze, 也不应该直接修改物件内容 (immutable)
userAgentData: typeof GM_info.userAgentData = {};
// 当前扩充的blacklist
// 在未初始化前,预设 []。一般情况初始化值会很快被替换
// 注意:即使没有使用 Object.freeze, 也不应该直接修改阵列内容 (immutable)
blacklist: string[] = [];
blacklistExcludeMatches: string[] = [];
blacklistExcludeGlobs: string[] = [];
// 获取inject.js内容时调用,需要预先调用preInject
injectJsCodePromise: Promise<string | undefined> | null = null;
contentJsCodePromise: Promise<string | undefined> | null = null;
// initReady
initReady: Promise<boolean> | boolean = false;
mq: IMessageQueue;
sitesLoaded: Set<string> = new Set<string>();
updateSitesBusy: boolean = false;
loadingInitProcessPromise: Promise<any> | undefined;
initialCompiledResourcePromise: Promise<any> | undefined;
compiledResourceDAO: CompiledResourceDAO = new CompiledResourceDAO();
private readonly scriptCodeDAO: ScriptCodeDAONew = new ScriptCodeDAONew();
constructor(
private systemConfig: SystemConfig,
private group: Group,
private msgSender: MessageSend,
mq: IMessageQueue,
private value: ValueService,
public script: ScriptService,
private resource: ResourceService,
private scriptDAO: ScriptDAO,
private localStorageDAO: LocalStorageDAO
) {
this.logger = LoggerCore.logger({ component: "runtime" });
// 使用中间件
this.group = this.group.use(async (_, __, next) => {
if (typeof this.initReady !== "boolean") await this.initReady;
return next();
});
this.mq = mq.group("", async (_, __, next) => {
if (typeof this.initReady !== "boolean") await this.initReady;
return next();
});
}
async initUserAgentData() {
// @ts-ignore
const userAgentData = navigator.userAgentData;
if (userAgentData) {
this.userAgentData = {
brands: userAgentData.brands,
mobile: userAgentData.mobile,
platform: userAgentData.platform,
};
// 处理architecture和bitness
if (chrome.runtime.getPlatformInfo) {
try {
const platformInfo = await chrome.runtime.getPlatformInfo();
this.userAgentData.architecture = platformInfo.nacl_arch;
this.userAgentData.bitness = platformInfo.arch.includes("64") ? "64" : "32";
} catch (e) {
// 避免 API 无法执行的问题。不影响整体运作
console.warn(e);
}
}
}
}
async showUserscriptActivationGuide() {
const storageKey = "firstShowDeveloperMode";
chrome.action.setBadgeBackgroundColor({
color: "#ff8c00",
});
chrome.action.setBadgeTextColor({
color: "#ffffff",
});
chrome.action.setBadgeText({
text: "!",
});
chrome.permissions.onAdded.addListener((permissions: chrome.permissions.Permissions) => {
const lastError = chrome.runtime.lastError;
if (lastError) {
console.error("chrome.runtime.lastError in chrome.permissions.onAdded:", lastError);
return;
}
if (permissions.permissions?.includes("userScripts")) {
chrome.action.setBadgeBackgroundColor({
color: [0, 0, 0, 0], // transparent (RGBA)
});
chrome.action.setBadgeTextColor({
color: "#ffffff", // default is white
});
chrome.action.setBadgeText({
text: "", // clears badge
});
}
});
const currentInstalledBrowser = getBrowserInstalledVersion();
const lastInstalledBrowser = (await this.localStorageDAO.get(storageKey))?.value as string | boolean | undefined;
// 判断是否安装后的首次,或是浏览器升级后的首次
if (currentInstalledBrowser === lastInstalledBrowser) return; // 非首次则不弹出页面
const savePromise = this.localStorageDAO.save({
key: storageKey,
value: currentInstalledBrowser,
});
await Promise.allSettled([initLocalesPromise, this.initReady, savePromise]); // 等一下语言加载和 isUserScriptsAvailable 检查之类的
const userscript_enabled: boolean = this.isUserScriptsAvailable;
const permission = await isPermissionOk("userScripts");
const browserType = getBrowserType();
const guard =
browserType.chrome & BrowserType.guardedByDeveloperMode
? "developerMode"
: browserType.chrome & BrowserType.guardedByAllowScript
? "allowScript"
: "none";
// 打开页面
const path = `${DocumentationSite}${localePath}/docs/use/open-dev/`;
let search = `?userscript_enabled=${userscript_enabled}&userscript_permission=${permission}&userscript_guard=${guard}`;
if (browserType.chrome & BrowserType.Edge) search += "&browser=edge";
else if (browserType.chrome & BrowserType.Chrome) search += "&browser=chrome";
const hash = `${guard === "developerMode" ? "#enable-developer-mode" : guard === "allowScript" ? "#allow-user-scripts" : ""}`;
chrome.tabs.create({ url: `${path}${search}${hash}` });
}
async getInjectJsCode() {
if (!this.injectJsCodePromise) {
this.injectJsCodePromise = fetch("/src/inject.js")
.then((res) => res.text())
.catch((e) => {
console.error("Unable to fetch /src/inject.js", e);
return undefined;
});
}
return this.injectJsCodePromise;
}
async getContentJsCode() {
if (!this.contentJsCodePromise) {
this.contentJsCodePromise = fetch("/src/content.js")
.then((res) => res.text())
.catch((e) => {
console.error("Unable to fetch /src/content.js", e);
return undefined;
});
}
return this.contentJsCodePromise;
}
createMatchInfoEntry(
scriptRes: ScriptRunResource,
o: { scriptUrlPatterns: URLRuleEntry[]; originalUrlPatterns: URLRuleEntry[] | null }
) {
// 优化性能,将不需要的信息去掉
// 而且可能会超过缓存的存储限制
const matchInfo = {
...scriptRes,
scriptUrlPatterns: o.scriptUrlPatterns,
originalUrlPatterns: o.originalUrlPatterns === null ? o.scriptUrlPatterns : o.originalUrlPatterns,
code: "",
value: {},
resource: {},
} as ScriptMatchInfo;
return matchInfo;
}
async waitInit() {
const [cRuntimeStartFlag, compiledResources, allScripts] = await Promise.all([
cacheInstance.get<boolean>("runtimeStartFlag"),
this.compiledResourceDAO.all(),
this.scriptDAO.all(),
]);
const unregisterScriptIds = [] as string[];
// 没有 CompiledResources 表示这是 没有启用脚本 或 代码有改变需要重新安装。
// 这个情况会把所有有效脚本跟Inject&Content脚本先取消注册。后续载入时会重新以新代码注册。
const cleanUpPreviousRegister = !compiledResources.length;
this.initialCompiledResourcePromise = Promise.all(
allScripts.map(async (script) => {
const uuid = script.uuid;
const isNormalScript = script.type === SCRIPT_TYPE_NORMAL;
const enable = script.status === SCRIPT_STATUS_ENABLE;
if (!isNormalScript || !enable) {
// 确保浏览器没有残留 PageScripts
if (uuid) unregisterScriptIds.push(uuid);
} else if (cleanUpPreviousRegister) {
// CompiledResourceNamespace 修改后先反注册残留脚本,之后再重新加载 PageScripts
if (uuid) unregisterScriptIds.push(uuid);
}
if (isNormalScript) {
let compiledResource = await this.compiledResourceDAO.get(uuid);
if (!compiledResource) {
const ret = await this.buildAndSaveCompiledResourceFromScript(script, false);
if (!ret) return;
compiledResource = ret?.compiledResource;
}
if (!compiledResource?.scriptUrlPatterns) {
this.logger.error("No compiledResource or scriptUrlPatterns found", { uuid });
return;
}
const { scriptUrlPatterns, originalUrlPatterns } = compiledResource;
const uuidOri = `${uuid}${ORIGINAL_URLMATCH_SUFFIX}`;
// 添加新的数据
const scriptMatch = enable ? this.scriptMatchEnable : this.scriptMatchDisable;
scriptMatch.addRules(uuid, scriptUrlPatterns);
if (originalUrlPatterns !== null && originalUrlPatterns !== scriptUrlPatterns) {
scriptMatch.addRules(uuidOri, originalUrlPatterns);
}
}
})
);
if (cleanUpPreviousRegister) {
// 先反注册残留脚本
unregisterScriptIds.push(
// 兼容旧的注册ID,过渡期后可移除
"scriptcat-early-start-flag",
"scriptcat-inject",
"scriptcat-content"
);
}
if (unregisterScriptIds.length) {
// 忽略 UserScripts API 无法执行
await Promise.allSettled([this.unregistryPageScripts(unregisterScriptIds, true)]); // ignore success or fail
}
if (!cRuntimeStartFlag) {
await cacheInstance.set<boolean>("runtimeStartFlag", true);
}
let count = 0;
try {
const res = await chrome.userScripts?.getScripts({ ids: ["scriptcat-inject"] });
count = res?.length;
} catch {
// 该错误为预期内情况,无需记录 debug 日志
} finally {
// 考虑 UserScripts API 不可使用等情况
runtimeGlobal.registerState = count === 1 ? RuntimeRegisterCode.REGISTER_DONE : RuntimeRegisterCode.UNSET;
}
}
async updateResourceOnScriptChange(script: Script) {
if (script.type !== SCRIPT_TYPE_NORMAL || script.status !== SCRIPT_STATUS_ENABLE) {
throw new Error("Invalid Calling of updateResourceOnScriptChange");
}
// 安装,启用,或earlyStartScript的value更新
const ret = await this.buildAndSaveCompiledResourceFromScript(script, true);
if (!ret) return;
const { apiScript } = ret;
await this.loadPageScript(script, apiScript!);
}
init() {
// 启动gm api
const permission = new PermissionVerify(this.group.group("permission"), this.mq);
const gmApi = new GMApi(
this.systemConfig,
permission,
this.group,
this.msgSender,
this.mq,
this.value,
new GMExternalDependencies(this)
);
permission.init();
gmApi.start();
this.group.on("stopScript", this.stopScript.bind(this));
this.group.on("runScript", this.runScript.bind(this));
this.group.on("pageLoad", this.pageLoad.bind(this));
// 监听脚本开启
this.mq.subscribe<TEnableScript[]>("enableScripts", async (data) => {
const unregisteyUuids = [] as string[];
for (const { uuid, enable } of data) {
const script = await this.scriptDAO.get(uuid);
if (!script) {
this.logger.error("script enable failed, script not found", {
uuid: uuid,
});
continue;
}
if (enable !== (script.status === SCRIPT_STATUS_ENABLE)) {
// 防止启用停止状态冲突
this.logger.error("script enable status conflicts", {
uuid: uuid,
});
continue;
}
// 如果是普通脚本, 在service worker中进行注册
// 如果是后台脚本, 在offscreen中进行处理
// 脚本类别不会更改
if (script.type === SCRIPT_TYPE_NORMAL) {
// 加载页面脚本
if (enable) {
await this.updateResourceOnScriptChange(script);
} else {
unregisteyUuids.push(uuid);
}
}
}
await this.unregistryPageScripts(unregisteyUuids);
});
// 监听脚本安装
this.mq.subscribe<TInstallScript>("installScript", async (data) => {
const script = await this.scriptDAO.get(data.script.uuid);
if (!script) {
this.logger.error("script install failed, script not found", {
uuid: data.script.uuid,
});
return;
}
// 代码更新时脚本类别不会更改
if (script.type === SCRIPT_TYPE_NORMAL) {
const enable = script.status === SCRIPT_STATUS_ENABLE;
if (enable) {
await this.updateResourceOnScriptChange(script);
} else {
// 还是要建立 CompiledResoure, 否则 Popup 看不到 Script
await this.buildAndSaveCompiledResourceFromScript(script, false);
}
}
});
// 监听脚本删除
this.mq.subscribe<TDeleteScript[]>("deleteScripts", async (data) => {
const unregisteyUuids = [] as string[];
for (const { uuid } of data) {
unregisteyUuids.push(uuid);
this.scriptMatchEnable.clearRules(uuid);
this.scriptMatchEnable.clearRules(`${uuid}${ORIGINAL_URLMATCH_SUFFIX}`);
this.scriptMatchDisable.clearRules(uuid);
this.scriptMatchDisable.clearRules(`${uuid}${ORIGINAL_URLMATCH_SUFFIX}`);
}
await this.unregistryPageScripts(unregisteyUuids);
});
// 监听脚本排序
this.mq.subscribe<TSortedScript[]>("sortedScripts", async (scripts) => {
const uuidSort = Object.fromEntries(scripts.map(({ uuid, sort }) => [uuid, sort]));
this.scriptMatchEnable.setupSorter(uuidSort);
this.scriptMatchDisable.setupSorter(uuidSort);
});
// 监听offscreen环境初始化, 初始化完成后, 再将后台脚本运行起来
this.mq.subscribe("preparationOffscreen", () => {
this.scriptDAO.all().then((list) => {
const res = [];
for (const script of list) {
if (script.type === SCRIPT_TYPE_NORMAL) {
continue;
}
res.push({
uuid: script.uuid,
enable: script.status === SCRIPT_STATUS_ENABLE,
});
}
if (res.length > 0) {
this.mq.publish<TEnableScript[]>("enableScripts", res);
}
});
this.systemConfig.getLanguage().then((lng: string) => {
this.mq.publish("setSandboxLanguage", lng);
});
this.systemConfig.addListener("language", (lng) => {
this.mq.publish("setSandboxLanguage", lng);
});
});
// 监听脚本值变更
this.mq.subscribe<TScriptValueUpdate>("valueUpdate", async ({ script, valueUpdated }: TScriptValueUpdate) => {
if (valueUpdated) {
if (script.status === SCRIPT_STATUS_ENABLE && isEarlyStartScript(script.metadata)) {
// 如果是预加载脚本,需要更新脚本代码重新注册
// scriptMatchInfo 里的 value 改变 => compileInjectionCode -> injectionCode 改变
await this.updateResourceOnScriptChange(script);
}
}
});
if (chrome.extension.inIncognitoContext) {
this.systemConfig.addListener("enable_script_incognito", async (enable) => {
// 隐身窗口不对注册了的脚本进行实际操作
// 在pageLoad时,根据isLoadScripts进行判断
this.isLoadScripts = enable && (await this.systemConfig.getEnableScriptNormal());
});
this.systemConfig.addListener("enable_script", async (enable) => {
// 隐身窗口不对注册了的脚本进行实际操作
// 当主窗口的enable改为false时,isLoadScripts也会更改为false
this.isLoadScripts = enable && (await this.systemConfig.getEnableScriptIncognito());
});
} else {
this.systemConfig.addListener("enable_script", async (enable) => {
this.isLoadScripts = enable;
await this.unregisterUserscripts();
if (enable) {
await this.registerUserscripts();
}
this.updateIcon();
});
}
this.systemConfig.addListener("blacklist", async (blacklist: string) => {
this.blacklist = obtainBlackList(blacklist);
this.loadBlacklist();
await this.unregisterUserscripts();
if (this.isUserScriptsAvailable && this.isLoadScripts) {
// 重新注册用户脚本;注册是会用加入 blacklistExcludeMatches 和 blacklistExcludeGlobs
await this.registerUserscripts();
}
this.logger.info("blacklist updated", {
blacklist,
});
});
const onUserScriptAPIGrantAdded = async () => {
this.isUserScriptsAvailable = true;
// 注册脚本
if (this.isLoadScripts) {
await this.unregisterUserscripts();
await this.registerUserscripts();
}
this.updateIcon();
};
const onUserScriptAPIGrantRemoved = async () => {
this.isUserScriptsAvailable = false;
// 取消当前注册 (如有)
await this.unregisterUserscripts();
this.updateIcon();
};
chrome.permissions.onAdded.addListener((permissions: chrome.permissions.Permissions) => {
const lastError = chrome.runtime.lastError;
if (lastError) {
console.error("chrome.runtime.lastError in chrome.permissions.onAdded:", lastError);
return;
}
if (permissions.permissions?.includes("userScripts")) {
// Firefox 或其他浏览器或需要手动启动 optional_permission
// 启动后注册脚本,不需重启扩充
onUserScriptAPIGrantAdded();
}
});
chrome.permissions.onRemoved.addListener((permissions: chrome.permissions.Permissions) => {
const lastError = chrome.runtime.lastError;
if (lastError) {
console.error("chrome.runtime.lastError in chrome.permissions.onRemoved:", lastError);
return;
}
if (permissions.permissions?.includes("userScripts")) {
// 虽然在目前设计中未有使用 permissions.remove
// 仅保留作为未来之用
onUserScriptAPIGrantRemoved();
}
});
// ======== 以下初始化是异步处理,因此扩充载入时可能会优先跑其他同步初始化 ========
// waitInit 优先处理 (包括处理重启问题)
this.loadingInitProcessPromise = this.waitInit();
this.initReady = (async () => {
// 取得初始值 或 等待各种异步同时进行的初始化 (_1, _2, ...)
const [isUserScriptsAvailable, isLoadScripts, strBlacklist, _1, _2] = await Promise.all([
checkUserScriptsAvailable(),
this.systemConfig.getEnableScript(),
this.systemConfig.getBlacklist(),
this.loadingInitProcessPromise, // 初始化程序等待
this.initUserAgentData(), // 初始化:userAgentData
]);
// 保存初始值
this.isUserScriptsAvailable = isUserScriptsAvailable;
this.isLoadScripts = isLoadScripts;
this.blacklist = obtainBlackList(strBlacklist);
// 更新 logo
this.updateIcon();
// 检查是否开启了开发者模式
if (!this.isUserScriptsAvailable) {
// 未开启加上警告引导
this.showUserscriptActivationGuide();
let cid: ReturnType<typeof setInterval> | number;
cid = setInterval(async () => {
if (!this.isUserScriptsAvailable) {
// 注:optional permission 的设计会触发 chrome.permissions.onAdded
// this.isUserScriptsAvailable 自动转为 true, 不需要检测
try {
const scriptId = `undefined-test-${Date.now()}`;
await chrome.userScripts.register([
{
id: scriptId,
js: [{ code: "void 0;" }],
matches: ["https://not-found.scriptcat.org/"],
world: "USER_SCRIPT",
},
]);
await chrome.userScripts.unregister({ ids: [scriptId] });
} catch (_e) {
// 预期出错,不执行后续
return;
}
}
clearInterval(cid);
cid = 0;
// 主要针对 Allow User Scripts 设计
chrome.runtime.reload();
}, 500);
}
// 初始化:加载黑名单
this.loadBlacklist();
// 或许能加快PageLoad的载入速度。subframe 的 URL 不捕捉。
setOnTabURLChanged((newUrl: string) => {
if (!this.isUrlBlacklist(newUrl)) {
this.scriptMatchEnable.urlMatch(newUrl);
}
});
// 注册脚本
await this.initialCompiledResourcePromise; // 先等待 CompiledResource 完成避免注册时重复生成
await this.registerUserscripts();
this.initReady = true;
// 初始化完成
return true;
})();
}
updateIcon() {
const enableUserscript: boolean = this.isUserScriptsAvailable && this.isLoadScripts;
const iconUrl = enableUserscript
? chrome.runtime.getURL("assets/logo-32.png") // 设置正常logo
: chrome.runtime.getURL("assets/logo-gray-32.png"); // 如果未启用脚本,设置灰色的logo
chrome.action.setIcon(
{
path: { "32": iconUrl },
},
() => {
const lastError = chrome.runtime.lastError;
if (lastError) {
console.error("chrome.runtime.lastError in chrome.action.setIcon:", lastError);
}
}
);
}
public loadBlacklist() {
// 设置黑名单match
const blacklist = this.blacklist; // 重用cache的blacklist阵列 (immutable)
const rules = extractUrlPatterns([...blacklist.map((e) => `@include ${e}`)]);
this.blackMatch.clearRules("BK");
this.blackMatch.addRules("BK", rules);
// 黑名单排除
const excludeMatches = [];
const excludeGlobs = [];
for (const rule of rules) {
if (rule.ruleType === RuleType.MATCH_INCLUDE) {
// matches -> excludeMatches
excludeMatches.push(rule.patternString);
} else if (rule.ruleType === RuleType.GLOB_INCLUDE) {
// includeGlobs -> excludeGlobs
excludeGlobs.push(rule.patternString);
}
}
this.blacklistExcludeMatches = excludeMatches;
this.blacklistExcludeGlobs = excludeGlobs;
}
public isUrlBlacklist(url: string) {
return this.blackMatch.urlMatch(url)[0] === "BK";
}
// 取消脚本注册
async unregisterUserscripts() {
// 检查 registered 避免重复操作增加系统开支
// 已成功注册(true)或是未知有无注册(null)的情况下执行
if (runtimeGlobal.registerState !== RuntimeRegisterCode.UNREGISTER_DONE) {
runtimeGlobal.registerState = RuntimeRegisterCode.UNREGISTER_DONE;
// 重置 flag 避免取消注册失败
// 即使注册失败,通过重置 flag 可避免错误地呼叫已取消注册的Script
await Promise.allSettled([chrome.userScripts?.unregister(), chrome.scripting.unregisterContentScripts()]);
}
}
async buildAndSaveCompiledResourceFromScript(script: Script, withCode: boolean = false) {
const scriptRes = withCode ? await this.script.buildScriptRunResource(script) : buildScriptRunResourceBasic(script);
const resources = withCode ? scriptRes.resource : await this.resource.getScriptResources(scriptRes, true);
const resourceUrls = (script.metadata["require"] || []).map((res) => resources[res]?.url).filter((res) => res);
const scriptMatchInfo = await this.applyScriptMatchInfo(scriptRes);
if (!scriptMatchInfo) return undefined;
const res = getUserScriptRegister(scriptMatchInfo);
const registerScript = res.registerScript;
let jsCode = "";
if (withCode) {
const code = compileInjectionCode(scriptRes, scriptRes.code, scriptMatchInfo.scriptUrlPatterns);
registerScript.js[0].code = jsCode = code;
}
// 过滤掉matches为空的脚本
if (!registerScript.matches || registerScript.matches.length === 0) {
this.logger.error("registerScript matches is empty", {
script: script.name,
uuid: script.uuid,
});
return undefined;
}
const scriptUrlPatterns = scriptMatchInfo.scriptUrlPatterns;
const originalUrlPatterns = scriptMatchInfo.originalUrlPatterns;
const result = {
flag: scriptRes.flag,
name: script.name,
require: resourceUrls, // 仅储存url
uuid: script.uuid,
matches: registerScript.matches || [],
includeGlobs: registerScript.includeGlobs || [],
excludeMatches: registerScript.excludeMatches || [],
excludeGlobs: registerScript.excludeGlobs || [],
allFrames: registerScript.allFrames || false,
world: registerScript.world || "",
runAt: registerScript.runAt || "",
scriptUrlPatterns: scriptUrlPatterns,
originalUrlPatterns: scriptUrlPatterns === originalUrlPatterns ? null : originalUrlPatterns,
} as CompiledResource;
this.compiledResourceDAO.save(result);
return { compiledResource: result, jsCode, apiScript: registerScript };
}
// 从CompiledResource中还原脚本代码
async restoreJSCodeFromCompiledResource(script: Script, result: CompiledResource) {
// 如果是 Scriptlet (unwrap) 脚本,需要另外的处理方式
if (isScriptletUnwrap(script.metadata)) {
const scriptRes = await this.script.buildScriptRunResource(script);
if (!scriptRes) return "";
return compileScriptletCode(scriptRes, scriptRes.code, result.scriptUrlPatterns);
}
// 如果是预加载脚本,需要另外的处理方式
if (isEarlyStartScript(script.metadata)) {
const scriptRes = await this.script.buildScriptRunResource(script);
if (!scriptRes) return "";
return compileInjectionCode(scriptRes, scriptRes.code, result.scriptUrlPatterns);
}
const originalCode = await this.script.scriptCodeDAO.get(result.uuid);
const require: CompileScriptCodeResource["require"] = [];
for (const requireUrl of result.require) {
const res = await this.resource.resourceDAO.get(requireUrl);
if (res) {
require.push({ url: res.url, content: res.content });
}
}
return compileInjectScriptByFlag(
result.flag,
compileScriptCodeByResource({
name: result.name,
code: originalCode?.code || "",
require,
})
);
}
async getParticularScriptList({
excludeMatches,
excludeGlobs,
}: {
excludeMatches: string[];
excludeGlobs: string[];
}) {
const list = await this.scriptDAO.all();
// 按照脚本顺序位置排序
list.sort((a, b) => a.sort - b.sort);
const registerScripts = await Promise.all(
list.map(async (script) => {
if (script.type !== SCRIPT_TYPE_NORMAL || script.status !== SCRIPT_STATUS_ENABLE) {
return undefined;
}
let resultCode = "";
let result = await this.compiledResourceDAO.get(script.uuid);
if (!result || !result.scriptUrlPatterns?.length) {
// 按常理不会跑这个
const ret = await this.buildAndSaveCompiledResourceFromScript(script, true);
if (!ret) return undefined;
result = ret.compiledResource;
resultCode = ret.jsCode;
} else {
resultCode = await this.restoreJSCodeFromCompiledResource(script, result);
}
if (!resultCode) return undefined;
const registerScript = {
id: result.uuid,
js: [{ code: resultCode }],
matches: result.matches,
includeGlobs: result.includeGlobs,
excludeMatches: [...result.excludeMatches, ...excludeMatches],
excludeGlobs: [...result.excludeGlobs, ...excludeGlobs],
allFrames: result.allFrames,
world: result.world,
} as chrome.userScripts.RegisteredUserScript;
if (result.runAt) {
registerScript.runAt = result.runAt as chrome.extensionTypes.RunAt;
}
return registerScript;
})
).then(async (res) => {
// 过滤掉undefined和未开启的
return res.filter((item) => item) as chrome.userScripts.RegisteredUserScript[];
});
return registerScripts;
}
// 获取content.js和inject.js的脚本注册信息
async getContentAndInjectScript({
excludeMatches,
excludeGlobs,
}: {
excludeMatches: string[];
excludeGlobs: string[];
}) {
// 配置脚本运行环境: 注册时前先准备 chrome.runtime 等设定
// Firefox MV3 只提供 runtime.sendMessage 及 runtime.connect
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/userScripts/WorldProperties#messaging
try {
await chrome.userScripts.configureWorld({
csp: "script-src 'self' 'unsafe-inline' 'unsafe-eval' *",
messaging: true,
});
} catch (_e) {
try {
await chrome.userScripts.configureWorld({
messaging: true,
});
} catch (_e) {
console.error("chrome.userScripts.configureWorld({messaging:true}) failed.");
// do nothing
}
}
let retContent: chrome.scripting.RegisteredContentScript[] = [];
const retInject: chrome.userScripts.RegisteredUserScript[] = [];
// ------ scripting.js ------
// Note: Chrome does not support file.js?query
// 注意:Chrome 不支持 file.js?query
retContent = [
{
id: "scriptcat-scripting",
js: ["/src/scripting.js"],
matches: ["<all_urls>"],
allFrames: true,
runAt: "document_start",
excludeMatches,
} satisfies chrome.scripting.RegisteredContentScript,
];
// ------ inject.js & content.js ------
const jsonUAD = JSON.stringify(this.userAgentData);
const injectJs = await this.getInjectJsCode();
if (injectJs) {
// 构建inject.js的脚本注册信息
const codeBody = `(function (UserAgentData) {\n${injectJs}\n})(${jsonUAD})`;
const code = `${codeBody}${sourceMapTo("scriptcat-inject.js")}\n`;
const script = {
id: "scriptcat-inject",
js: [{ code }],
matches: ["<all_urls>"],
allFrames: true,
runAt: "document_start",
excludeMatches: excludeMatches,
excludeGlobs: excludeGlobs,
world: "MAIN",
} satisfies chrome.userScripts.RegisteredUserScript;
retInject.push(script);
}
const contentJs = await this.getContentJsCode();
if (contentJs) {
// 构建 content.js 的脚本注册信息
const codeBody = `(function (UserAgentData) {\n${contentJs}\n})(${jsonUAD})`;
const code = `${codeBody}${sourceMapTo("scriptcat-content.js")}\n`;
const script = {
id: "scriptcat-content",
js: [{ code }],
matches: ["<all_urls>"],
allFrames: true,
runAt: "document_start",
excludeMatches,
excludeGlobs,
world: "USER_SCRIPT",
} satisfies chrome.userScripts.RegisteredUserScript;
retInject.push(script);
}
return { content: retContent, inject: retInject };
}
// 如果是重复注册,需要先调用 unregisterUserscripts
async registerUserscripts() {
// 若 UserScripts API 不可使用 或 ScriptCat设定为不启用脚本 则退出
if (!this.isUserScriptsAvailable || !this.isLoadScripts) return;
// 判断是否已经注册过
if (runtimeGlobal.registerState === RuntimeRegisterCode.REGISTER_DONE) {
// 异常情况
// 检查scriptcat-content和scriptcat-inject是否存在
const res = await chrome.userScripts.getScripts({ ids: ["scriptcat-inject"] });
if (res.length === 1) {
return;
}
// scriptcat-content/scriptcat-inject不存在的情况
// 走一次重新注册的流程
this.logger.warn("registered = true but scriptcat-content/scriptcat-inject not exists, re-register userscripts.");
runtimeGlobal.registerState = RuntimeRegisterCode.UNSET; // 异常时强制反注册
}
// 删除旧注册
await this.unregisterUserscripts();
// 使注册时重新注入 chrome.runtime
try {
await chrome.userScripts.resetWorldConfiguration();
} catch (e: any) {
console.error("chrome.userScripts.resetWorldConfiguration() failed.", e);
}
const options = {
excludeMatches: this.blacklistExcludeMatches,
excludeGlobs: this.blacklistExcludeGlobs,
};
const particularScriptList = await this.getParticularScriptList(options);
// getContentAndInjectScript依赖loadScriptMatchInfo
// 需要等getParticularScriptList完成后再执行
const { inject: injectScriptList, content: contentScriptList } = await this.getContentAndInjectScript(options);
const list: chrome.userScripts.RegisteredUserScript[] = [...particularScriptList, ...injectScriptList];
let failed = false;
try {
await chrome.userScripts.register(list);
} catch (e: any) {
this.logger.error("batch registration error", Logger.E(e));
// 批量注册失败则退回单个注册
for (const script of list) {
try {
await chrome.userScripts.register([script]);
} catch (e: any) {
if (e.message?.includes("Duplicate script ID")) {
// 如果是重复注册, 则更新
try {
await chrome.userScripts.update([script]);
} catch (e) {
failed = true;
this.logger.error("update error", Logger.E(e));
}
} else {
this.logger.error("register error", Logger.E(e));
}
}
}
}
if (contentScriptList.length > 0) {
try {
await chrome.scripting.registerContentScripts(contentScriptList);
} catch (e: any) {
failed = true;
this.logger.error("register content.js error", Logger.E(e));
}
}
runtimeGlobal.registerState = failed ? RuntimeRegisterCode.UNSET : RuntimeRegisterCode.REGISTER_DONE;
}