Skip to content

Commit

Permalink
优化沙盒功能 & 兼容firefox & 修复首次require失败的问题 & 优化代码结构
Browse files Browse the repository at this point in the history
  • Loading branch information
CodFrm committed Apr 17, 2021
1 parent 90e59d2 commit 57d8e6b
Show file tree
Hide file tree
Showing 36 changed files with 296 additions and 332 deletions.
2 changes: 2 additions & 0 deletions build/scriptcat/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"js": [
"src/content.js"
],
"run_at": "document_start",
"all_frames": true
}
],
Expand All @@ -33,6 +34,7 @@
"proxy",
"cookies",
"storage",
"debugger",
"webRequest",
"<all_urls>",
"notifications",
Expand Down
2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ declare namespace GM_Types {

#### GM_xmlhttpRequest

> 部分功能缺失
> 部分功能缺失,cookie功能firefox暂不支持
```typescript
declare function GM_xmlhttpRequest(details: GM_Types.XHRDetails): GM_Types.AbortHandle<void>;
Expand Down
10 changes: 4 additions & 6 deletions docs/cat-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
本扩展特有的API将会以 CAT_ 开头进行定义,如有同步类型的API,也会使用 CAT.* 的方式进行定义.对于某些API为了使用方便会提供GM的别名.



### 定义


Expand Down Expand Up @@ -33,7 +32,6 @@ declare namespace CAT_Types {
```



#### CAT_clearProxy

> 清理代理
Expand All @@ -43,10 +41,10 @@ declare function CAT_clearProxy(): void;
```



#### CAT_click
> 模拟点击
> 真实点击
使用了[Input.dispatchMouseEvent](https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchMouseEvent)实现,请确认元素在可视区域内,且坐标是相对于窗口的位置.
```ts
declare function CAT_click(el: HTMLElement): void;
```
declare function CAT_click(x: number, y: number): void
```
1 change: 1 addition & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* 支持`@require`引用其他脚本
* 将GM_set/getValue函数使其实时全局同步
* 添加了`CAT_click`API,可进行真实点击
* 支持了`GM_setClipboard`

## v0.2.0
> 第一个可用的版本
Expand Down
103 changes: 53 additions & 50 deletions src/apps/grant/background.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { LOGGER_LEVEL_INFO } from "@App/model/logger";
import { Permission, PermissionModel } from "@App/model/permission";
import { Script, SCRIPT_TYPE_BACKGROUND, SCRIPT_TYPE_CRONTAB } from "@App/model/script";
import { PermissionModel } from "@App/model/permission";
import { isFirefox } from "@App/pkg/utils";
import axios from "axios";
import { App } from "../app";
import { AppEvent, PermissionConfirm, ScriptGrant, ScriptValueChange } from "../msg-center/event";
import { MsgCenter } from "../msg-center/msg-center";
import { ScriptManager } from "../script/manager";
import { Grant, Api, IPostMessage, IGrantListener, ConfirmParam, PermissionParam, FreedCallback } from "./interface";
import { v4 as uuidv4 } from "uuid"
import { Value, ValueModel } from "@App/model/value";
import { ValueModel } from "@App/model/value";
import { LOGGER_LEVEL_INFO } from "@App/model/do/logger";
import { Permission } from "@App/model/do/permission";
import { SCRIPT_TYPE_CRONTAB, SCRIPT_TYPE_BACKGROUND, Script } from "@App/model/do/script";
import { Value } from "@App/model/do/value";

class postMessage implements IPostMessage {

Expand Down Expand Up @@ -51,53 +52,56 @@ export class BackgroundGrant {
private constructor(scriptMgr: ScriptManager, listener: IGrantListener) {
this.listener = listener;
this.scriptMgr = scriptMgr;
//处理xhrcookie的问题
chrome.webRequest.onBeforeSendHeaders.addListener((data) => {
let setCookie = '';
let cookie = '';
let anonymous = false;
let cookieIndex = -1;
let requestHeaders: chrome.webRequest.HttpHeader[] = [];
data.requestHeaders?.forEach((val, key) => {
switch (val.name.toLowerCase()) {
case "x-cat-" + this.rand + "-cookie": {
setCookie = val.value || '';
break;
}
case "x-cat-" + this.rand + "-anonymous": {
anonymous = true;
break;
}
case "cookie": {
cookieIndex = key;
cookie = val.value || '';
break;
//处理xhrcookie的问题,firefox不支持
try {
chrome.webRequest.onBeforeSendHeaders.addListener((data) => {
let setCookie = '';
let cookie = '';
let anonymous = false;
let cookieIndex = -1;
let requestHeaders: chrome.webRequest.HttpHeader[] = [];
data.requestHeaders?.forEach((val, key) => {
switch (val.name.toLowerCase()) {
case "x-cat-" + this.rand + "-cookie": {
setCookie = val.value || '';
break;
}
case "x-cat-" + this.rand + "-anonymous": {
anonymous = true;
break;
}
case "cookie": {
cookieIndex = key;
cookie = val.value || '';
break;
}
default: {
requestHeaders.push(val);
}
}
default: {
requestHeaders.push(val);
});
if (anonymous) {
cookie = '';
}
if (setCookie) {
if (!cookie || cookie.endsWith(';')) {
cookie += setCookie;
} else {
cookie += ';' + setCookie;
}
}
});
if (anonymous) {
cookie = '';
}
if (setCookie) {
if (!cookie || cookie.endsWith(';')) {
cookie += setCookie;
} else {
cookie += ';' + setCookie;
cookie && requestHeaders.push({
name: 'cookie',
value: cookie
});
return {
requestHeaders: requestHeaders,
}
}
cookie && requestHeaders.push({
name: 'cookie',
value: cookie
});
return {
requestHeaders: requestHeaders,
}
}, {
urls: ["<all_urls>"],
}, ["blocking", "requestHeaders", "extraHeaders"]);
}, {
urls: ["<all_urls>"],
}, ["blocking", "requestHeaders", "extraHeaders"]);
} catch (e) {
}
}

// 单实例
Expand Down Expand Up @@ -329,7 +333,7 @@ export class BackgroundGrant {
resolve(ret);
});
},
alias: ['GMSC_xmlhttpRequest', 'GM.fetch'],
alias: ['GM.fetch'],
})
protected GM_xmlhttpRequest(grant: Grant, post: IPostMessage): Promise<any> {
return new Promise(resolve => {
Expand Down Expand Up @@ -736,7 +740,6 @@ export class BackgroundGrant {
document.addEventListener('copy', (e: ClipboardEvent) => {
e.preventDefault();
let { type, data } = BackgroundGrant.clipboardData;
console.log(type, data, BackgroundGrant.clipboardData);
(<any>e).clipboardData.setData(type || 'text/plain', data);
})
}
Expand Down
18 changes: 4 additions & 14 deletions src/apps/grant/frontend.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ScriptCache } from "@App/model/script";
import { Value } from "@App/model/value";
import { ScriptCache } from "@App/model/do/script";
import { Value } from "@App/model/do/value";
import { randomString } from "@App/pkg/utils";
import { BrowserMsg } from "../msg-center/browser";
import { AppEvent, ScriptValueChange } from "../msg-center/event";
Expand Down Expand Up @@ -131,16 +131,6 @@ export class FrontendGrant implements ScriptContext {
});
}

@FrontendGrant.GMFunction({ depend: ['GM_xmlhttpRequest'] })
public GMSC_xmlhttpRequest(details: GM_Types.XHRDetails): Promise<GM_Types.XHRResponse> {
return new Promise(resolve => {
details.onload = (xhr) => {
resolve(xhr);
}
this.GM_xmlhttpRequest(details);
});
}

public GM_notification(text: string, title: string, image: string, onclick: Function): void

@FrontendGrant.GMFunction()
Expand Down Expand Up @@ -261,8 +251,8 @@ export class FrontendGrant implements ScriptContext {
}

@FrontendGrant.GMFunction()
public CAT_click(el: HTMLElement): void {
this.postRequest('CAT_click', [el.offsetLeft, el.offsetTop]);
public CAT_click(x: number, y: number): void {
this.postRequest('CAT_click', [x, y]);
}

@FrontendGrant.GMFunction()
Expand Down
2 changes: 1 addition & 1 deletion src/apps/grant/interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Script } from "@App/model/script";
import { Script } from "@App/model/do/script";

export interface Grant {
value: string
Expand Down
13 changes: 2 additions & 11 deletions src/apps/logger/logger.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
import {
Log,
LoggerModel,
LOGGER_LEVEL,
LOGGER_LEVEL_DEBUG,
LOGGER_LEVEL_ERROR,
LOGGER_LEVEL_INFO,
LOGGER_LEVEL_WARN,
LOGGER_TYPE,
LOGGER_TYPE_SYSTEM,
} from "@App/model/logger";
import { LOGGER_LEVEL, Log, LOGGER_LEVEL_INFO, LOGGER_LEVEL_WARN, LOGGER_LEVEL_ERROR, LOGGER_LEVEL_DEBUG } from "@App/model/do/logger";
import { LoggerModel } from "@App/model/logger";

export interface Logger {
// todo 可以改造为可调用实例
Expand Down
7 changes: 4 additions & 3 deletions src/apps/msg-center/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class BrowserMsg {
constructor(id: string) {
this.id = id;
document.addEventListener(this.id, event => {
let detail = (<any>event).detail
let detail = JSON.parse((<any>event).detail);
let ret = this.listenMap.get(detail.topic);
if (ret) {
ret(detail.msg);
Expand All @@ -21,11 +21,12 @@ export class BrowserMsg {
}

public send(topic: string, msg: any) {
// 兼容火狐的序列化
let ev = new CustomEvent(this.id, {
detail: {
detail: JSON.stringify({
topic: topic,
msg: msg,
},
}),
});
document.dispatchEvent(ev);
}
Expand Down
28 changes: 14 additions & 14 deletions src/apps/resource.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { hash, Resource, ResourceLinkModel, ResourceModel } from "@App/model/resource";
import { Resource } from "@App/model/do/resource";
import { ResourceLinkModel, ResourceModel } from "@App/model/resource";
import { SystemConfig } from "@App/pkg/config";
import axios from "axios";
import crypto from "crypto-js";
Expand All @@ -11,20 +12,19 @@ export class ResourceManager {
public addResource(url: string, scriptId: number): Promise<boolean> {
return new Promise(async resolve => {
let u = this.parseUrl(url);
this.getResource(u.url).then(async result => {
if (!result) {
let resource = await this.loadByUrl(u.url);
if (!resource) {
return;
}
resource.createtime = new Date().getTime();
resource.updatetime = new Date().getTime();
await App.Cache.set('resource:' + u.url, resource);
if (await this.model.save(resource)) {
App.Log.Info("resource", u.url, "add");
}
let result = await this.getResource(u.url);
if (!result) {
let resource = await this.loadByUrl(u.url);
if (!resource) {
return resolve(false);
}
});
resource.createtime = new Date().getTime();
resource.updatetime = new Date().getTime();
await App.Cache.set('resource:' + u.url, resource);
if (await this.model.save(resource)) {
App.Log.Info("resource", u.url, "add");
}
}

let link = await this.linkModel.findOne({ url: u.url, scriptId: scriptId });
if (link) {
Expand Down
5 changes: 2 additions & 3 deletions src/apps/script/background.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Script, ScriptCache } from "@App/model/script";
import { Value } from "@App/model/value";
import App from "@App/views/pages/Option";
import { ScriptCache, Script } from "@App/model/do/script";
import { Value } from "@App/model/do/value";
import { CronJob } from "cron";
import { AppEvent, ScriptValueChange } from "../msg-center/event";
import { IScript } from "./interface";
Expand Down
2 changes: 1 addition & 1 deletion src/apps/script/interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Script, ScriptCache } from "@App/model/script";
import { ScriptCache, Script } from "@App/model/do/script";

export interface IScript {
// 用于自动启动
Expand Down
Loading

0 comments on commit 57d8e6b

Please sign in to comment.