-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathuserscript_manager_logic.mjs
240 lines (221 loc) · 9.67 KB
/
userscript_manager_logic.mjs
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
// A userscript manager runs user-defined scripts (called userscripts) on
// websites based on the metadata that is encoded in the userscript source text.
// For history, see https://en.wikipedia.org/wiki/Userscript
//
// This file provides a partial implementation of a userscript manager, and
// exports the following functions that are called by code in background.js:
//
// - parseUserScript() - parses userscript source text to a representation of
// the user script for use with the "browser.userScripts" extension API.
//
// - computeScriptDifferences() - compares two representations of a user script
// and returns whether they have changed. This is used for determining which
// scripts should be updated, when the actual registrations are compared with
// the scripts in the extension storage. As script registration is relatively
// expensive, this enables updating only the scripts that have changed.
//
// - handleUserScriptMessage() - Handles browser.runtime.onUserScriptMessage
// event, which is triggered when a script in the USER_SCRIPT world invokes
// the browser.runtime.sendMessage() method (see userscript_api.js).
export function parseUserScript(userScriptText) {
let metadata = parseMetadataBlock(userScriptText);
if (!metadata) {
console.warn("Ignoring non-userscript input");
return null;
}
// Create object for use with browser.userScripts.register():
let registeredUserScript = {
// The userScripts API requires each script to have a unique ID that does
// not start with "_". The userscript format specifies the identifier of
// a script is formed from @namespace and @name:
// https://wiki.greasespot.net/Metadata_Block#@name
// https://violentmonkey.github.io/api/metadata-block/#name
id: JSON.stringify([ metadata.get("@namespace"), metadata.get("@name") ]),
js: null, // js is a required array and will be set below.
// All of the following fields are optional.
allFrames: !metadata.has("@noframes"),
matches: metadata.getArray("@match"),
excludeMatches: metadata.getArray("@exclude-match"),
includeGlobs: metadata.getArray("@include"),
excludeGlobs: metadata.getArray("@exclude"),
runAt: parseRunAt(metadata.get("@run-at")),
world: null, // "MAIN" or "USER_SCRIPT", set below.
worldId: null, // Can only be set if world is "USER_SCRIPT", set below.
};
// See https://wiki.greasespot.net/@grant
// When "@grant" is used, the userscript requests access to extra APIs that
// are not available to regular web pages.
let grants = parseGrants(metadata.getArray("@grant"));
if (grants.length === 0) {
// When the userscript does not request any additional APIs, we only need
// to execute one script: the original userscript source code.
registeredUserScript.js = [{ code: userScriptText }];
// When no additional APIs are granted, it is not strictly necessary to
// isolate the code from the web page, and therefore we use the "MAIN"
// world.
registeredUserScript.world = "MAIN";
registeredUserScript.worldId = "";
} else {
// When the userscript defines "@grant", it requests access to several
// userscript-specific APIs. These are not provided by the browser, but
// the responsibility of the user script manager extension.
// See userscript_api.js for an explanation of this logic.
registeredUserScript.js = [
{ file: "userscript_api.js" },
// initCustomAPIForUserScripts is defined in userscript_api.js
{ code: `initCustomAPIForUserScripts(${JSON.stringify(grants)})`},
{ code: userScriptText },
];
// If extra APIs are requested, we need to define a sandbox that isolates
// the execution environment of the userscript from the web page, or else
// the page can try to interfere with the userscript, and at worst abuse
// privileged functionality.
registeredUserScript.world = "USER_SCRIPT";
// To isolate different userscript scripts from each other, we create a
// unique world for each user script. This enables us to effectively
// implement access control per script.
registeredUserScript.worldId = Math.random().toString();
}
return registeredUserScript;
}
function parseMetadataBlock(userScriptText) {
// Parse userscript metadata block, which is in the following format:
// // ==UserScript==
// // @key value
// // ==/UserScript==
// See https://wiki.greasespot.net/Metadata_Block
let header = `\n${userScriptText}\n`.split("\n// ==UserScript==\n", 2)[1];
if (!header) {
console.error("UserScript header start not found");
return null;
}
header = header.split("\n// ==/UserScript==\n")[0];
if (!header) {
console.error("UserScript header end not found");
return null;
}
let metadata = new Map();
for (let line of header.split("\n")) {
let match = /^\/\/ (@\S+)(\s+.*)?$/.exec(line);
if (!match) {
console.warn(`Skipping invalid UserScript header line: ${line}`);
continue;
}
let [, key, value] = match;
if (!metadata.has(key)) {
metadata.set(key, []);
}
metadata.get(key).push(value.trim());
}
return {
rawHeader: header,
has: key => metadata.has(key),
get: key => metadata.get(key)?.[0],
getArray: key => metadata.get(key) || [],
};
}
function parseRunAt(runAtFromUserScriptMetadata) {
// Transforms some of the supported @run-at values to the values
// https://wiki.greasespot.net/Metadata_Block#.40run-at
// https://www.tampermonkey.net/documentation.php#meta:run_at
// https://violentmonkey.github.io/api/metadata-block/#run-at
switch (runAtFromUserScriptMetadata) {
case "document-start": return "document_start";
case "document-end": return "document_end";
case "document-idle": return "document_idle";
// Default if unspecified or not recognized. Some userscript managers
// support more values, the extension API only recognizes the above three.
default: return "document_idle";
}
}
function isSameRegisteredUserScript(oldScript, newScript) {
// In general, to test whether two RegisteredUserScript are equal, we have to
// compare each property (and if undefined/null, use the default value).
//
// In this demo, the parseUserScripts function generated all of the script's
// properties from an input code string, which is also the last item of the
// "js" array. Comparing these is enough to test whether they are the same.
return oldScript.js.at(-1).code === newScript.js.at(-1).code;
}
export function computeScriptDifferences(oldScripts, newScripts) {
let scriptIdsToRemove = [];
let scriptsToUpdate = [];
let scriptsToRegister = [];
for (let script of oldScripts) {
if (!newScripts.some(s => s.id === script.id)) {
// old script no longer exists. We should remove it.
scriptIdsToRemove.push(script.id);
}
}
for (let script of newScripts) {
let oldScript = oldScripts.find(s => s.id === script.id);
if (!oldScript) {
scriptsToRegister.push(script);
} else if (!isSameRegisteredUserScript(script, oldScript)) {
// Script was updated, remove old one and register new one.
scriptsToUpdate.push(script);
} else {
// oldScript is kept when we do not update or remove it.
}
}
return { scriptIdsToRemove, scriptsToUpdate, scriptsToRegister };
}
function parseGrants(grantsFromUserScriptMetadata) {
// Userscripts may access privileged APIs as defined in:
// https://wiki.greasespot.net/@grant
// https://violentmonkey.github.io/api/metadata-block/#grant
// https://www.tampermonkey.net/documentation.php#meta:grant
let grants = [];
for (let grant of grantsFromUserScriptMetadata) {
if (grant === "none") {
// "@grant none" is equivalent to no grants.
return [];
}
// Although there are many APIs, we only support a small subset in this
// demo. ee handleUserScriptMessage() below and userscript_api.js.
if (grant === "GM_info" || grant === "GM_openInTab") {
grants.push(grant);
} else {
console.warn(`@grant ${grant} is not implemented`);
}
}
return grants;
}
export async function handleUserScriptMessage(message, sender) {
// This is the runtime.onUserScriptMessage handler that implements the
// privileged functionality to support functionality in userscript_api.js
// TODO: Validate that the message is allowed.
// sender.userScriptWorldId can be used to look up the world and the scripts
// that execute within.
if (message.userscript_api_name === "GM_openInTab") {
await browser.tabs.create({ url: message.args[0] });
return;
}
if (message.userscript_api_name === "GM_info") {
// In parseUserScripts(), each generated script has a unique worldId, so if
// the script is still registered, we can discover the script registration.
// For simplicity, we extract the original userscript source text from it.
let scripts = await browser.userScripts.getScripts();
let script = scripts.find(s => s.worldId === sender.userScriptWorldId);
let userScriptText = script.js.at(-1).code;
// Minimal implementation of GM_info, based on:
// https://wiki.greasespot.net/GM.info
let metadata = parseMetadataBlock(userScriptText);
return {
script: {
description: metadata.get("@description"),
excludes: metadata.getArray("@exclude"),
includes: metadata.getArray("@include"),
matches: metadata.getArray("@match"),
name: metadata.get("@name"),
namespace: metadata.get("@namespace"),
"run-at": metadata.get("@run-at"),
version: metadata.get("@version"),
},
scriptMetaStr: metadata.rawHeader,
scriptHandler: "[Name of my Userscript Manager]",
version: browser.runtime.getManifest().version,
};
}
console.error("Unexpected message", message);
}