forked from ScratchAddons/ScratchAddons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget-userscripts.js
More file actions
408 lines (383 loc) · 15.6 KB
/
Copy pathget-userscripts.js
File metadata and controls
408 lines (383 loc) · 15.6 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
import changeAddonState from "./imports/change-addon-state.js";
import { getMissingOptionalPermissions } from "./imports/util.js";
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.replaceTabWithUrl) chrome.tabs.update(sender.tab.id, { url: request.replaceTabWithUrl });
else if (request.getEnabledAddons) {
let enabled = Object.keys(scratchAddons.localState.addonsEnabled).filter(
(addonId) => scratchAddons.localState.addonsEnabled[addonId]
);
const tag = request.getEnabledAddons.tag;
if (tag) {
enabled = enabled.filter((id) =>
scratchAddons.manifests.some(({ addonId, manifest }) => addonId === id && manifest.tags.includes(tag))
);
}
sendResponse(enabled);
}
});
scratchAddons.localEvents.addEventListener("addonDynamicEnable", ({ detail }) => {
const { addonId, manifest } = detail;
chrome.tabs.query({}, (tabs) =>
tabs.forEach((tab) => {
if (tab.url || (!tab.url && typeof browser !== "undefined")) {
chrome.tabs.sendMessage(tab.id, "getInitialUrl", { frameId: 0 }, (res) => {
void chrome.runtime.lastError;
if (res) {
(async () => {
const { userscripts, userstyles, cssVariables } = await getAddonData({ addonId, url: res, manifest });
if (userscripts.length || userstyles.length) {
chrome.tabs.sendMessage(
tab.id,
{
dynamicAddonEnabled: {
scripts: userscripts,
userstyles,
cssVariables,
addonId,
injectAsStyleElt: !!manifest.injectAsStyleElt,
index: scratchAddons.manifests.findIndex((addon) => addon.addonId === addonId),
dynamicEnable: Boolean(manifest.dynamicEnable),
dynamicDisable: Boolean(manifest.dynamicDisable),
},
},
{ frameId: 0 }
);
}
})();
}
});
}
})
);
});
scratchAddons.localEvents.addEventListener("addonDynamicDisable", ({ detail }) => {
const { addonId } = detail;
chrome.tabs.query({}, (tabs) =>
tabs.forEach((tab) => {
if (tab.url || (!tab.url && typeof browser !== "undefined")) {
chrome.tabs.sendMessage(
tab.id,
{ dynamicAddonDisable: { addonId } },
{ frameId: 0 },
() => void chrome.runtime.lastError
);
}
})
);
});
scratchAddons.localEvents.addEventListener("updateUserstylesSettingsChange", ({ detail }) => {
const { addonId, manifest } = detail;
chrome.tabs.query({}, (tabs) =>
tabs.forEach((tab) => {
if (tab.url || (!tab.url && typeof browser !== "undefined")) {
chrome.tabs.sendMessage(tab.id, "getInitialUrl", { frameId: 0 }, (res) => {
if (res) {
(async () => {
const { userscripts, userstyles, cssVariables } = await getAddonData({ addonId, url: res, manifest });
chrome.tabs.sendMessage(
tab.id,
{
updateUserstylesSettingsChange: {
scripts: userscripts,
userstyles,
cssVariables,
addonId,
injectAsStyleElt: !!manifest.injectAsStyleElt,
index: scratchAddons.manifests.findIndex((addon) => addon.addonId === addonId),
},
},
{ frameId: 0 }
);
})();
}
});
}
})
);
});
async function getAddonData({ addonId, manifest, url }) {
const promises = [];
const userscripts = [];
for (const script of manifest.userscripts || []) {
if (userscriptMatches({ url }, script, addonId))
userscripts.push({
url: script.url,
runAtComplete: typeof script.runAtComplete === "boolean" ? script.runAtComplete : true,
});
}
const userstyles = [];
for (const style of manifest.userstyles || []) {
if (userscriptMatches({ url }, style, addonId))
if (manifest.injectAsStyleElt) {
// Reserve index in array to avoid race conditions (#700)
const arrLength = userstyles.push(null);
const indexToUse = arrLength - 1;
promises.push(
fetch(chrome.runtime.getURL(`/addons/${addonId}/${style.url}`))
.then((res) => res.text())
.then((text) => {
// Replace %addon-self-dir% for relative URLs
text = text.replace(/\%addon-self-dir\%/g, chrome.runtime.getURL(`addons/${addonId}`));
// Provide source url
text += `\n/*# sourceURL=${style.url} */`;
userstyles[indexToUse] = text;
})
);
} else {
userstyles.push(chrome.runtime.getURL(`/addons/${addonId}/${style.url}`));
}
}
await Promise.all(promises);
return { userscripts, userstyles, cssVariables: manifest.customCssVariables || [] };
}
async function getContentScriptInfo(url) {
const data = {
url,
httpStatusCode: null, // Set by webRequest onResponseStarted listener
globalState: {},
addonsWithUserscripts: [],
addonsWithUserstyles: [],
};
const promises = [];
const missingPermissions = await getMissingOptionalPermissions();
scratchAddons.manifests.forEach(async ({ addonId, manifest }, i) => {
if (!scratchAddons.localState.addonsEnabled[addonId]) return;
if (manifest.permissions?.some((p) => missingPermissions.includes(p))) {
changeAddonState(addonId, false);
return;
}
const promise = getAddonData({ addonId, manifest, url });
promises.push(promise);
const { userscripts, userstyles, cssVariables } = await promise;
if (userscripts.length) data.addonsWithUserscripts.push({ addonId, scripts: userscripts });
if (userstyles.length)
data.addonsWithUserstyles.push({
addonId,
styles: userstyles,
cssVariables,
injectAsStyleElt: manifest.injectAsStyleElt,
index: i,
});
});
await Promise.all(promises);
data.globalState = scratchAddons.globalState._target;
return data;
}
function createCsIdentity({ tabId, frameId, url }) {
// String that should uniquely identify a tab/iframe in the csInfoCache map
return `${tabId}/${frameId}@${url}`;
}
const csInfoCache = new Map();
// Using this event to preload contentScriptInfo ASAP, since onBeforeRequest
// obviously happens before the content script has a chance to send us a message.
// However, SA should work just fine even if this event does not trigger
// (example: on browser startup, with a Scratch page opening on startup).
chrome.webRequest.onBeforeRequest.addListener(
async (request) => {
if (!scratchAddons.localState.allReady) return;
const identity = createCsIdentity({ tabId: request.tabId, frameId: request.frameId, url: request.url });
const loadingObj = { loading: true };
csInfoCache.set(identity, loadingObj);
const info = await getContentScriptInfo(request.url);
if (csInfoCache.get(identity) !== loadingObj) {
// Another content script with same identity took our
// place in the csInfoCache map while the promise resolved
return;
}
csInfoCache.set(identity, { loading: false, info, timestamp: Date.now() });
scratchAddons.localEvents.dispatchEvent(new CustomEvent("csInfoCacheUpdated"));
},
{
urls: ["https://scratch.mit.edu/*"],
types: ["main_frame", "sub_frame"],
}
);
// It is not uncommon to cache objects that will never be used
// Example: going to https://scratch.mit.edu/studios/104 (no slash after 104)
// will redirect to /studios/104/ (with a slash)
// If a cache entry is too old, remove it
chrome.alarms.create("cleanCsInfoCache", { periodInMinutes: 1 });
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === "cleanCsInfoCache") {
csInfoCache.forEach((obj, key) => {
if (!obj.loading) {
const currentTimestamp = Date.now();
const objTimestamp = obj.timestamp;
if (currentTimestamp - objTimestamp > 45000) {
csInfoCache.delete(key);
}
}
});
}
});
chrome.webRequest.onResponseStarted.addListener(
(request) => {
const identity = createCsIdentity({ tabId: request.tabId, frameId: request.frameId, url: request.url });
const cacheEntry = csInfoCache.get(identity);
if (cacheEntry && cacheEntry.loading === false) {
cacheEntry.info.httpStatusCode = request.statusCode;
}
},
{
urls: ["https://scratch.mit.edu/*"],
types: ["main_frame"],
}
);
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (!request.contentScriptReady) return;
if (scratchAddons.localState.allReady) {
const identity = createCsIdentity({
tabId: sender.tab.id,
frameId: sender.frameId,
url: request.contentScriptReady.url,
});
const getCacheEntry = () => csInfoCache.get(identity);
let cacheEntry = getCacheEntry();
if (cacheEntry) {
if (cacheEntry.loading) {
scratchAddons.localEvents.addEventListener("csInfoCacheUpdated", function thisFunction() {
cacheEntry = getCacheEntry();
if (!cacheEntry) {
scratchAddons.localEvents.removeEventListener("csInfoCacheUpdated", thisFunction);
} else if (!cacheEntry.loading) {
sendResponse(cacheEntry.info);
csInfoCache.delete(identity);
scratchAddons.localEvents.removeEventListener("csInfoCacheUpdated", thisFunction);
}
});
return true;
} else {
sendResponse(cacheEntry.info);
csInfoCache.delete(identity);
}
} else {
getContentScriptInfo(request.contentScriptReady.url).then((info) => {
sendResponse(info);
});
return true;
}
} else {
// Wait until manifests and addon.settings are ready
scratchAddons.localEvents.addEventListener(
"ready",
async () => {
const info = await getContentScriptInfo(request.contentScriptReady.url);
sendResponse(info);
},
{ once: true }
);
return true;
}
});
// In case a tab messaged us before we registered the event above,
// we notify them they can resend the contentScriptInfo message
chrome.tabs.query({}, (tabs) =>
tabs.forEach((tab) => {
if (tab.url || (!tab.url && typeof browser !== "undefined")) {
chrome.tabs.sendMessage(tab.id, "backgroundListenerReady", () => void chrome.runtime.lastError);
}
})
);
// Pathname patterns. Make sure NOT to set global flag!
// Don't forget ^ and $
const WELL_KNOWN_PATTERNS = {
projects: /^\/projects\/(?:editor|\d+(?:\/(?:fullscreen|editor))?)\/?$/,
projectEmbeds: /^\/projects\/\d+\/embed\/?$/,
studios: /^\/studios\/\d+(?:\/(?:projects|comments|curators|activity))?\/?$/,
profiles: /^\/users\/[\w-]+\/?$/,
topics: /^\/discuss\/topic\/\d+\/?$/,
newPostScreens: /^\/discuss\/(?:topic\/\d+|\d+\/topic\/add)\/?$/,
editingScreens: /^\/discuss\/(?:topic\/\d+|\d+\/topic\/add|post\/\d+\/edit|settings\/[\w-]+)\/?$/,
forums: /^\/discuss(?!\/m(?:$|\/))(?:\/.*)?$/,
scratchWWWNoProject:
/^\/(?:(?:about|annual-report(?:\/\d+)?|camp|conference\/20(?:1[79]|[2-9]\d|18(?:\/(?:[^\/]+\/details|expect|plan|schedule))?)|contact-us|code_of_ethics|credits|developers|DMCA|download(?:\/scratch2)?|educators(?:\/faq|register|waiting)?|explore\/(?:project|studio)s\/\w+(?:\/\w+)?|community_guidelines|faq|ideas|join|messages|parents|privacy_policy|research|scratch_1\.4|search\/(?:project|studio)s|starter-projects|classes\/(?:complete_registration|[^\/]+\/register\/[^\/]+)|signup\/[^\/]+|terms_of_use|wedo(?:-legacy)?|ev3|microbit|vernier|boost|studios\/\d*(?:\/(?:projects|comments|curators|activity))?)\/?)?$/,
};
const WELL_KNOWN_MATCHERS = {
isNotScratchWWW: (match) => {
const { projects, projectEmbeds, scratchWWWNoProject } = WELL_KNOWN_PATTERNS;
return !(projects.test(match) || projectEmbeds.test(match) || scratchWWWNoProject.test(match));
},
};
function matchesIf(injectable, settings) {
// injectable.if is guaranteed to exist
// addonEnabled and settings are AND-ed
// settings keys are AND-ed
// addonEnabled and settings values are OR-ed
/**
* Formula:
* NOT (
* (addonEnabled exists AND all of the addons are disabled) OR
* (settings exists AND there is a setting where none of potential values match)
* )
* Or,
* NOT (
* (addonEnabled AND AND(addons**Dis**abled)) OR
* (settings exists AND OR(AND(settings do **NOT** match)))
* )
*/
return !(
(injectable.if.addonEnabled?.length &&
(Array.isArray(injectable.if.addonEnabled) ? injectable.if.addonEnabled : [injectable.if.addonEnabled]).every(
(addon) => !scratchAddons.localState.addonsEnabled[addon]
)) ||
(injectable.if.settings &&
Object.keys(injectable.if.settings).some((settingName) =>
(Array.isArray(injectable.if.settings[settingName])
? injectable.if.settings[settingName]
: [injectable.if.settings[settingName]]
).every((possibleValue) => settings[settingName] !== possibleValue)
))
);
}
// regexPattern = "^https:(absolute-regex)" | "^(relative-regex)"
// matchesPattern = "*" | regexPattern | Array<wellKnownName | wellKnownMatcher | regexPattern | legacyPattern>
function userscriptMatches(data, scriptOrStyle, addonId) {
if (scriptOrStyle.if && !matchesIf(scriptOrStyle, scratchAddons.globalState.addonSettings[addonId])) return false;
const url = data.url;
const parsedURL = new URL(url);
const { matches, _scratchDomainImplied } = scriptOrStyle;
const parsedPathname = parsedURL.pathname;
const parsedOrigin = parsedURL.origin;
const originPath = parsedOrigin + parsedPathname;
const matchURL = _scratchDomainImplied ? parsedPathname : originPath;
const scratchOrigin = "https://scratch.mit.edu";
const isScratchOrigin = parsedOrigin === scratchOrigin;
// "*" is used for any URL on Scratch origin
if (matches === "*") return isScratchOrigin;
// matches becomes RegExp if it is a string that starts with ^
// See load-addon-manifests.js
if (matches instanceof RegExp) {
if (_scratchDomainImplied && !isScratchOrigin) return false;
return matches.test(matchURL);
}
for (const match of matches) {
if (match instanceof RegExp) {
if (match._scratchDomainImplied && !isScratchOrigin) continue;
if (match.test(match._scratchDomainImplied ? parsedPathname : originPath)) {
return true;
}
} else if (Object.prototype.hasOwnProperty.call(WELL_KNOWN_PATTERNS, match)) {
if (isScratchOrigin && WELL_KNOWN_PATTERNS[match].test(parsedPathname)) return true;
} else if (Object.prototype.hasOwnProperty.call(WELL_KNOWN_MATCHERS, match)) {
if (isScratchOrigin && WELL_KNOWN_MATCHERS[match](parsedPathname)) return true;
} else if (urlMatchesLegacyPattern(match, parsedURL)) return true;
}
return false;
}
function urlMatchesLegacyPattern(pattern, urlUrl) {
const patternUrl = new URL(pattern);
// We assume both URLs start with https://scratch.mit.edu
const patternPath = patternUrl.pathname.split("/");
const urlPath = urlUrl.pathname.split("/");
// Implicit slash at the end of the URL path, if it's not there
if (urlPath[urlPath.length - 1] !== "") urlPath.push("");
// Implicit slash at the end of the pattern, unless it's a wildcard
if (patternPath[patternPath.length - 1] !== "" && patternPath[patternPath.length - 1] !== "*") patternPath.push("");
while (patternPath.length) {
// shift() removes the first item of an array, and returns it
const patternItem = patternPath.shift();
const urlItem = urlPath.shift();
if (patternItem !== urlItem && patternItem !== "*") return false;
}
return true;
}