forked from martok/palefill
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
759 lines (697 loc) · 28.9 KB
/
main.js
File metadata and controls
759 lines (697 loc) · 28.9 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
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
/*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Pale Moon Web Technologies Polyfill Add-on
Copyright (c) 2020-22 Martok & Contributors. All rights reserved.
Portions based on GitHub Web Components Polyfill Add-on
Copyright (c) 2020 JustOff. All rights reserved.
Copyright (c) 2022 SeaHOH. All rights reserved.
https://github.com/JustOff/github-wc-polyfill
*/
"use strict";
const { alert, cspJoinHeader, cspSplitHeader, encodeHTMLAttribute, print, setCompare, sha256 } = require("util");
const settings = require("settings").getService();
const pf = require("polyfills");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
const nsIContentPolicy = Ci.nsIContentPolicy;
const ENABLED_CONTENT_TYPES = new Set([nsIContentPolicy.TYPE_DOCUMENT, nsIContentPolicy.TYPE_SUBDOCUMENT, nsIContentPolicy.TYPE_SCRIPT]);
function evaluateFix(fix, script, csp, contentReplace) {
switch(fix) {
/* marker */
case "$script-content": // apply also to script content
case "sm-cookie": // re-set request cookie in SeaMonkey
break;
/* standard technologies */
case "std-customElements":
script.push(pf.Window_customElements);
break;
case "std-IntlRelativeTimeFormat":
script.push(pf.Intl_RelativeTimeFormat_dummy);
break;
case "std-PerformanceObserver":
csp["script-src"].push("unpkg.com");
script.push({"src": "https://unpkg.com/@fastly/performance-observer-polyfill@2.0.0/polyfill/index.js",
"integrity": "sha384-a04eMdOeDNNfk4MJMfTFLaFz3BlylyFwanlcrzEJh6ddqcaapp/3phIOiNVrF/QC"});
break;
case "std-ShadowDOM":
csp["script-src"].push("unpkg.com");
script.push({"src": "https://unpkg.com/@webcomponents/shadydom@1.9.0/shadydom.min.js",
"integrity": "sha384-PFKLoiJYZCqKOdOUvo0Z18Ofro9s8QJkXaagRBHR4z8WMAyGeyp0ZWmziwHoeI7K"});
break;
case "std-queueMicrotask":
script.push(pf.Window_queueMicrotask);
break;
/* site-specific fixes */
case "dhl-optchain":
contentReplace.push([`document?.getElementsByTagName?.('html')?.[0]?.getAttribute?.('lang')`, `document.getElementsByTagName('html')[0].getAttribute('lang')`]);
break;
case "gh-compat":
script.push(pf.Element_attachShadow);
script.push(pf.Github_enableDiffButton);
script.push({"src": "https://github.githubassets.com/assets/compat-838cedbb.js",
"integrity": "sha512-g4ztuyuFPzjTvIqYBeZdHEDaHz2K6RCz4RszsnL3m5ko4kiWCjB9W6uIScLkNr8l/BtC2dYiIFkOdOLDYBHLqQ=="});
break;
case "gh-integrity":
// strip any and all integrity from directly loaded files
// FIXME: this is waaaay to general. should only do this for scripts we know will get modified?
contentReplace.push([/integrity="sha512-[^"]+" (?=src="https:\/\/github.githubassets.com\/assets\/.+?\.js"><\/script>)/g, ""]);
break;
case "gh-temp-oldindex2":
contentReplace.push([/<script.+chunk-index2-[a-z0-9]+\.js"><\/script>/, ""]);
script.push({"defer": "defer",
"integrity": "sha512-o/3J98IT190CWjNtrpkWpVUdnrkKSwQ1jDFOagsCc8ZvvyaqewKygiqxbxF/Z/BzHnrUvLkTe43sQ/D4PAyGRA==",
"data-module-id": "./chunk-index2.js",
"data-src": "https://github.githubassets.com/assets/chunk-index2-a3fdc9f7.js"});
break;
case "gh-script-optchain":
// works only for this specific minimizer output...
contentReplace.push([/([a-zA-Z]+)\?\?/g, "((typeof($1)!==undefined)&&($1!==null))?($1):"]);
contentReplace.push([`this.matchFields?.join("-")`, `((y)=>y?y.join("-"):y)(this.matchFields)`]);
contentReplace.push([`H.integrity=S.sriHashes[t],`, ``]);
break;
case "gh-worker-csp":
csp["worker-src"].push("github.githubassets.com");
break;
case "gl-script":
contentReplace.push([String.raw`/^&(?<iid>\d+)$/`, String.raw`/^&(\d+)$/`]);
contentReplace.push([`.groups.iid`, `[1]`]);
// https://gitlab.com/gitlab-org/gitlab/-/merge_requests/79161
contentReplace.push([String.raw`/^(?<indent>\s*)(?<leader>((?<isUl>[*+-])|(?<isOl>\d+\.))( \[([xX\s])\])?\s)(?<content>.)?/`, String.raw`/^(\s*)((([*+-])|(\d+\.))( \[([xX\s])\])?\s)(.)?/`]);
// indent: 1, leader: 2, isUl: 4, isOl: 5, content: 8
// const{indent:r,leader:o}=t.groups,
contentReplace.push([/\{indent:(.),leader:(.)\}=(.)\.groups/, "[$1,$2]=[$3[1],$3[2]]"]);
// const{leader:n,indent:i,content:s,isOl:a}=o.groups
contentReplace.push([/\{leader:(.),indent:(.),content:(.),isOl:(.)\}=(.)\.groups/, "[$1,$2,$3,$4]=[$5[2],$5[1],$5[8],$5[5]]"]);
// {indent:i,isOl:s}=null!==(n=null==e?void 0:e.groups)&&void 0!==n?n:{}
contentReplace.push([/\{indent:(.),isOl:(.)\}=null!==\((.)=null==(.)\?void 0:.\.groups\)&&void 0!==.\?.:{}/, "[$1,$2]=(null!==$4?[$4[1],$4[5]]:[])"]);
break;
case "godbolt-script":
contentReplace.push([`_languageId;_loadingTriggered;_lazyLoadPromise;_lazyLoadPromiseResolve;_lazyLoadPromiseReject;constructor(e){`,
`constructor(e){this._languageId=this._loadingTriggered=this._lazyLoadPromise=this._lazyLoadPromiseResolve=this._lazyLoadPromiseReject=null;`]);
contentReplace.push([`_onDidChange=new l.Emitter;_onDidExtraLibsChange=new l.Emitter;_extraLibs;_removedExtraLibs;_eagerModelSync;_compilerOptions;_diagnosticsOptions;_workerOptions;_onDidExtraLibsChangeTimeout;_inlayHintsOptions;constructor(e,t,i,n){`,
`constructor(e,t,i,n){this._onDidChange=new l.Emitter;this._onDidExtraLibsChange=new l.Emitter;this._compilerOptions=this._diagnosticsOptions=this._workerOptions=this._inlayHintsOptions=null;`]);
contentReplace.push([`_modeId;_defaults;_configChangeListener;_updateExtraLibsToken;_extraLibsChangeListener;_worker;_client;constructor(e,t){`,
`constructor(e,t){`]);
// now they're just trolling us - most of these aren't even efficient encodings
contentReplace.push([`}_libFiles;_hasFetchedLibFiles;_fetchLibFilesPromise;`,
`}`]);
contentReplace.push([`}_disposables=[];_listener=Object.create(null);dispose()`,
`}dispose()`]);
contentReplace.push([`v=class extends p{constructor(e,t,i,n){`,
`v=class extends p{constructor(e,t,i,n){this._disposables=[];this._listener=Object.create(null);`]);
contentReplace.push([`i.kindModifiers?.indexOf("deprecated")`,
`(i.kindModifiers==null?null:i.kindModifiers.indexOf("deprecated"))`]);
contentReplace.push([`{signatureHelpTriggerCharacters=["(",","];`,
`{`]);
break;
case "reddit-comments-regexp":
contentReplace.push([String.raw`/(?:reddit\.com\/r\/)(?<subreddit>[\w]+)(?:\/comments\/)?(?<postId>[\w]+)?/`, String.raw`/(?:reddit\.com\/r\/)([\w]+)(?:\/comments\/)?([\w]+)?/`]);
contentReplace.push([String.raw`var s;const{subreddit:o,postId:r}=(null===(s=t.match(i))||void 0===s?void 0:s.groups)||{};`, String.raw`const s=t.match(i),o=!s||null==s[1]?void 0:s[1],r=!s||null==s[2]?void 0:s[2];`]);
break;
case "tmx-optchain":
contentReplace.push([`args.order2?.value`,
`(args.order2===null?null:args.order2.value)`]);
/* browser-specific fixes */
case "sm-gh-extra":
if (service.isSeaMonkey) {
script.push(pf.Element_toggleAttribute);
script.push(pf.Array_flat);
script.push(pf.Array_flatMap);
script.push(pf.String_matchAll);
}
break;
default:
return false;
}
return true;
}
class RuleSelector {
constructor (domain) {
this.domain = domain;
this.path = undefined;
this.policyTypes = new Set();
}
/*
Filter Syntax is basic https://adblockplus.org/filter-cheatsheet
Limititations: Domain part MUST be present
only type options apply
path component may contain exactly 1 wildcard "*"
Example:
example.com
example.com/path/a.html
example.com/path/to.js$script
example.com$subdocument
*/
static parse(selstr) {
const [, url, suffix] = RuleSelector.RE_SUFFIX.exec(selstr);
if (!url) {
throw new SyntaxError("URL part missing");
}
const opts = suffix?suffix.split(","):[];
const ps = url.indexOf("/");
const domain = (ps < 0) ? url : url.substring(0, ps);
const path = (ps < 0) ? "" : url.substr(ps);
if (!domain) {
throw new SyntaxError("Domain part missing");
}
const selector = new RuleSelector(domain);
if (path) {
if (path.indexOf("*") < 0) {
selector.path = path;
} else {
selector.path = path.split("*");
}
}
for (const o of opts) {
switch (o) {
case "document":
selector.policyTypes.add(nsIContentPolicy.TYPE_DOCUMENT);
break;
case "subdocument":
selector.policyTypes.add(nsIContentPolicy.TYPE_SUBDOCUMENT);
break;
case "script":
selector.policyTypes.add(nsIContentPolicy.TYPE_SCRIPT);
break;
default:
throw new SyntaxError("Unknown option: " + o);
}
}
if (!selector.policyTypes.size) {
selector.policyTypes.add(nsIContentPolicy.TYPE_DOCUMENT);
selector.policyTypes.add(nsIContentPolicy.TYPE_SUBDOCUMENT);
}
return selector;
}
compareExceptDomain(other) {
return (this.path === other.path) && setCompare(this.policyTypes, other.policyTypes);
}
matchPath(path) {
const selp = this.path;
switch (typeof selp) {
case "string":
if (selp !== path)
return false;
break;
case "object":
if (!path.endsWith(selp[1]))
return false;
if (!path.startsWith(selp[0]))
return false;
break;
}
return true;
}
}
RuleSelector.RE_SUFFIX = /^(.*?)(?:\$((?:(?:document|script|subdocument)(?:,(?!$)|$))+))?$/;
/*
Rule Engine Compiled Decision Tree
Requirements:
- early-out based on domain name
- handle wildcards in final name of domains (not anywhere "up" the tree)
- share RuleSelector if same fixset (memory optimization)
Tree:
'com':
'github':
'': [sel1]
'gist': [sel1, sel2]
*/
class RuleEngine {
constructor () {
this.selectors = new Map();
this.tree = {};
}
clear() {
this.selectors.clear();
this.tree = {};
}
_maybeRaiseSyntaxError(except, raiseErrors, context) {
if (raiseErrors) {
throw new SyntaxError("Error on parsing " + context + "\n" + except.message);
}
print("Error on parsing " + context + "\n" + except.message);
}
_domainSplit(domainPattern) {
// return [...domainPattern].reverse().join("").split(".");
const r = domainPattern.split(".");
r.reverse();
return r;
}
_treeAdd(domainPattern, selector) {
const dcomp = this._domainSplit(domainPattern);
let node = this.tree;
let leaf = null;
for (let i=0; i < dcomp.length; i++) {
const c = dcomp[i];
if ("*" === c) {
leaf = node[c] = (node[c] || new Set());
break;
}
node = node[c] = (node[c] || {});
}
if (null == leaf) {
// ended here without a wildcard -> leaf is the explicit empty entry
leaf = node[""] = (node[""] || new Set());
}
leaf.add(selector);
}
_treeFind(domain, testonly) {
const dcomp = this._domainSplit(domain);
const selectors = new Set();
let node = this.tree;
let sset;
for (let i=0; i < dcomp.length; i++) {
const c = dcomp[i];
if ((sset = node["*"] || false) !== false) {
if (testonly) return true;
for (const s of sset) selectors.add(s);
}
node = node[c];
if (!node) {
// no more subdomains can match, resultset is at most any wildcards encountered up to here
break;
}
}
if (node) {
// last domain part matched something
if ((sset = node[""] || false) !== false) {
if (testonly) return true;
for (const s of sset) selectors.add(s);
}
}
if (testonly) return false;
return selectors;
}
_addRule(selector, fixset) {
let usedSel = selector;
// if the same selector and fixset already exists for another domain, reuse that to save memory
for (const [sel, fix] of this.selectors.entries()) {
if (setCompare(fixset, fix) && selector.compareExceptDomain(sel)) {
usedSel = sel;
break;
}
}
if (usedSel === selector) {
// no alias found, add new
this.selectors.set(usedSel, fixset);
}
this._treeAdd(selector.domain, usedSel);
}
addRulesFromDict(defs, raiseErrors=false) {
let processed = 0;
let accepted = 0;
for (const defn of defs) {
const fixset = new Set(defn.fix);
for (const selstr of defn.selector) {
processed++;
try {
const selector = RuleSelector.parse(selstr);
if (selector) {
this._addRule(selector, fixset);
accepted++;
}
} catch (e) {
if (e instanceof SyntaxError) {
this._maybeRaiseSyntaxError(e, raiseErrors, selstr);
} else {
throw e;
}
}
}
}
return [accepted, processed];
}
addRulesFromString(script, raiseErrors=false) {
let processed = 0;
let accepted = 0;
const lines = script.split(/\r\n|\r|\n/);
let selectors = [];
for (const line of lines) {
if (!line) continue;
if (line.startsWith("!")) continue;
processed++;
try {
if (line.startsWith(" ") || line.startsWith("\t")) {
if (!selectors.length) {
throw new SyntaxError("Fixes without preceding selector");
}
const fixset = new Set();
for (const f of line.trim().split(",").filter(s => !!s.length)) {
fixset.add(f);
}
if (fixset.size) {
for (const selector of selectors) {
this._addRule(selector, fixset);
}
}
selectors = [];
} else {
const selector = RuleSelector.parse(line);
if (selector) {
selectors.push(selector);
}
}
accepted ++;
} catch (e) {
if (e instanceof SyntaxError) {
this._maybeRaiseSyntaxError(e, raiseErrors, line);
} else {
throw e;
}
}
}
if (selectors.length) {
this._maybeRaiseSyntaxError(new SyntaxError("Final group missing fixes"), raiseErrors, "");
}
return [accepted, processed];
}
isSiteEnabled(hostname) {
return this._treeFind(hostname, true);
}
getApplicable(URI, contentPolicy) {
const selectors = this._treeFind(URI.host, false);
const applied = new Set();
for (const selector of selectors) {
if (!selector.policyTypes.has(contentPolicy)) continue;
if (!selector.matchPath(URI.path)) continue;
const fixes = this.selectors.get(selector);
for (const f of fixes) {
applied.add(f);
}
}
if (!applied.size) {
return null;
}
return applied;
}
}
class MergedFix {
constructor (fixes) {
this.fixes = fixes;
this.compiled = false;
}
ensureCompiled() {
if (this.compiled)
return;
const scripts = [];
const csp = {'script-src': [], 'worker-src': []};
const contentReplace = [];
// for each selected fix, append it and it's consequences to a list
for (const item of this.fixes) {
if (!evaluateFix(item, scripts, csp, contentReplace)) {
print("Error in fix evaluation: ", item);
};
}
// collect all consequences into easy to apply fields
this.scripts = "";
this.csp = {};
this.contentReplace = contentReplace;
// coalesce inline scripts, create elements for external resources
let inline = "";
for (const script of scripts) {
if (typeof script === "string") {
inline += "(function(){" + script + "}).call(this);\n";
} else {
const attribs = {"crossorigin": "anonymous", "type": "text/javascript"};
const scr = ['<script'];
for (const [k, v] of Object.entries(Object.assign(attribs, script))) {
scr.push(k + '=\"' + encodeHTMLAttribute(v) + '\"');
}
scr.push('></script>');
this.scripts += scr.join(' ');
}
}
// hash the inline script and add script-src csp
if (inline) {
this.scripts += `<script type="text/javascript" >${inline}</script>`;
csp['script-src'].push("'sha256-" + sha256(inline) + "'");
}
// convert CSP array to header text
for (const [p, s] of Object.entries(csp)) {
if (s.length) {
const uniq_sources = [... new Set(s)];
this.csp[p] = uniq_sources.join(' ');
}
}
this.compiled = true;
}
isModifyScriptContent() {
return this.fixes.includes("$script-content");
}
}
class PolyfillService {
constructor() {
this.isSeaMonkey = Services.appinfo.name == "SeaMonkey";
this.fixCache = new Map();
this.rules = new RuleEngine();
this.rules.addRulesFromString(require("builtin-rules"));
this.exclusion = new RuleEngine();
this.exclusion.addRulesFromString(settings.getJSONPref("exclusion") || "");
settings.onPrefChanged.on(this._prefChanged, this);
}
destroy() {
settings.onPrefChanged.remove(this._prefChanged, this);
}
_prefChanged(pref) {
print("pref changed: ", pref);
switch (pref) {
case "exclusion":
this.exclusion.clear();
this.exclusion.addRulesFromString(settings.getJSONPref("exclusion") || "");
break;
}
}
isSiteEnabled(URI) {
return this.rules.isSiteEnabled(URI.host);
}
getFixes(URI, contentPolicy) {
const fset = this.rules.getApplicable(URI, contentPolicy);
if (fset === null) {
return null;
}
const excluded = this.exclusion.getApplicable(URI, contentPolicy);
if (excluded !== null) {
if (excluded.has("*")) {
fset.clear()
} else {
for (const x of excluded) {
fset.delete(x);
}
}
}
if (!fset.size) {
return null;
}
const aapplied = Array.sort([...fset]);
const key = aapplied.join('+');
let fixes = this.fixCache.get(key);
if (typeof fixes === "undefined") {
fixes = new MergedFix(aapplied);
this.fixCache.set(key, fixes);
}
return fixes;
}
modifyContentSecurityPolicy(csp, activeFixes) {
activeFixes.ensureCompiled();
// no change required
if (!Object.getOwnPropertyNames(activeFixes.csp).length) {
return csp;
}
// parse map
const policies = cspSplitHeader(csp);
// append new rules
for (const [dir, val] of Object.entries(activeFixes.csp)) {
if (policies.hasOwnProperty(dir)) {
policies[dir].push(val);
} else {
// special case: don't introduce a script-src policy if the only use is our inline script
// (this check works because the hash signed script is always the last in the list, after all required domains)
if ("script-src" === dir && val.startsWith("'sha256-")) {
continue;
}
policies[dir] = val;
}
}
// reassemble the new policies
csp = cspJoinHeader(policies);
return csp;
}
modifyRequestData(data, activeFixes) {
activeFixes.ensureCompiled();
if (activeFixes.contentReplace) {
for (const [f, t] of activeFixes.contentReplace) {
data = data.replace(f, t);
}
}
if (activeFixes.scripts) {
const p1 = data.indexOf("<head");
if (p1>=0) {
const p2 = data.indexOf(">", p1+5);
if (p2 >= 0) {
data = data.slice(0, p2 + 1) + activeFixes.scripts + data.slice(p2 + 1);
}
}
}
return data;
}
}
class TracingListener {
constructor(fixes) {
this.receivedData = [];
this.originalListener = null;
this.activeFixes = fixes;
}
onDataAvailable(request, context, inputStream, offset, count) {
const binaryInputStream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci["nsIBinaryInputStream"]);
binaryInputStream.setInputStream(inputStream);
const data = binaryInputStream.readBytes(count);
this.receivedData.push(data);
}
onStartRequest(request, context) {
try {
this.originalListener.onStartRequest(request, context);
} catch (err) {
request.cancel(err.result);
}
}
onStopRequest(request, context, statusCode) {
let data = this.receivedData.join("");
try {
data = service.modifyRequestData(data, this.activeFixes);
} catch (e) {}
const storageStream = Cc["@mozilla.org/storagestream;1"].createInstance(Ci["nsIStorageStream"]);
storageStream.init(8192, data.length, null);
const os = storageStream.getOutputStream(0);
if (data.length > 0) {
os.write(data, data.length);
}
os.close();
try {
this.originalListener.onDataAvailable(request, context, storageStream.newInputStream(0), 0, data.length);
} catch (e) {}
try {
this.originalListener.onStopRequest(request, context, statusCode);
} catch (e) {}
}
}
TracingListener.QueryInterface = XPCOMUtils.generateQI([Ci.nsIStreamListener, Ci.nsISupports]);
class HTTPObserver {
constructor() {
this.cookie = null;
}
safeGetResponseHeader(channel, header, def = "") {
try {
return channel.getResponseHeader(header);
} catch(e) {
/*eat NS_ERROR_NOT_AVAILABLE exception if header is not set */
return def;
}
}
isHTMLDocument(subject) {
return (subject.loadInfo.externalContentPolicyType == nsIContentPolicy.TYPE_DOCUMENT ||
subject.loadInfo.externalContentPolicyType == nsIContentPolicy.TYPE_SUBDOCUMENT) &&
(this.safeGetResponseHeader(subject, "Content-Type", "text/html").indexOf("text/html") != -1);
}
isScript(subject) {
return (subject.loadInfo.externalContentPolicyType == nsIContentPolicy.TYPE_SCRIPT);
}
observe(subject, topic, data) {
// early-out tests
if (!(subject instanceof Ci.nsIHttpChannel)) return;
if (!ENABLED_CONTENT_TYPES.has(subject.loadInfo.externalContentPolicyType)) return;
if (!service.isSiteEnabled(subject.URI)) return;
// full test
const fixes = service.getFixes(subject.URI, subject.loadInfo.externalContentPolicyType);
if (fixes === null) {
return;
}
switch (topic) {
case "http-on-examine-response":
case "http-on-examine-cached-response":
if ([200, 304].includes(subject.responseStatus)) {
try {
print("applied fixes to ", subject.URI.spec, ": ", fixes.fixes);
let csp = this.safeGetResponseHeader(subject, "Content-Security-Policy");
if (!!csp) {
csp = service.modifyContentSecurityPolicy(csp, fixes);
subject.setResponseHeader("Content-Security-Policy", csp, false);
}
const mod_content = this.isHTMLDocument(subject) || (this.isScript(subject) && fixes.isModifyScriptContent());
// FIXME: ideally, we would only do that on new data (200) and let the cache store our modified content.
// but apparently the cache is *before* the nsITraceableChannel?
if (mod_content) {
const tracerSubject = subject.QueryInterface(Ci.nsITraceableChannel);
const newListener = new TracingListener(fixes);
newListener.originalListener = tracerSubject.setNewListener(newListener);
}
} catch (e) {console.error(e)}
}
break;
case "http-on-modify-request":
if (service.isSeaMonkey && fixes.a.includes("sm-cookie")) {
try {
this.cookie = subject.getRequestHeader("Cookie");
} catch (e) {
if (this.cookie) {
subject.setRequestHeader("Cookie", this.cookie, false);
}
}
}
break;
}
}
}
HTTPObserver.QueryInterface = XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]);
function _optionsDisplayed(xul) {
const btnApply = xul.getElementById("palefill-exclusion-apply");
const txtFilters = xul.getElementById("palefill-exclusion-list");
txtFilters.value = settings.getJSONPref("exclusion") || "";
btnApply.addEventListener("click", () => {
const newText = txtFilters.value.trim();
const tmpRules = new RuleEngine();
try {
const [a, p] = tmpRules.addRulesFromString(newText, true);
if (a == p) {
settings.setJSONPref("exclusion", newText);
alert("Palefill", `Success! Saved.`);
} else {
alert("Palefill", `Successfully parsed ${a}/${p} lines. Check debug output for details.`);
}
} catch (e) {
if (e instanceof SyntaxError) {
alert("Palefill", e.message);
} else {
throw e;
}
}
});
}
var service = null;
var httpObserver = null;
function init() {
service = new PolyfillService();
httpObserver = new HTTPObserver();
Services.obs.addObserver(httpObserver, "http-on-examine-response", false);
Services.obs.addObserver(httpObserver, "http-on-examine-cached-response", false);
if (service.isSeaMonkey) {
Services.obs.addObserver(httpObserver, "http-on-modify-request", false);
}
settings.onOptionsDisplayed.on(_optionsDisplayed);
}
function done() {
settings.onOptionsDisplayed.remove(_optionsDisplayed);
if (service.isSeaMonkey) {
Services.obs.removeObserver(httpObserver, "http-on-modify-request", false);
}
Services.obs.removeObserver(httpObserver, "http-on-examine-cached-response", false);
Services.obs.removeObserver(httpObserver, "http-on-examine-response", false);
httpObserver = null;
service.destroy();
service = null;
}
exports = {
init,
done
}