-
Notifications
You must be signed in to change notification settings - Fork 1
/
purlfy.js
584 lines (568 loc) · 22.7 KB
/
purlfy.js
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
class Purlfy extends EventTarget {
// Static properties
/**
* Returns the version of the library.
* @returns {string} The version of the library.
*/
static get version() {
return "0.3.10";
};
/**
* A TextDecoder object used internally.
* @type {TextDecoder}
*/
static #decoder = new TextDecoder();
/**
* A DOMParser object used internally.
* @type {DOMParser | null}
*/
static #domParser = typeof DOMParser !== "undefined" ? new DOMParser() : null;
/**
* The constructor of the AsyncFunction class.
* @type {Function}
*/
static #AsyncFunction = async function () { }.constructor;
/**
* The initial statistics object. (All values are 0)
* @type {Object}
*/
static #zeroStatistics = {
url: 0,
param: 0,
decoded: 0,
redirected: 0,
visited: 0,
char: 0
};
/**
* The default acts for URL purification.
* @type {Object}
*/
static #acts = {
url: decodeURIComponent,
base64: s => { // https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa#unicode_strings
s = s.replaceAll('_', '/').replaceAll('-', '+');
const bytes = Uint8Array.from(atob(s), (m) => m.codePointAt(0));
return Purlfy.#decoder.decode(bytes);
},
slice: (s, startEnd) => {
const [start, end] = startEnd.split(":");
return s.slice(parseInt(start), end ? parseInt(end) : undefined)
},
regex: (s, regex) => {
const r = new RegExp(regex);
const m = s.match(r);
return m ? m[0] : "";
},
dom: (s) => Purlfy.#domParser.parseFromString(s, "text/html"),
sel: (s, selector) => s.querySelector(selector),
attr: (e, attr) => e.getAttribute(attr),
text: (e) => e.textContent,
};
// Instance properties
/**
* Whether to enable the fetch mode.
* @type {boolean}
*/
fetchEnabled = false;
/**
* Whether to enable the lambda mode.
* @type {boolean}
*/
lambdaEnabled = false;
/**
* The maximum number of iterations for purification.
* @type {number}
*/
maxIterations = 5;
/**
* The logger function.
* @type {Function}
*/
#log = console.log.bind(console, "\x1b[38;2;220;20;60m[pURLfy]\x1b[0m");
/**
* The fetch function.
* @type {Function}
*/
#fetch = fetch.bind(globalThis);
/**
* The statistics object.
* @type {Object}
*/
#statistics = { ...Purlfy.#zeroStatistics };
/**
* The rules object.
* @type {Object}
*/
#rules = {};
/**
* Creates a new instance of the Purlfy class.
* @param {Object} [options] The options for the instance.
* @param {boolean} [options.fetchEnabled] Whether to enable the fetch mode.
* @param {boolean} [options.lambdaEnabled] Whether to enable the lambda mode.
* @param {number} [options.maxIterations] The maximum number of iterations for purification.
* @param {Object} [options.statistics] The statistics object.
* @param {Function} [options.log] The logger function.
* @param {Function} [options.fetch] The fetch function.
*/
constructor(options) {
super();
this.fetchEnabled = options?.fetchEnabled ?? this.fetchEnabled;
this.lambdaEnabled = options?.lambdaEnabled ?? this.lambdaEnabled;
this.maxIterations = options?.maxIterations ?? this.maxIterations;
Object.assign(this.#statistics, options?.statistics);
this.#log = options?.log ?? this.#log;
this.#fetch = options?.fetch ?? this.#fetch;
}
// Static methods
/**
* Checks if the given value is of the given type or undefined.
* @param {*} value The value to check.
* @param {string} type The type to check.
* @returns {boolean} Whether the given value is of the given type or undefined.
*/
static #udfOrType(value, type) {
return value === undefined || typeof value === type;
}
/**
* Checks if the given URL object's search string follows the standard format.
* @param {URL} urlObj The URL object to check.
* @returns {boolean} Whether the given URL object's search string follows the standard format.
*/
static #isStandard(urlObj) {
return urlObj.searchParams.toString() === urlObj.search.slice(1);
}
/**
* Checks if the given item is an object.
* @param {*} item The item to check.
* @returns {boolean} Whether the given item is an object.
* @see https://stackoverflow.com/questions/27936772
*/
static #isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
/**
* Merges the given objects deeply.
* @param {Object} target The target object to merge into.
* @param {...Object} sources The source objects to merge.
* @returns {Object} The merged object.
* @see https://stackoverflow.com/questions/27936772
*/
static #mergeDeep(target, ...sources) { // TODO: handle rules conflict (e.g. "path" and "path/")
if (!sources.length) return target;
const source = sources.shift();
if (Purlfy.#isObject(target) && Purlfy.#isObject(source)) {
for (const key in source) {
if (Purlfy.#isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
Purlfy.#mergeDeep(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return Purlfy.#mergeDeep(target, ...sources);
}
/**
* Applies the given acts to the given input.
* @param {string} input The input to apply the acts to.
* @param {string[]} acts The acts to apply.
* @param {Function} logFunc The logger function.
* @returns {string | null} The result of applying the given acts to the given input.
*/
static #applyActs(input, acts, logFunc) {
let dest = input;
for (const cmd of (acts)) {
const name = cmd.split(":")[0];
const arg = cmd.slice(name.length + 1);
const act = Purlfy.#acts[name];
if (!act) {
logFunc("Invalid act:", cmd);
dest = null;
break;
}
try {
dest = act(dest, arg);
} catch (e) {
logFunc(`Error processing input with act "${name}":`, e);
dest = null;
break;
}
}
if (typeof dest === "string" || dest instanceof URL) {
return dest.toString();
} else {
return null;
}
}
// Instance methods
/**
* Clears the statistics.
* @returns {void}
*/
clearStatistics() {
const increment = {};
for (const [key, value] of Object.entries(this.#statistics)) {
increment[key] = -value;
}
this.#incrementStatistics(increment);
}
/**
* Clears the rules.
* @returns {void}
*/
clearRules() {
this.#rules = {};
}
/**
* Gets the statistics.
* @returns {Object} The statistics.
*/
getStatistics() {
return { ...this.#statistics };
}
/**
* Imports the given rules.
* @param {...Object} rulesets The rulesets to import.
* @returns {void}
*/
importRules(...rulesets) {
Purlfy.#mergeDeep(this.#rules, ...rulesets);
}
/**
* Checks if the given rule is valid.
* @param {Object} rule The rule to check.
* @returns {boolean} Whether the given rule is valid.
*/
#validRule(rule) {
if (!rule || !rule.mode || !rule.description || !rule.author) return false;
if ((rule.acts ?? []).includes("dom") && !Purlfy.#domParser) return false; // Feature detection for DOMParser
switch (rule.mode) {
case "white":
return Array.isArray(rule.params);
case "black":
return Array.isArray(rule.params) && Purlfy.#udfOrType(rule.std, "boolean");
case "param":
return Array.isArray(rule.params) && (rule.acts === undefined || Array.isArray(rule.acts)) && Purlfy.#udfOrType(rule.continue, "boolean");
case "regex":
return Array.isArray(rule.regex) && Array.isArray(rule.replace) && Purlfy.#udfOrType(rule.continue, "boolean") && rule.regex.length === rule.replace.length;
case "redirect":
return this.fetchEnabled && Purlfy.#udfOrType(rule.ua, "string") && Purlfy.#udfOrType(rule.headers, "object") && Purlfy.#udfOrType(rule.continue, "boolean");
case "visit":
return this.fetchEnabled && Purlfy.#udfOrType(rule.ua, "string") && Purlfy.#udfOrType(rule.headers, "object") && (rule.acts === undefined || Array.isArray(rule.acts)) && Purlfy.#udfOrType(rule.continue, "boolean");
case "lambda":
return this.lambdaEnabled && (typeof rule.lambda === "string" || rule.lambda instanceof Purlfy.#AsyncFunction) && Purlfy.#udfOrType(rule.continue, "boolean");
default:
return false;
}
}
/**
* Iteratively matches the longest rule for the given URL parts.
* @param {string[]} parts The URL parts to match.
* @returns {Object|null} The matched rule.
*/
#matchRule(parts) {
let fallbackRule = null; // Most precise fallback rule
let currentRules = this.#rules;
for (const part of parts) {
if (currentRules.hasOwnProperty("")) {
fallbackRule = currentRules[""];
}
if (currentRules.hasOwnProperty(part + "/")) {
currentRules = currentRules[part + "/"]; // Exact match - continue to the next level
} else if (currentRules.hasOwnProperty(part)) {
const rule = currentRules[part];
if (this.#validRule(rule)) {
return rule; // Exact match found
}
} else { // No exact match found, try to match with regex
let found = false;
// Iterate through current rules to match RegExp
for (const [key, val] of Object.entries(currentRules)) {
if (!key.startsWith("/")) continue; // Skip non-RegExp keys
try {
const sub = key.endsWith("/"); // Has sub-rules
const regexStr = sub ? key.slice(1, -1) : key.slice(1);
if (regexStr === "") continue; // Skip empty regex
const regex = new RegExp(regexStr);
if (regex.test(part)) { // Regex matches
if (!sub && this.#validRule(val)) {
return val; // Regex match found
} else if (sub) {
currentRules = val; // Continue to the next level
found = true;
break;
}
}
} catch (e) {
this.#log("Invalid regex:", key.slice(1));
}
}
if (!found) break; // No matching rule found
}
}
if (currentRules.hasOwnProperty("")) { // Fallback rule
fallbackRule = currentRules[""];
}
if (this.#validRule(fallbackRule)) {
return fallbackRule;
}
return null;
}
/**
* Increments the statistics.
* @param {Object} increment The incremental statistics.
* @returns {void}
*/
#incrementStatistics(increment) {
for (const [key, value] of Object.entries(increment)) {
this.#statistics[key] += value;
}
if (typeof CustomEvent === "function") {
this.dispatchEvent(new CustomEvent("statisticschange", {
detail: increment
}));
} else {
this.dispatchEvent(new Event("statisticschange"));
}
}
/**
* Applies the given rule to the given URL object.
* @param {URL} urlObj The URL object to apply the rule to.
* @param {Object} rule The rule to apply.
* @param {Function} logFunc The logger function.
* @returns {Promise<[URL, boolean, Object]>} The new URL object, whether to continue and the mode-specific incremental statistics.
*/
async #applyRule(urlObj, rule, logFunc) {
const mode = rule.mode;
const increment = { ...Purlfy.#zeroStatistics }; // Incremental statistics
const lengthBefore = urlObj.href.length;
const paramsCntBefore = urlObj.searchParams.size;
let shallContinue = false;
switch (mode) { // Purifies `urlObj` based on the rule
case "white": { // Whitelist mode
const newParams = new URLSearchParams();
for (const param of rule.params) {
if (urlObj.searchParams.has(param)) {
newParams.set(param, urlObj.searchParams.get(param));
}
}
urlObj.search = newParams.toString();
break;
}
case "black": { // Blacklist mode
if (!rule.std && !Purlfy.#isStandard(urlObj)) {
logFunc("Non-standard URL search string:", urlObj.search);
break;
}
for (const param of rule.params) {
urlObj.searchParams.delete(param);
}
urlObj.search = urlObj.searchParams.toString();
break;
}
case "param": { // Specific param mode
// Process given parameter to be used as a new URL
let paramValue = null;
for (const param of rule.params) { // Find the first available parameter value
if (urlObj.searchParams.has(param)) {
paramValue = urlObj.searchParams.get(param);
break;
}
}
if (!paramValue) {
logFunc("Parameter(s) not found:", rule.params.join(", "));
break;
}
const dest = Purlfy.#applyActs(paramValue, rule.acts ?? ["url"], logFunc);
if (dest && URL.canParse(dest, urlObj.href)) { // Valid URL
urlObj = new URL(dest, urlObj.href);
} else { // Invalid URL
logFunc("Invalid URL:", dest);
break;
}
shallContinue = rule.continue ?? true;
increment.decoded++;
break;
}
case "regex": { // Regex mode
let newUrl = urlObj.href;
for (let i = 0; i < rule.regex.length; i++) {
const regex = new RegExp(rule.regex[i], "g");
const replace = rule.replace[i];
newUrl = newUrl.replaceAll(regex, replace);
}
newUrl = Purlfy.#applyActs(newUrl, rule.acts ?? [], logFunc);
if (newUrl && URL.canParse(newUrl, urlObj.href)) { // Valid URL
urlObj = new URL(newUrl, urlObj.href);
} else { // Invalid URL
logFunc("Invalid URL:", newUrl);
break;
}
shallContinue = rule.continue ?? true;
break;
}
case "redirect": { // Redirect mode
if (!this.fetchEnabled) {
logFunc("Redirect mode is disabled.");
break;
}
const options = {
method: "HEAD",
redirect: "manual",
headers: rule.headers ?? {}
};
if (rule.ua) {
options.headers["User-Agent"] = rule.ua;
}
let dest = null;
try {
const r = await this.#fetch(urlObj.href, options);
if (r.status >= 300 && r.status < 400 && r.headers.has("location")) {
dest = r.headers.get("location");
} else if (r.url !== urlObj.href) {
dest = r.url; // In case `redirect: manual` doesn't work
}
} catch (e) {
logFunc("Error following redirect:", e);
break;
}
if (dest && URL.canParse(dest, urlObj.href)) {
const prevUrl = urlObj.href;
urlObj = new URL(dest, urlObj.href);
if (urlObj.href === prevUrl) { // No redirection
logFunc("No redirection made.");
break;
}
shallContinue = rule.continue ?? true;
increment.redirected++;
} else {
logFunc("Invalid redirect destination:", dest);
}
break;
}
case "visit": { // Visit mode
if (!this.fetchEnabled) {
logFunc("Visit mode is disabled.");
break;
}
const options = {
method: "GET",
redirect: "manual",
headers: rule.headers ?? {}
};
if (rule.ua) {
options.headers["User-Agent"] = rule.ua;
}
let r, html = null;
try {
r = await this.#fetch(urlObj.href, options);
html = await r.text();
} catch (e) {
logFunc("Error visiting URL:", e);
break;
}
if (r.status >= 300 && r.status < 400 && r.headers.has("location")) {
logFunc("Visit mode, but got redirected to:", r.url);
urlObj = new URL(r.headers.get("location"), urlObj.href);
} else if (r.url !== urlObj.href) { // In case `redirect: manual` doesn't work
logFunc("Visit mode, but got redirected to:", r.url);
urlObj = new URL(r.url, urlObj.href);
} else {
const dest = Purlfy.#applyActs(html, rule.acts?.length ? rule.acts : [String.raw`regex:https?:\/\/.(?:www\.)?[-a-zA-Z0-9@%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?!&\/\/=]*)`], logFunc);
if (dest && URL.canParse(dest, urlObj.href)) { // Valid URL
urlObj = new URL(dest, urlObj.href);
} else { // Invalid URL
logFunc("Invalid URL:", dest);
break;
}
}
shallContinue = rule.continue ?? true;
increment.visited++;
break;
}
case "lambda": {
if (!this.lambdaEnabled) {
logFunc("Lambda mode is disabled.");
break;
}
try {
const lambda = typeof rule.lambda === "string" ? new Purlfy.#AsyncFunction("url", rule.lambda) : rule.lambda;
rule.lambda = lambda; // "Cache" the compiled lambda function
urlObj = await lambda(urlObj);
shallContinue = rule.continue ?? true;
} catch (e) {
logFunc("Error executing lambda:", e);
}
break;
}
default: {
logFunc("Invalid mode:", mode);
break;
}
}
const paramsCntAfter = urlObj.searchParams.size;
increment.param += (["white", "black"].includes(mode)) ? (paramsCntBefore - paramsCntAfter) : 0;
increment.char += Math.max(lengthBefore - urlObj.href.length, 0); // Prevent negative char count
return [urlObj, shallContinue, increment];
}
/**
* Purifies the given URL based on the rules.
* @param {string} originalUrl The original URL to purify.
* @returns {Promise<Object>} The purified URL and the rule applied.
*/
async purify(originalUrl) {
let increment = { ...Purlfy.#zeroStatistics }; // Incremental statistics of a single purification
let shallContinue = true;
let firstRule = null;
let iteration = 0;
let urlObj;
this.#log("Purifying URL:", originalUrl);
const optionalLocation = typeof location !== 'undefined' ? location.href : undefined;
if (originalUrl && URL.canParse(originalUrl, optionalLocation)) {
urlObj = new URL(originalUrl, optionalLocation);
} else {
this.#log(`Cannot parse URL ${originalUrl}`);
return {
url: originalUrl,
rule: "N/A"
}
}
while (shallContinue && iteration++ < this.maxIterations) {
const logi = (...args) => this.#log(`[#${iteration}]`, ...args);
const protocol = urlObj.protocol;
if (protocol !== "http:" && protocol !== "https:") { // Not a valid HTTP URL
logi(`Not a HTTP URL: ${urlObj.href}`);
break;
}
const hostAndPath = urlObj.host + urlObj.pathname;
const parts = hostAndPath.split("/").filter(part => part !== "");
const rule = this.#matchRule(parts);
if (!rule) { // No matching rule found
logi(`No matching rule found for ${urlObj.href}.`);
break;
}
firstRule ??= rule;
logi(`Matching rule: ${rule.description} by ${rule.author}`);
let singleIncrement; // Incremental statistics for the current iteration
[urlObj, shallContinue, singleIncrement] = await this.#applyRule(urlObj, rule, logi);
for (const [key, value] of Object.entries(singleIncrement)) {
increment[key] += value;
}
logi("Purified URL:", urlObj.href);
}
if (firstRule && originalUrl !== urlObj.href) { // Increment statistics only if a rule was applied and URL has been changed
increment.url++;
this.#incrementStatistics(increment);
}
return {
url: urlObj.href,
rule: firstRule ? `${firstRule.description} by ${firstRule.author}` : "N/A"
};
}
}
if (typeof module !== "undefined" && module.exports) {
module.exports = Purlfy; // Export for Node.js
} else {
this.Purlfy = Purlfy; // Export for browser
}