-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrules.mjs
More file actions
492 lines (421 loc) · 13.6 KB
/
Copy pathrules.mjs
File metadata and controls
492 lines (421 loc) · 13.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
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
const SUPPORTED_SCHEMES = new Set(["http", "https", "*"]);
export const MAX_USER_AGENT_LENGTH = 1024;
export const MAX_USER_AGENT_HOSTS = 32;
export const MAX_USER_AGENT_HOSTS_LENGTH = 1024;
export function normalizeScriptWorld(value) {
return value === "MAIN" ? "MAIN" : "USER_SCRIPT";
}
function isValidHostname(hostname) {
if (hostname === "*") {
return true;
}
const value = hostname.startsWith("*.") ? hostname.slice(2) : hostname;
if (!value || value.includes("*") || value.length > 253) {
return false;
}
// Chrome match patterns do not accept ports. IPv4, localhost and DNS names
// are all covered by these hostname labels.
return value.split(".").every((label) =>
label.length > 0
&& label.length <= 63
&& /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label)
);
}
export function parseMatchPattern(pattern) {
if (typeof pattern !== "string") {
throw new Error("errorMatchString");
}
const trimmed = pattern.trim();
const match = /^(https?|\*):\/\/([^/]+)(\/.*)$/.exec(trimmed);
if (!match) {
throw new Error("errorMatchFormat");
}
const [, scheme, rawHost, path] = match;
const host = rawHost.toLowerCase();
if (!SUPPORTED_SCHEMES.has(scheme) || !isValidHostname(host)) {
throw new Error("errorMatchSchemeHost");
}
if (!path.startsWith("/")) {
throw new Error("errorMatchPath");
}
if (/\s/.test(path) || path.includes("#")) {
throw new Error("errorMatchWhitespaceFragment");
}
return { scheme, host, path, pattern: `${scheme}://${host}${path}` };
}
function hostMatches(patternHost, hostname) {
const normalized = hostname.toLowerCase();
if (patternHost === "*") {
return true;
}
if (patternHost.startsWith("*.")) {
const base = patternHost.slice(2);
return normalized === base || normalized.endsWith(`.${base}`);
}
return normalized === patternHost;
}
function wildcardMatches(pattern, value) {
const escapedParts = pattern.split("*").map((part) =>
part.replace(/[|\\{}()[\]^$+?.]/g, "\\$&")
);
return new RegExp(`^${escapedParts.join(".*")}$`).test(value);
}
export function matchesUrl(pattern, urlValue) {
let parsedPattern;
let url;
try {
parsedPattern = parseMatchPattern(pattern);
url = new URL(urlValue);
} catch {
return false;
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
return false;
}
const scheme = url.protocol.slice(0, -1);
if (parsedPattern.scheme !== "*" && parsedPattern.scheme !== scheme) {
return false;
}
return hostMatches(parsedPattern.host, url.hostname)
&& wildcardMatches(parsedPattern.path, `${url.pathname}${url.search}`);
}
export function permissionPatternFor(pattern) {
const { scheme, host } = parseMatchPattern(pattern);
return `${scheme}://${host}/*`;
}
function escapeRegex(value) {
return value.replace(/[|\\{}()[\]^$+?.-]/g, "\\$&");
}
export function dnrRegexForMatchPattern(pattern) {
const { scheme, host, path } = parseMatchPattern(pattern);
const schemePattern = scheme === "*" ? "https?" : scheme;
const hostPattern = host === "*"
? "(?:\\[[0-9a-f:]+\\]|[^/:]+)"
: host.startsWith("*.")
? `(?:[^./:]+\\.)*${escapeRegex(host.slice(2))}`
: escapeRegex(host);
const encodedPath = encodeURI(path);
const pathPattern = encodedPath
.split("*")
.map(escapeRegex)
.join(".*");
return `^${schemePattern}:\\/\\/${hostPattern}(?::[0-9]+)?${pathPattern}$`;
}
export function dnrRegexForOrigin(urlValue) {
const url = new URL(urlValue);
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error("errorMatchSchemeHost");
}
return `^${escapeRegex(url.origin)}\\/`;
}
export function parseUserAgentHost(value) {
if (typeof value !== "string" || !value.trim()) {
throw new Error("errorUserAgentHostInvalid");
}
const host = value.trim().toLowerCase();
if (host === "*" || !isValidHostname(host)) {
throw new Error("errorUserAgentHostInvalid");
}
return host;
}
export function normalizeUserAgentHosts(values) {
const input = Array.isArray(values)
? values
: (typeof values === "string" ? [values] : []);
const hosts = [];
const indexes = [];
const errors = [];
const seen = new Set();
input.forEach((value, index) => {
const trimmed = typeof value === "string" ? value.trim() : "";
if (!trimmed) {
return;
}
try {
const host = parseUserAgentHost(trimmed);
if (!seen.has(host)) {
seen.add(host);
hosts.push(host);
indexes.push(index);
}
} catch (error) {
errors.push({ index, message: error.message });
}
});
if (hosts.length > MAX_USER_AGENT_HOSTS) {
errors.push({
index: indexes[MAX_USER_AGENT_HOSTS],
message: "errorUserAgentHostsTooMany"
});
}
if (hosts.join("\n").length > MAX_USER_AGENT_HOSTS_LENGTH) {
let length = 0;
let overflowIndex = indexes.at(-1) || 0;
hosts.some((host, index) => {
length += host.length + (index > 0 ? 1 : 0);
if (length > MAX_USER_AGENT_HOSTS_LENGTH) {
overflowIndex = indexes[index];
return true;
}
return false;
});
errors.push({ index: overflowIndex, message: "errorUserAgentHostsTooLong" });
}
const safeHosts = hosts.slice(0, MAX_USER_AGENT_HOSTS);
while (safeHosts.join("\n").length > MAX_USER_AGENT_HOSTS_LENGTH) {
safeHosts.pop();
}
return { hosts: safeHosts, errors };
}
export function permissionPatternForUserAgentHost(value) {
return `*://${parseUserAgentHost(value)}/*`;
}
export function dnrRegexForUserAgentHost(value) {
const host = parseUserAgentHost(value);
const hostPattern = host.startsWith("*.")
? `(?:[^./:]+\\.)*${escapeRegex(host.slice(2))}`
: escapeRegex(host);
return `^(?:https?|wss?):\\/\\/${hostPattern}(?::[0-9]+)?\\/`;
}
export function dnrRegexForUserAgentTargets(urlValue, hosts) {
const patterns = [
dnrRegexForOrigin(urlValue),
...normalizeUserAgentHosts(hosts).hosts.map(dnrRegexForUserAgentHost)
];
return `^(?:${patterns.map((pattern) => pattern.slice(1)).join("|")})`;
}
export function parseResourceUrl(value) {
if (typeof value !== "string" || !value.trim()) {
throw new Error("errorResourceRequired");
}
let url;
try {
url = new URL(value.trim());
} catch {
throw new Error("errorResourceInvalid");
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error("errorResourceScheme");
}
if (url.username || url.password) {
throw new Error("errorResourceCredentials");
}
return url.href;
}
export function permissionPatternForResourceUrl(value) {
const url = new URL(parseResourceUrl(value));
return `${url.protocol}//${url.hostname}/*`;
}
export function normalizeResourceUrls(values) {
const input = Array.isArray(values)
? values
: (typeof values === "string" ? [values] : []);
const urls = [];
const errors = [];
const seen = new Set();
input.forEach((value, index) => {
const trimmed = typeof value === "string" ? value.trim() : "";
if (!trimmed) {
return;
}
try {
const normalized = parseResourceUrl(trimmed);
if (!seen.has(normalized)) {
seen.add(normalized);
urls.push(normalized);
}
} catch (error) {
errors.push({ index, message: error.message });
}
});
return { urls, errors };
}
function ruleUrls(rule, pluralKey, legacyKey) {
if (Array.isArray(rule?.[pluralKey])) {
return rule[pluralKey];
}
return typeof rule?.[legacyKey] === "string" && rule[legacyKey].trim()
? [rule[legacyKey]]
: [];
}
export function jsResourcePermissionPatterns(rule) {
const patterns = new Set();
for (const value of ruleUrls(rule, "jsUrls", "jsUrl")) {
if (typeof value === "string" && value.trim()) {
patterns.add(permissionPatternForResourceUrl(value));
}
}
return [...patterns];
}
export function userAgentHostPermissionPatterns(rule) {
if (!ruleHasUserAgent(rule)) {
return [];
}
return normalizeUserAgentHosts(rule?.userAgentHosts).hosts
.map(permissionPatternForUserAgentHost);
}
export function rulePermissionPatterns(rule) {
return [
...new Set([
permissionPatternFor(rule.match),
...jsResourcePermissionPatterns(rule),
...userAgentHostPermissionPatterns(rule)
])
];
}
export async function findMissingRulePermissions(rules, containsOrigin) {
const patternsByRuleId = new Map();
const uniquePatterns = new Set();
for (const rule of Array.isArray(rules) ? rules : []) {
if (!rule?.enabled || !rule.id) {
continue;
}
const patterns = rulePermissionPatterns(rule);
patternsByRuleId.set(rule.id, patterns);
patterns.forEach((pattern) => uniquePatterns.add(pattern));
}
const grantedEntries = await Promise.all(
[...uniquePatterns].map(async (pattern) => [
pattern,
await containsOrigin(pattern)
])
);
const grantedByPattern = new Map(grantedEntries);
const missingByRuleId = new Map();
for (const [ruleId, patterns] of patternsByRuleId) {
const missing = patterns.filter((pattern) => !grantedByPattern.get(pattern));
if (missing.length > 0) {
missingByRuleId.set(ruleId, missing);
}
}
return missingByRuleId;
}
export function normalizeRule(rule) {
const cssUrls = normalizeResourceUrls(ruleUrls(rule, "cssUrls", "cssUrl")).urls;
const jsUrls = normalizeResourceUrls(ruleUrls(rule, "jsUrls", "jsUrl")).urls;
const userAgentHosts = normalizeUserAgentHosts(rule?.userAgentHosts).hosts;
return {
id: typeof rule?.id === "string" ? rule.id : "",
name: typeof rule?.name === "string" ? rule.name.trim() : "",
match: typeof rule?.match === "string" ? rule.match.trim() : "",
css: typeof rule?.css === "string" ? rule.css.trim() : "",
cssUrls,
js: typeof rule?.js === "string" ? rule.js.trim() : "",
jsUrls,
jsWorld: normalizeScriptWorld(rule?.jsWorld),
userAgent: typeof rule?.userAgent === "string" ? rule.userAgent.trim() : "",
userAgentHosts,
enabled: rule?.enabled === true
};
}
export function ruleHasUserAgent(rule) {
return typeof rule?.userAgent === "string" && Boolean(rule.userAgent.trim());
}
export function ruleHasJavaScript(rule) {
return Boolean(rule?.js?.trim() || ruleUrls(rule, "jsUrls", "jsUrl").length);
}
export function ruleHasContent(rule) {
return Boolean(
rule?.css?.trim()
|| ruleUrls(rule, "cssUrls", "cssUrl").length
|| rule?.js?.trim()
|| ruleUrls(rule, "jsUrls", "jsUrl").length
|| ruleHasUserAgent(rule)
);
}
function userAgentSpecificity(rule, index) {
const { scheme, host, path } = parseMatchPattern(rule.match);
const hostRank = host === "*" ? 0 : (host.startsWith("*.") ? 1 : 2);
const pathLiteralLength = path.replaceAll("*", "").length;
const schemeRank = scheme === "*" ? 0 : 1;
return [hostRank, pathLiteralLength, schemeRank, index];
}
function compareSpecificity(left, right) {
for (let index = 0; index < left.length; index += 1) {
if (left[index] !== right[index]) {
return left[index] - right[index];
}
}
return 0;
}
export function selectUserAgentRule(rules, urlValue) {
let selected = null;
let selectedSpecificity = null;
(Array.isArray(rules) ? rules : []).forEach((rule, index) => {
if (!rule?.enabled || !ruleHasUserAgent(rule) || !matchesUrl(rule.match, urlValue)) {
return;
}
const specificity = userAgentSpecificity(rule, index);
if (!selected || compareSpecificity(specificity, selectedSpecificity) > 0) {
selected = rule;
selectedSpecificity = specificity;
}
});
return selected;
}
export function sortUserAgentRulesByPriority(rules) {
return (Array.isArray(rules) ? rules : [])
.map((rule, index) => ({ rule, specificity: userAgentSpecificity(rule, index) }))
.sort((left, right) => compareSpecificity(left.specificity, right.specificity))
.map((entry) => entry.rule);
}
export function ruleDisplayName(rule) {
const name = typeof rule?.name === "string" ? rule.name.trim() : "";
if (name) {
return name;
}
const match = typeof rule?.match === "string" ? rule.match.trim() : "";
try {
const { host } = parseMatchPattern(match);
return host.startsWith("*.") ? host.slice(2) : host;
} catch {
return match;
}
}
export function validateRuleInput(input) {
const errors = {};
const name = typeof input?.name === "string" ? input.name.trim() : "";
const match = typeof input?.match === "string" ? input.match.trim() : "";
const css = typeof input?.css === "string" ? input.css.trim() : "";
const js = typeof input?.js === "string" ? input.js.trim() : "";
const userAgent = typeof input?.userAgent === "string" ? input.userAgent.trim() : "";
const cssUrlResult = normalizeResourceUrls(input?.cssUrls);
const jsUrlResult = normalizeResourceUrls(input?.jsUrls);
const userAgentHostResult = normalizeUserAgentHosts(input?.userAgentHosts);
try {
parseMatchPattern(match);
} catch (error) {
errors.match = error.message;
}
if (cssUrlResult.errors.length > 0) {
errors.cssUrls = cssUrlResult.errors;
}
if (jsUrlResult.errors.length > 0) {
errors.jsUrls = jsUrlResult.errors;
}
if (userAgentHostResult.errors.length > 0) {
errors.userAgentHosts = userAgentHostResult.errors;
}
if (userAgent.length > MAX_USER_AGENT_LENGTH) {
errors.userAgent = "errorUserAgentTooLong";
} else if (/[\u0000-\u001f\u007f]/.test(userAgent)) {
errors.userAgent = "errorUserAgentControlCharacters";
}
const value = {
name,
match,
css,
cssUrls: cssUrlResult.urls,
js,
jsUrls: jsUrlResult.urls,
jsWorld: normalizeScriptWorld(input?.jsWorld),
userAgent,
userAgentHosts: userAgentHostResult.hosts,
enabled: Boolean(input?.enabled)
};
return {
valid: Object.keys(errors).length === 0,
errors,
value
};
}