-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy pathgm_api.ts
More file actions
1717 lines (1634 loc) · 60.8 KB
/
gm_api.ts
File metadata and controls
1717 lines (1634 loc) · 60.8 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 LoggerCore from "@App/app/logger/core";
import Logger from "@App/app/logger/logger";
import { ScriptDAO } from "@App/app/repo/scripts";
import { SubscribeDAO } from "@App/app/repo/subscribe";
import { type IGetSender, type Group, GetSenderType } from "@Packages/message/server";
import type { ExtMessageSender, MessageSend, TMessageCommAction } from "@Packages/message/types";
import { connect, sendMessage } from "@Packages/message/client";
import type { IMessageQueue } from "@Packages/message/message_queue";
import { type ValueService } from "@App/app/service/service_worker/value";
import type { ConfirmParam } from "../permission_verify";
import PermissionVerify, { PermissionVerifyApiGet } from "../permission_verify";
import { cacheInstance } from "@App/app/cache";
import { type RuntimeService } from "../runtime";
import {
getIcon,
isFirefox,
getCurrentTab,
openInCurrentTab,
cleanFileName,
makeBlobURL,
stripUndefined,
} from "@App/pkg/utils/utils";
import { type SystemConfig } from "@App/pkg/config/config";
import i18next, { i18nName } from "@App/locales/locales";
import FileSystemFactory from "@Packages/filesystem/factory";
import type FileSystem from "@Packages/filesystem/filesystem";
import { isWarpTokenError } from "@Packages/filesystem/error";
import { joinPath } from "@Packages/filesystem/utils";
import type {
EmitEventRequest,
GMRegisterMenuCommandParam,
GMUnRegisterMenuCommandParam,
MessageRequest,
NotificationMessageOption,
GMApiRequest,
} from "../types";
import type { TScriptMenuRegister, TScriptMenuUnregister } from "../../queue";
import type { NotificationOptionCache } from "../utils";
import { BrowserNoSupport, notificationsUpdate } from "../utils";
import i18n from "@App/locales/locales";
import { encodeRValue, type TKeyValuePair } from "@App/pkg/utils/message_value";
import { createObjectURL } from "../../offscreen/client";
import type { GMXhrStrategy } from "./gm_xhr";
import {
GMXhrFetchStrategy,
GMXhrXhrStrategy,
nwErrorResultPromises,
nwErrorResults,
redirectedUrls,
scXhrRequests,
SWRequestResultParams,
} from "./gm_xhr";
import { headerModifierMap, headersReceivedMap } from "./gm_xhr";
import { BgGMXhr } from "@App/pkg/utils/xhr/bg_gm_xhr";
import { mightPrepareSetClipboard, setClipboard } from "../clipboard";
import { nativePageWindowOpen } from "../../offscreen/gm_api";
import { WakeUpCommand, wakeupPingCommand } from "@App/pkg/utils/wakeup-ping";
let generatedUniqueMarkerIDs = "";
let generatedUniqueMarkerIDWhen = "";
// 用来生成绝不重复的 MarkerID
const generateUniqueMarkerID = () => {
const u1 = Math.floor(Date.now()).toString(36);
let u2 = `_${Math.floor(Math.random() * 2514670967279938 + 1045564536402193).toString(36)}`;
if (u1 !== generatedUniqueMarkerIDWhen) {
generatedUniqueMarkerIDWhen = u1;
generatedUniqueMarkerIDs = u2;
} else {
// 实际上 u2 的重复可能性非常低
while (generatedUniqueMarkerIDs.indexOf(u2) >= 0) {
u2 = `_${Math.floor(Math.random() * 2514670967279938 + 1045564536402193).toString(36)}`;
}
generatedUniqueMarkerIDs += u2;
}
return `MARKER::${u1}${u2}`;
};
type OnBeforeSendHeadersOptions = `${chrome.webRequest.OnBeforeSendHeadersOptions}`;
type OnHeadersReceivedOptions = `${chrome.webRequest.OnHeadersReceivedOptions}`;
// GMExternalDependencies接口定义
// 为了支持外部依赖注入,方便测试和扩展
interface IGMExternalDependencies {
emitEventToTab(to: ExtMessageSender, req: EmitEventRequest): void;
isBlacklistNetwork(url: URL): boolean;
}
/**
* 这里的值如果末尾是-结尾,将会判断使用.startsWith()判断,否则使用.includes()
*
* @link https://developer.mozilla.org/zh-CN/docs/Glossary/Forbidden_request_header
*/
export const unsafeHeaders: {
[key: string]: boolean;
} = {
// 部分浏览器中并未允许
"user-agent": true,
// 这两个是前缀
"proxy-": true,
"sec-": true,
// cookie已经特殊处理
cookie: true,
"accept-charset": true,
"accept-encoding": true,
"access-control-request-headers": true,
"access-control-request-method": true,
connection: true,
"content-length": true,
date: true,
dnt: true,
expect: true,
"feature-policy": true,
host: true,
"keep-alive": true,
origin: true,
referer: true,
te: true,
trailer: true,
"transfer-encoding": true,
upgrade: true,
via: true,
};
/**
* 检测是否存在不安全的请求头(xhr不允许自定义的的请求头)
* @returns
* + true 存在
* + false 不存在
*/
export const checkHasUnsafeHeaders = (key: string) => {
key = key.toLowerCase();
if (unsafeHeaders[key]) {
return true;
}
// ends with "-"
const specialHeaderKeys = ["proxy-", "sec-"];
if (specialHeaderKeys.some((specialHeaderKey) => key.startsWith(specialHeaderKey))) {
return true;
}
return false;
};
export enum ConnectMatch {
NONE = 0, // 没有匹配
ALL = 1, // 遇到 "*" 通配符
DOMAIN = 2, // 匹配子域
EXACT = 3, // 完全匹配
}
export enum SelfMatch {
NONE = 0,
EXACT = 1,
SUB = 2,
}
export const getConnectMatched = (
metadataConnect: string[] | undefined,
reqURL: URL,
sender: IGetSender
): ConnectMatch => {
const checkSelfDomainMatching = () => {
const senderURL = sender.getSender()?.url;
if (senderURL) {
let senderURLObject;
try {
senderURLObject = new URL(senderURL);
} catch {
// ignore
}
if (senderURLObject) {
if (reqURL.hostname === senderURLObject.hostname) return SelfMatch.EXACT; // 自身
if (`.${reqURL.hostname}`.endsWith(`.${senderURLObject.hostname}`)) return SelfMatch.SUB; // 子域
}
}
return SelfMatch.NONE;
};
const selfCheckRes = checkSelfDomainMatching();
if (selfCheckRes === SelfMatch.EXACT) {
// TM 行为:只要是同一个网域的Xhr都放行。目前SC未支持finalUrl改变的拒绝
return ConnectMatch.EXACT; // 完全匹配
}
// 不是同一网域时,检查一下 @connect
if (metadataConnect?.length) {
for (let i = 0, l = metadataConnect.length; i < l; i += 1) {
const lowerMetaConnect = metadataConnect[i].toLowerCase();
if (lowerMetaConnect === "self") {
// 此处包含子网域
if (selfCheckRes === SelfMatch.SUB) return ConnectMatch.DOMAIN; // 匹配其子域
} else if (lowerMetaConnect === "*") {
// 不完全遵照TM。SC 只要有 @connect * 就全放行不询问
return ConnectMatch.ALL;
} else if (`.${reqURL.hostname}`.endsWith(`.${lowerMetaConnect}`)) {
return ConnectMatch.DOMAIN; // 完全匹配或其子域
}
}
}
return ConnectMatch.NONE;
};
type NotificationData = {
uuid: string;
details: GMTypes.NotificationDetails;
sender: ExtMessageSender;
};
// GMExternalDependencies接口定义
// 为了支持外部依赖注入,方便测试和扩展
export class GMExternalDependencies implements IGMExternalDependencies {
constructor(private runtimeService: RuntimeService) {}
emitEventToTab(to: ExtMessageSender, req: EmitEventRequest): void {
this.runtimeService.emitEventToTab(to, req);
}
isBlacklistNetwork(url: URL) {
const isBlackListed =
this.runtimeService.isUrlBlacklist(url.href) || // 黑名单中含有该网址 https://abc.com/page.html
this.runtimeService.isUrlBlacklist(`${url.protocol}//${url.hostname}`) || // 黑名单中含有该网域 https://abc.com
this.runtimeService.isUrlBlacklist(`${url.protocol}//${url.hostname}/`); // 黑名单中含有该网域 https://abc.com/
return isBlackListed;
}
}
export class MockGMExternalDependencies implements IGMExternalDependencies {
emitEventToTab(to: ExtMessageSender, req: EmitEventRequest): void {
// Mock implementation for testing
console.log("Mock emitEventToTab called", { to, req });
}
isBlacklistNetwork(_url: URL) {
return false;
}
}
const supportedRequestMethods = new Set<string>([
"connect",
"delete",
"get",
"head",
"options",
"patch",
"post",
"put",
]);
export default class GMApi {
logger: Logger;
scriptDAO: ScriptDAO = new ScriptDAO();
subscribeDAO: SubscribeDAO = new SubscribeDAO();
constructor(
private systemConfig: SystemConfig,
private permissionVerify: PermissionVerify,
private group: Group,
private msgSender: MessageSend,
private mq: IMessageQueue,
private value: ValueService,
private gmExternalDependencies: IGMExternalDependencies
) {
this.logger = LoggerCore.logger().with({ service: "runtime/gm_api" });
}
// PermissionVerify.API
// sendMessage from Content Script, etc
async handlerRequest(data: MessageRequest, sender: IGetSender) {
this.logger.trace("GM API request", { api: data.api, uuid: data.uuid, param: data.params });
const api = PermissionVerifyApiGet(data.api);
if (!api) {
throw new Error("gm api is not found");
}
const req = await this.parseRequest(data);
try {
await this.permissionVerify.verify(req, api, sender, this);
} catch (e) {
this.logger.error("verify error", { api: data.api }, Logger.E(e));
throw e;
}
return api.api.call(this, req, sender);
}
// 解析请求
async parseRequest<T>(data: MessageRequest<T>): Promise<GMApiRequest<T>> {
const script = await this.scriptDAO.get(data.uuid);
if (!script) {
throw new Error("script is not found");
}
// 订阅脚本的 connect 使用订阅声明的 connect 覆盖脚本自身的
if (script.subscribeUrl) {
const subscribe = await this.subscribeDAO.get(script.subscribeUrl);
if (subscribe?.metadata?.connect) {
script.metadata = { ...script.metadata, connect: subscribe.metadata.connect };
}
}
return { ...data, script } as GMApiRequest<T>;
}
@PermissionVerify.API({
confirm: async (request: GMApiRequest<[string, GMTypes.CookieDetails]>, sender: IGetSender, gmApi: GMApi) => {
if (request.params[0] === "store") {
return true;
}
const detail = request.params[1];
// 未指定 url 和 domain 时,自动使用当前页面的 URL(兼容 Tampermonkey 行为)
const senderURL = sender.getSender()?.url;
if (!detail.url && !detail.domain && senderURL) {
detail.url = senderURL;
}
let url: URL = <URL>{};
if (detail.url) {
url = new URL(`${detail.url}`);
} else if (detail.domain) {
url.hostname = url.host = `${detail.domain}`;
} else {
throw new Error("there must be one of url or domain");
}
if (getConnectMatched(request.script.metadata.connect, url, sender) === ConnectMatch.NONE) {
// 检查是否配置了权限
const ret = await gmApi.permissionVerify.queryPermission(request, {
permission: "cookie",
permissionValue: url.host,
});
if (ret && ret.allow) {
return true;
}
throw new Error("hostname must be in the definition of connect");
}
const metadata: { [key: string]: string } = {};
metadata[i18next.t("script_name")] = i18nName(request.script);
metadata[i18next.t("request_domain")] = url.host;
return {
permission: "cookie",
permissionValue: url.host,
title: i18next.t("access_cookie_content")!,
metadata,
describe: i18next.t("confirm_script_operation")!,
permissionContent: i18next.t("cookie_domain")!,
uuid: "",
};
},
})
async GM_cookie(request: GMApiRequest<[string, GMTypes.CookieDetails]>, sender: IGetSender) {
const param = request.params;
if (param.length !== 2) {
throw new Error("there must be two parameters");
}
const cookieAction: string = `${param[0]}`;
const detail: GMTypes.CookieDetails = param[1];
// 未指定 url 和 domain 时,自动使用当前页面的 URL(兼容 Tampermonkey 行为)
const senderURL = sender.getSender()?.url;
if (!detail.url && !detail.domain && senderURL) {
detail.url = senderURL;
}
if (detail.domain) detail.domain = `${detail.domain}`.trim();
if (detail.url) detail.url = `${detail.url}`.trim();
if (!detail.partitionKey || typeof detail.partitionKey !== "object") {
detail.partitionKey = {};
}
if (typeof detail.partitionKey.topLevelSite !== "string") {
// string | undefined
detail.partitionKey.topLevelSite = undefined;
}
// 处理tab的storeid
const tabId = sender.getExtMessageSender().tabId;
let storeId: string | undefined;
if (tabId !== -1) {
const stores = await chrome.cookies.getAllCookieStores();
const store = stores.find((val) => val.tabIds.includes(tabId));
if (store) {
storeId = store.id;
}
}
switch (cookieAction) {
case "list": {
detail.domain = detail.domain || undefined;
detail.url = detail.url || undefined;
const cookies = await chrome.cookies.getAll(
stripUndefined({
domain: detail.domain,
name: detail.name,
path: detail.path,
secure: detail.secure,
session: detail.session,
url: detail.url,
storeId: storeId,
partitionKey: stripUndefined(detail.partitionKey),
})
);
return cookies;
}
case "delete": {
detail.domain = undefined;
detail.url = detail.url || senderURL;
if (!detail.url || !detail.name) {
throw new Error("delete operation must have url and name");
}
await chrome.cookies.remove(
stripUndefined({
name: detail.name,
url: detail.url,
storeId: storeId,
partitionKey: stripUndefined(detail.partitionKey),
})
);
break;
}
case "set": {
detail.domain = detail.domain || undefined;
detail.url = detail.url || senderURL;
// https://developer.chrome.com/docs/extensions/reference/api/cookies#method-set
if (!detail.name) detail.name = ""; // Empty by default if omitted.
if (!detail.value) detail.value = ""; // Empty by default if omitted.
if (!detail.url) {
throw new Error("set operation must have url");
}
await chrome.cookies.set(
stripUndefined({
url: detail.url,
name: detail.name,
domain: detail.domain,
value: detail.value,
expirationDate: detail.expirationDate,
path: detail.path,
httpOnly: detail.httpOnly,
secure: detail.secure,
storeId: storeId,
partitionKey: stripUndefined(detail.partitionKey),
})
);
break;
}
default: {
throw new Error("action can only be: get, set, delete, store");
}
}
}
@PermissionVerify.API()
async GM_log(
request: GMApiRequest<[string, GMTypes.LoggerLevel, GMTypes.LoggerLabel[]?]>,
_sender: IGetSender
): Promise<boolean> {
const message = request.params[0];
const level = request.params[1] || "info";
const labels = request.params[2] || [];
LoggerCore.logger(...labels).log(level, message, {
uuid: request.uuid,
name: request.script.name,
component: "GM_log",
});
return true;
}
@PermissionVerify.API({ link: ["GM_deleteValue", "GM_deleteValues"] })
async GM_setValue(request: GMApiRequest<[string, string, any?]>, sender: IGetSender) {
if (!request.params || request.params.length < 2) {
throw new Error("param is failed");
}
const [id, key, value] = request.params as [string, string, any];
const keyValuePairs = [[key, encodeRValue(value)]] as TKeyValuePair[];
const valueSender = {
runFlag: request.runFlag,
tabId: sender.getSender()?.tab?.id || -1,
};
await this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender });
}
@PermissionVerify.API({ link: ["GM_deleteValues"] })
async GM_setValues(request: GMApiRequest<[string, TKeyValuePair[]]>, sender: IGetSender) {
if (!request.params || request.params.length !== 2) {
throw new Error("param is failed");
}
const [id, keyValuePairs] = request.params;
const valueSender = {
runFlag: request.runFlag,
tabId: sender.getSender()?.tab?.id || -1,
};
await this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender });
}
@PermissionVerify.API()
CAT_userConfig(request: GMApiRequest<void>, sender: IGetSender): void {
const { tabId } = sender.getExtMessageSender();
openInCurrentTab(`/src/options.html#/?userConfig=${request.uuid}`, tabId === -1 ? undefined : tabId);
}
@PermissionVerify.API({
confirm: async (request: GMApiRequest<[string, CATType.CATFileStorageDetails]>, _sender: IGetSender) => {
const [action, details] = request.params;
if (action === "config") {
return true;
}
const dir = details.baseDir ? details.baseDir : request.script.uuid;
const metadata: { [key: string]: string } = {};
metadata[i18next.t("script_name")] = i18nName(request.script);
return {
permission: "file_storage",
permissionValue: dir,
title: i18next.t("script_operation_title"),
metadata,
describe: i18next.t("script_operation_description", { dir }),
wildcard: false,
permissionContent: i18next.t("script_permission_content"),
} as ConfirmParam;
},
})
async CAT_fileStorage(
request: GMApiRequest<["config"] | ["list" | "download" | "upload" | "delete", CATType.CATFileStorageDetails]>,
sender: IGetSender
): Promise<{ action: string; data: any } | boolean> {
const [action, details] = request.params;
if (action === "config") {
const { tabId, windowId } = sender.getExtMessageSender();
chrome.tabs.create({
url: `/src/options.html#/setting`,
openerTabId: tabId === -1 ? undefined : tabId,
windowId: windowId === -1 ? undefined : windowId,
});
return true;
}
const fsConfig = await this.systemConfig.getCatFileStorage();
if (fsConfig.status === "unset") {
return { action: "error", data: { code: 1, error: "file storage is unset" } };
}
if (fsConfig.status === "error") {
return { action: "error", data: { code: 2, error: "file storage is error" } };
}
let fs: FileSystem;
const baseDir = `ScriptCat/app/${details.baseDir ? details.baseDir : request.script.uuid}`;
try {
fs = await FileSystemFactory.create(fsConfig.filesystem, fsConfig.params[fsConfig.filesystem]);
await FileSystemFactory.mkdirAll(fs, baseDir);
fs = await fs.openDir(baseDir);
} catch (e: any) {
if (isWarpTokenError(e)) {
fsConfig.status = "error";
this.systemConfig.setCatFileStorage(fsConfig);
return { action: "error", data: { code: 2, error: e.error.message } };
}
return { action: "error", data: { code: 8, error: e.message } };
}
switch (action) {
case "list":
try {
const list = await fs.list();
for (const file of list) {
(<any>file).absPath = file.path;
file.path = joinPath(file.path.substring(file.path.indexOf(baseDir) + baseDir.length));
}
return { action: "onload", data: list };
} catch (e: any) {
return { action: "error", data: { code: 3, error: e.message } };
}
case "upload":
try {
const w = await fs.create(details.path);
await w.write(await (await fetch(<string>details.data)).blob());
return { action: "onload", data: true };
} catch (e: any) {
return { action: "error", data: { code: 4, error: e.message } };
}
case "download":
try {
const info: CATType.FileStorageFileInfo = details.file;
fs = await fs.openDir(`${info.path}`);
const r = await fs.open({
fsid: (<any>info).fsid,
name: info.name,
path: info.absPath,
size: info.size,
digest: info.digest,
createtime: info.createtime,
updatetime: info.updatetime,
});
const blob = await r.read("blob");
const url = await makeBlobURL({ blob, persistence: false }, (params) =>
createObjectURL(this.msgSender, params)
);
return { action: "onload", data: url };
} catch (e: any) {
return { action: "error", data: { code: 5, error: e.message } };
}
break;
case "delete":
try {
await fs.delete(`${details.path}`);
return { action: "onload", data: true };
} catch (e: any) {
return { action: "error", data: { code: 6, error: e.message } };
}
default:
throw new Error("action is not supported");
}
}
// 根据header生成dnr规则
async buildDNRRule(markerID: string, params: GMSend.XHRDetails, sender: IGetSender): Promise<boolean> {
// 添加请求header
const headers = params.headers || (params.headers = {});
const { anonymous, cookie } = params;
// HTTP/1.1 and HTTP/2
// https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2
// https://datatracker.ietf.org/doc/html/rfc6648
// All header names in HTTP/2 are lower case, and CF will convert if needed.
// All headers comparisons in HTTP/1.1 should be case insensitive.
headers["x-sc-request-marker"] = `${markerID}`;
// 关联 reqID 方法
// 1) 尝试在 onBeforeRequest 进行关连
// 2) 如果在 chrome.webRequest.onBeforeSendHeaders 执行时,modifyHeaders DNR 未被执行,则以 "x-sc-request-marker" 进行关连
// 如果header中没有origin就设置为空字符串,如果有origin就不做处理,注意处理大小写
if (typeof headers["Origin"] !== "string" && typeof headers["origin"] !== "string") {
headers["Origin"] = "";
}
const modifyReqHeaders = [] as chrome.declarativeNetRequest.ModifyHeaderInfo[];
// 判断是否是anonymous
if (anonymous) {
// 如果是anonymous,并且有cookie,则设置为自定义的cookie
if (cookie) {
modifyReqHeaders.push({
header: "cookie",
operation: "set",
value: cookie,
});
} else {
// 否则删除cookie
modifyReqHeaders.push({
header: "cookie",
operation: "remove",
});
}
} else {
if (cookie) {
// 否则正常携带cookie header
headers["cookie"] = cookie;
}
// 追加该网站本身存储的cookie
const tabId = sender.getExtMessageSender().tabId;
let storeId: string | undefined;
if (tabId !== -1 && typeof tabId === "number") {
const stores = await chrome.cookies.getAllCookieStores();
const store = stores.find((val) => val.tabIds.includes(tabId));
if (store) {
storeId = store.id;
}
}
const cookies = await chrome.cookies.getAll(
stripUndefined({
url: params.url,
storeId: storeId,
partitionKey: stripUndefined(params.cookiePartition),
})
);
// 追加cookie
if (cookies?.length) {
const v = cookies.map((c) => `${c.name}=${c.value}`).join("; ");
const u = `${headers["cookie"] || ""}`.trim();
headers["cookie"] = u ? `${u}${!u.endsWith(";") ? "; " : " "}${v}` : v;
}
}
/** 请求的header的值 */
for (const [key, headerValue] of Object.entries(headers)) {
if (!headerValue) {
modifyReqHeaders.push({
header: key,
operation: "remove",
});
delete headers[key];
} else if (checkHasUnsafeHeaders(key)) {
modifyReqHeaders.push({
header: key,
operation: "set",
value: `${headerValue}`,
});
delete headers[key];
}
}
if (modifyReqHeaders.length > 0) {
// const tabs = await chrome.tabs.query({});
// const excludedTabIds: number[] = [];
// for (const tab of tabs) {
// if (tab.id) {
// excludedTabIds.push(tab.id);
// }
// }
let requestMethod = (params.method || "GET").toLowerCase() as chrome.declarativeNetRequest.RequestMethod;
if (!supportedRequestMethods.has(requestMethod)) {
requestMethod = "other" as chrome.declarativeNetRequest.RequestMethod;
}
const redirectNotManual = params.redirect !== "manual";
// 使用 cacheInstance 避免SW重启造成重复 DNR Rule ID
const ruleId = 10000 + (await cacheInstance.incr("gmXhrRequestId", 1));
const rule = {
id: ruleId,
action: {
type: "modifyHeaders",
requestHeaders: modifyReqHeaders,
},
priority: 1,
condition: {
resourceTypes: ["xmlhttprequest"],
urlFilter: params.url,
requestMethods: [requestMethod],
// excludedTabIds: excludedTabIds,
tabIds: [chrome.tabs.TAB_ID_NONE], // 只限于后台 service_worker / offscreen
},
} as chrome.declarativeNetRequest.Rule;
headerModifierMap.set(markerID, { rule, redirectNotManual });
await chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: [ruleId],
addRules: [rule],
});
}
return true;
}
@PermissionVerify.API({
confirm: async (request: GMApiRequest<[GMSend.XHRDetails?]>, sender: IGetSender, GMApiInstance: GMApi) => {
const msgConn = sender.getConnect();
if (!msgConn) {
throw new Error("GM_xmlhttpRequest ERROR: msgConn is undefined");
}
const throwErrorFn = (error: string) => {
msgConn.sendMessage({
action: "onerror",
data: {
status: 0,
responseHeaders: "",
error: error,
readyState: 4, // ERROR. DONE.
},
});
return new Error(error);
};
const details = request.params[0];
if (!details) {
throw throwErrorFn("param is failed");
}
let url;
try {
url = new URL(details.url);
} catch {
const msg = `Refused to connect to "${details.url}": The url is invalid`;
throw throwErrorFn(msg);
}
if (GMApiInstance.gmExternalDependencies.isBlacklistNetwork(url)) {
const msg = `Refused to connect to "${details.url}": URL is blacklisted`;
throw throwErrorFn(msg);
}
const connectMatched = getConnectMatched(request.script.metadata.connect, url, sender);
if (connectMatched === ConnectMatch.ALL) {
// SC: 有 @connect * 就不询问
return true;
} else {
// 如果 @connect 有匹配到就放行
if (connectMatched > 0) {
return true;
}
// @connect 没有匹配,但有列明 @connect 的话,则自动拒绝
if (request.script.metadata.connect?.find((e) => !!e)) {
// 查询数据库权限记录,如果之前用户允许过该域名,则放行,否则拒绝
const ret = await GMApiInstance.permissionVerify.queryPermission(request, {
permission: "cors",
permissionValue: url.hostname,
wildcard: true,
});
if (ret && ret.allow) {
return true;
}
const msg = `Refused to connect to "${details.url}": This domain is not a part of the @connect list`;
throw throwErrorFn(msg);
}
// 其他情况:要询问用户
}
const metadata: { [key: string]: string } = {};
metadata[i18next.t("script_name")] = i18nName(request.script);
metadata[i18next.t("request_domain")] = url.hostname;
metadata[i18next.t("request_url")] = details.url;
return {
permission: "cors",
permissionValue: url.hostname,
title: i18next.t("script_accessing_cross_origin_resource"),
metadata,
describe: i18next.t("confirm_operation_description"),
wildcard: true,
permissionContent: i18next.t("domain"),
} as ConfirmParam;
},
alias: ["GM.xmlHttpRequest"],
})
async GM_xmlhttpRequest(request: GMApiRequest<[GMSend.XHRDetails]>, sender: IGetSender) {
if (!sender.isType(GetSenderType.CONNECT)) {
throw new Error("GM_xmlhttpRequest ERROR: sender is not MessageConnect");
}
// https://github.com/scriptscat/scriptcat/issues/1343
let wakeupTrigger = true;
wakeupPingCommand(WakeUpCommand.START);
const wakeupStop = () => {
try {
if (wakeupTrigger) {
wakeupTrigger = false;
wakeupPingCommand(WakeUpCommand.STOP);
}
} catch {
// ignored
}
};
const msgConn = sender.getConnect()!;
let isConnDisconnected = false;
msgConn.onDisconnect(() => {
isConnDisconnected = true;
wakeupStop();
});
// 关联自己生成的请求id与chrome.webRequest的请求id
// 随机生成(同步),不需要 chrome.storage 存取
const markerID = generateUniqueMarkerID();
const resultParam = new SWRequestResultParams(markerID);
const details = request.params[0];
try {
/*
There are TM-specific parameters:
- cookie a cookie to be patched into the sent cookie set
- cookiePartition object?, containing the partition key to be used for sent and received partitioned cookies
topLevelSite string?, representing the top frame site for partitioned cookies
The ScriptCat implementation for cookie, cookiePartition, cookiePartition.topLevelSite are limited.
*/
// 处理cookiePartition
// 详见 https://github.com/scriptscat/scriptcat/issues/392
// https://github.com/scriptscat/scriptcat/commit/3774aa3acebeadb6b08162625a9af29a9599fa96
// cookiePartition shall refers to the following issue:
// https://github.com/Tampermonkey/tampermonkey/issues/2419
if (!details.cookiePartition || typeof details.cookiePartition !== "object") {
details.cookiePartition = {};
}
if (typeof details.cookiePartition.topLevelSite !== "string") {
// string | undefined
details.cookiePartition.topLevelSite = undefined;
}
// 添加请求header, 处理unsafe hearder
await this.buildDNRRule(markerID, details, sender);
// let finalUrl = "";
// 等待response
let useFetch;
{
const anonymous = details.anonymous ?? details.mozAnon ?? false;
const redirect = details.redirect;
const isFetch = details.fetch ?? false;
const isBufferStream = details.responseType === "stream";
useFetch = isFetch || !!redirect || anonymous || isBufferStream;
}
const loadendCleanUp = () => {
wakeupStop();
redirectedUrls.delete(markerID);
nwErrorResults.delete(markerID);
const reqId = scXhrRequests.get(markerID);
if (reqId) scXhrRequests.delete(reqId);
scXhrRequests.delete(markerID);
headersReceivedMap.delete(markerID);
headerModifierMap.delete(markerID);
};
let strategy: GMXhrStrategy | undefined = undefined;
if (useFetch) {
strategy = new GMXhrFetchStrategy(details, resultParam);
} else if (typeof XMLHttpRequest === "function") {
// No offscreen in Firefox, but Firefox background script itself provides XMLHttpRequest.
// Firefox 中没有 offscreen,但 Firefox 的"后台脚本"本身提供了 XMLHttpRequest。
strategy = new GMXhrXhrStrategy(resultParam);
}
if (strategy) {
const bgGmXhr = new BgGMXhr(details, resultParam, msgConn, strategy);
bgGmXhr.onLoaded(loadendCleanUp);
bgGmXhr.do();
} else {
// 再发送到offscreen, 处理请求
const offscreenCon = await connect(this.msgSender, "offscreen/gmApi/xmlHttpRequest", details);
offscreenCon.onMessage((msg) => {
// 发送到content
let data = msg.data;
// 修正 statusCode 在 接收responseHeader 后会变化的问题 (例如 401 -> 200)
if (msg.data?.status && resultParam.statusCode > 0 && resultParam.statusCode !== msg.data?.status) {
resultParam.resultParamStatusCode = msg.data.status;
}
data = {
...data,
finalUrl: resultParam.finalUrl, // 替换finalUrl
responseHeaders: resultParam.responseHeaders || data.responseHeaders || "", // 替换msg.data.responseHeaders
status: resultParam.statusCode || data.statusCode || data.status,
};
msg = {
action: msg.action,
data: data,
} as TMessageCommAction;
if (msg.action === "onloadend") {
loadendCleanUp();
}
if (!isConnDisconnected) {
msgConn.sendMessage(msg);
}
});
// 关闭连接
msgConn.onDisconnect(offscreenCon.disconnect.bind(offscreenCon));
}
} catch (e: any) {
wakeupStop();
const errorMsg = `GM_xmlhttpRequest ERROR: ${e?.message || e || "Unknown Error"}`;
if (!isConnDisconnected) {
msgConn.sendMessage({
action: "onerror",
data: {
status: resultParam.statusCode,
responseHeaders: resultParam.responseHeaders,
error: errorMsg,
readyState: 4, // ERROR. DONE.
},
});
}
throw new Error(errorMsg);
}
}
@PermissionVerify.API({ alias: ["CAT_registerMenuInput"] })
GM_registerMenuCommand(request: GMApiRequest<GMRegisterMenuCommandParam>, sender: IGetSender): any {
const [key, name, options] = request.params;
// 触发菜单注册, 在popup中处理
this.mq.emit<TScriptMenuRegister>("registerMenuCommand", {
uuid: request.script.uuid,
key,
name,
options,
tabId: sender.getSender()?.tab?.id || -1,
frameId: sender.getSender()?.frameId,
documentId: sender.getSender()?.documentId,
});
}
@PermissionVerify.API({ alias: ["CAT_unregisterMenuInput"] })
GM_unregisterMenuCommand(request: GMApiRequest<GMUnRegisterMenuCommandParam>, sender: IGetSender) {
const [key] = request.params;
// 触发菜单取消注册, 在popup中处理
this.mq.emit<TScriptMenuUnregister>("unregisterMenuCommand", {
uuid: request.script.uuid,
key,
tabId: sender.getSender()?.tab?.id || -1,
frameId: sender.getSender()?.frameId,
documentId: sender.getSender()?.documentId,
});
}
@PermissionVerify.API({})
async GM_openInTab(request: GMApiRequest<[string, GMTypes.SWOpenTabOptions]>, sender: IGetSender) {
const url = request.params[0];
const options = request.params[1];
if (options.useOpen) {
const prevTab = await getCurrentTab();
// 发送给offscreen页面处理 (使用window.open)
let ok;
if (typeof window === "object" && typeof window?.open === "function") {
// Firefox Background Page
ok = nativePageWindowOpen({ url });
} else {
ok = await sendMessage(this.msgSender, "offscreen/gmApi/windowOpen", { url });
}
// 注:一般而言,特殊打开的话没有实际 tab id.
// ------------------------------------------
if (ok) {
// 由于window.open强制在前台打开标签,因此获取状态为 { active:true } 的标签即为新标签
const tab = await getCurrentTab();
const tabId = tab?.id;
if (tabId && tabId !== prevTab?.id) return tabId;
}
// 当新tab被浏览器阻止时 window.open() 会返回 null 视为已经关闭
// 似乎在Firefox中禁止在background页面使用window.open(),强制返回null
return false;
}
const getNewTabId = async () => {
const { tabId, windowId } = sender.getExtMessageSender();
const active = options.active;
let currentTab: chrome.tabs.Tab | undefined;