forked from webrecorder/wombat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwombat.js
executable file
·6807 lines (6011 loc) · 198 KB
/
wombat.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
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable camelcase */
import FuncMap from './funcMap.js';
import { createStorage, Storage } from './customStorage.js';
import WombatLocation from './wombatLocation.js';
import AutoFetcher from './autoFetcher.js';
import { wrapEventListener, wrapSameOriginEventListener } from './listeners.js';
import {
addToStringTagToClass,
autobind,
ThrowExceptions
} from './wombatUtils.js';
import { postToGetUrl } from 'warcio/utils';
/**
* @param {Window} $wbwindow
* @param {Object} wbinfo
*/
function Wombat($wbwindow, wbinfo) {
if (!(this instanceof Wombat)) return new Wombat($wbwindow, wbinfo);
/** @type {boolean} */
this.debug_rw = false;
/** @type {Window} */
this.$wbwindow = $wbwindow;
this.WBWindow = Window;
this.origHost = $wbwindow.location.host;
this.origHostname = $wbwindow.location.hostname;
this.origProtocol = $wbwindow.location.protocol;
/** @type {string} */
this.HTTP_PREFIX = 'http://';
/** @type {string} */
this.HTTPS_PREFIX = 'https://';
/** @type {string} */
this.REL_PREFIX = '//';
/** @type {Array<string>} */
this.VALID_PREFIXES = [this.HTTP_PREFIX, this.HTTPS_PREFIX, this.REL_PREFIX];
/** @type {Array<string>} */
this.IGNORE_PREFIXES = [
'#',
'about:',
'data:',
'blob:',
'mailto:',
'javascript:',
'{',
'*'
];
if ('ignore_prefixes' in wbinfo) {
this.IGNORE_PREFIXES = this.IGNORE_PREFIXES.concat(wbinfo.ignore_prefixes);
}
this.WB_CHECK_THIS_FUNC = '_____WB$wombat$check$this$function_____';
this.WB_ASSIGN_FUNC = '_____WB$wombat$assign$function_____';
/** @type {function(qualifiedName: string, value: string): void} */
this.wb_setAttribute = $wbwindow.Element.prototype.setAttribute;
/** @type {function(qualifiedName: string): ?string} */
this.wb_getAttribute = $wbwindow.Element.prototype.getAttribute;
/** @type {function(): string} */
this.wb_funToString = Function.prototype.toString;
/** @type {AutoFetcher} */
this.WBAutoFetchWorker = null;
/** @type {boolean} */
this.wbUseAFWorker =
wbinfo.enable_auto_fetch && $wbwindow.Worker != null && wbinfo.is_live;
/** @type {string} */
this.wb_rel_prefix = '';
/** @type {boolean} */
this.wb_wombat_updating = false;
/** @type {FuncMap} */
this.message_listeners = new FuncMap();
/** @type {FuncMap} */
this.storage_listeners = new FuncMap();
/**
* rewrite modifiers for <link href="URL" rel="import|preload" as="x">
* expressed as as-value -> modifier
* @type {Object}
*/
this.linkAsTypes = {
script: 'js_',
worker: 'js_',
style: 'cs_',
image: 'im_',
document: 'if_',
fetch: 'mp_',
font: 'oe_',
audio: 'oe_',
video: 'oe_',
embed: 'oe_',
object: 'oe_',
track: 'oe_',
// the following cover the default case
'': 'mp_',
null: 'mp_',
undefined: 'mp_'
};
/**
* rewrite modifiers for <link href="URL" rel="x"> and or
* <link href="URL" rel="x" as="y"> expressed as a mapping of
* rel -> modifier or rel -> as -> modifier
* @type {Object}
*/
this.linkTagMods = {
linkRelToAs: {
import: this.linkAsTypes,
preload: this.linkAsTypes
},
stylesheet: 'cs_',
// the following cover the default case
null: 'mp_',
undefined: 'mp_',
'': 'mp_'
};
/**
* pre-computed modifiers for each tag
* @type {Object}
*/
this.tagToMod = {
A: { href: 'mp_' },
AREA: { href: 'mp_' },
AUDIO: { src: 'oe_', poster: 'im_' },
BASE: { href: 'mp_' },
EMBED: { src: 'oe_' },
FORM: { action: 'mp_' },
FRAME: { src: 'fr_' },
IFRAME: { src: 'if_' },
IMAGE: { href: 'im_', 'xlink:href': 'im_' },
IMG: { src: 'im_', srcset: 'im_' },
INPUT: { src: 'oe_' },
INS: { cite: 'mp_' },
META: { content: 'mp_' },
OBJECT: { data: 'oe_', codebase: 'oe_' },
Q: { cite: 'mp_' },
// covers both HTML and SVG script element,
SCRIPT: { src: 'js_', 'xlink:href': 'js_' },
SOURCE: { src: 'oe_', srcset: 'oe_' },
TRACK: { src: 'oe_' },
VIDEO: { src: 'oe_', poster: 'im_' },
image: { href: 'im_', 'xlink:href': 'im_' }
};
/** @type {Array<string>} */
this.URL_PROPS = [
'href',
'hash',
'pathname',
'host',
'hostname',
'protocol',
'origin',
'search',
'port'
];
/** @type {Object} */
this.wb_info = wbinfo;
/**
* custom options
* @type {Object}
*/
this.wb_opts = wbinfo.wombat_opts;
/** @type {string} */
this.wb_replay_prefix = wbinfo.prefix;
/** @type {boolean} */
this.wb_is_proxy = this.wb_info.proxy_magic || !this.wb_replay_prefix;
/** @type {string} */
this.wb_info.top_host = this.wb_info.top_host || '*';
/** @type {string} */
this.wb_curr_host =
$wbwindow.location.protocol + '//' + $wbwindow.location.host;
/** @type {Object} */
this.wb_info.wombat_opts = this.wb_info.wombat_opts || {};
/** @type {string} */
this.wb_orig_scheme = this.wb_info.wombat_scheme + '://';
/** @type {string} */
this.wb_orig_origin = this.wb_orig_scheme + this.wb_info.wombat_host;
/** @type {string} */
this.wb_abs_prefix = this.wb_replay_prefix;
/** @type {string} */
this.wb_capture_date_part = '';
if (!this.wb_info.is_live && this.wb_info.wombat_ts) {
this.wb_capture_date_part = '/' + this.wb_info.wombat_ts + '/';
}
/** @type {Array<string>} */
this.BAD_PREFIXES = [
'http:' + this.wb_replay_prefix,
'https:' + this.wb_replay_prefix,
'http:/' + this.wb_replay_prefix,
'https:/' + this.wb_replay_prefix
];
/** @type {RegExp} */
this.hostnamePortRe = /^[\w-]+(\.[\w-_]+)+(:\d+)(\/|$)/;
/** @type {RegExp} */
this.ipPortRe = /^\d+\.\d+\.\d+\.\d+(:\d+)?(\/|$)/;
/** @type {RegExp} */
this.workerBlobRe = /__WB_pmw\(.*?\)\.(?=postMessage\()/g;
/** @type {RegExp} */
this.rmCheckThisInjectRe = /_____WB\$wombat\$check\$this\$function_____\(.*?\)/g;
/** @type {RegExp} */
this.STYLE_REGEX = /(url\s*\(\s*[\\"']*)([^)'"]+)([\\"']*\s*\))/gi;
/** @type {RegExp} */
this.IMPORT_REGEX = /(@import\s*[\\"']*)([^)'";]+)([\\"']*\s*;?)/gi;
/** @type {RegExp} */
this.IMPORT_JS_REGEX = /^(import\s*\(['"]+)([^'"]+)(["'])/i;
/** @type {RegExp} */
this.no_wombatRe = /WB_wombat_/g;
/** @type {RegExp} */
this.srcsetRe = /\s*(\S*\s+[\d.]+[wx]),|(?:\s*,(?:\s+|(?=https?:)))/;
/** @type {RegExp} */
this.cookie_path_regex = /\bPath='?"?([^;'"\s]+)/i;
/** @type {RegExp} */
this.cookie_domain_regex = /\bDomain=([^;'"\s]+)/i;
/** @type {RegExp} */
this.cookie_expires_regex = /\bExpires=([^;'"]+)/gi;
/** @type {RegExp} */
this.SetCookieRe = /,(?![|])/;
/** @type {RegExp} */
this.IP_RX = /^(\d)+\.(\d)+\.(\d)+\.(\d)+$/;
/** @type {RegExp} */
this.FullHTMLRegex = /^\s*<(?:html|head|body|!doctype html)/i;
/** @type {RegExp} */
this.IsTagRegex = /^\s*</;
/** @type {RegExp} */
this.DotPostMessageRe = /(\.postMessage\s*\()/;
/** @type {RegExp} */
this.extractPageUnderModifierRE = /\/(?:[0-9]{14})?([a-z]{2, 3}_)\//;
/** @type {string} */
this.write_buff = '';
var eTargetProto = ($wbwindow.EventTarget || {}).prototype;
/** @type {Object} */
this.utilFns = {
cspViolationListener: function(e) {
console.group('CSP Violation');
console.log('Replayed Page URL', window.WB_wombat_location.href);
console.log('The documentURI', e.documentURI);
console.log('The blocked URL', e.blockedURI);
console.log('The directive violated', e.violatedDirective);
console.log('Our policy', e.originalPolicy);
if (e.sourceFile) {
var fileInfo = 'File: ' + e.sourceFile;
if (e.lineNumber && e.columnNumber) {
fileInfo += ' @ ' + e.lineNumber + ':' + e.columnNumber;
} else if (e.lineNumber) {
fileInfo += ' @ ' + e.lineNumber;
}
console.log(fileInfo);
}
console.groupEnd();
},
addEventListener: eTargetProto.addEventListener,
removeEventListener: eTargetProto.removeEventListener,
// some sites do funky things with the toString function
// (e.g. if used throw error or deny operation) hence we
// need a surefire and safe way to tell us what an object
// or function is hence Objects native toString
objToString: Object.prototype.toString,
wbSheetMediaQChecker: null,
XHRopen: null,
XHRsend: null
};
/**
* @type {{yesNo: boolean, added: boolean}}
*/
this.showCSPViolations = { yesNo: false, added: false };
autobind(this);
// this._addRemoveCSPViolationListener(true);
}
/**
* Performs the initialization of wombat's internals:
* - {@link initTopFrame}
* - {@link initWombatLoc}
* - {@link initWombatTop}
* - {@link initAutoFetchWorker}
* - initializes the wb_rel_prefix property
* - initializes the wb_unrewrite_rx property
* - if we are in framed replay mode and the wb_info mod is not bn_
* {@link initTopFrameNotify} is called
* @private
*/
Wombat.prototype._internalInit = function() {
this.initTopFrame(this.$wbwindow);
this.initWombatLoc(this.$wbwindow);
this.initWombatTop(this.$wbwindow);
// updated wb_unrewrite_rx for imgur.com
var wb_origin = this.$wbwindow.__WB_replay_top.location.origin;
var wb_host = this.$wbwindow.__WB_replay_top.location.host;
var wb_proto = this.$wbwindow.__WB_replay_top.location.protocol;
if (this.wb_replay_prefix && this.wb_replay_prefix.indexOf(wb_origin) === 0) {
this.wb_rel_prefix = this.wb_replay_prefix.substring(wb_origin.length);
} else {
this.wb_rel_prefix = this.wb_replay_prefix;
}
this.wb_prefixes = [this.wb_abs_prefix, this.wb_rel_prefix];
// make the protocol and host optional now
var rx =
'((' + wb_proto + ')?//' + wb_host + ')?' + this.wb_rel_prefix + '[^/]+/';
this.wb_unrewrite_rx = new RegExp(rx, 'g');
if (this.wb_info.is_framed && this.wb_info.mod !== 'bn_') {
this.initTopFrameNotify(this.wb_info);
}
this.initAutoFetchWorker();
};
/**
* Internal function that adds a "securitypolicyviolation" event listener
* to the document that will log any CSP violations in a nicer way than
* is the default
*
* If the yesNo argument is true, the event listener is added, otherwise
* it is removed
* @param {boolean} yesNo
* @private
*/
Wombat.prototype._addRemoveCSPViolationListener = function(yesNo) {
this.showCSPViolations.yesNo = yesNo;
if (this.showCSPViolations.yesNo && !this.showCSPViolations.added) {
this.showCSPViolations.added = true;
this._addEventListener(
document,
'securitypolicyviolation',
this.utilFns.cspViolationListener
);
} else {
this.showCSPViolations.added = false;
this._removeEventListener(
document,
'securitypolicyviolation',
this.utilFns.cspViolationListener
);
}
};
/**
* Adds the supplied event listener on the supplied event target
* @param {Object} obj
* @param {string} event
* @param {Function} fun
* @return {*}
* @private
*/
Wombat.prototype._addEventListener = function(obj, event, fun) {
if (this.utilFns.addEventListener) {
return this.utilFns.addEventListener.call(obj, event, fun);
}
obj.addEventListener(event, fun);
};
/**
* Removes the supplied event listener on the supplied event target
* @param {Object} obj
* @param {string} event
* @param {Function} fun
* @return {*}
* @private
*/
Wombat.prototype._removeEventListener = function(obj, event, fun) {
if (this.utilFns.removeEventListener) {
return this.utilFns.removeEventListener.call(obj, event, fun);
}
obj.removeEventListener(event, fun);
};
/**
* Extracts the modifier (i.e. mp\_, if\_, ...) the page is under that wombat is
* operating in. If extracting the modifier fails for some reason mp\_ is returned.
* Used to ensure the correct modifier is used for rewriting the service workers scope.
* @return {string}
*/
Wombat.prototype.getPageUnderModifier = function() {
try {
var pageUnderModifier = this.extractPageUnderModifierRE.exec(
location.pathname
);
if (pageUnderModifier && pageUnderModifier[1]) {
var mod = pageUnderModifier[1].trim();
return mod || 'mp_';
}
} catch (e) {}
return 'mp_';
};
/**
* Returns T/F indicating if the supplied function is a native function
* or not. The test checks for the presence of the substring `'[native code]'`
* in the result of calling `toString` on the function
* @param {Function} funToTest - The function to be tested
* @return {boolean}
*/
Wombat.prototype.isNativeFunction = function(funToTest) {
if (!funToTest || typeof funToTest !== 'function') return false;
var str = this.wb_funToString.call(funToTest);
if (str.indexOf('[native code]') == -1) {
return false;
}
if (funToTest.__WB_is_native_func__ !== undefined) {
return !!funToTest.__WB_is_native_func__;
}
return true;
};
/**
* Returns T/F indicating if the supplied argument is a string or not
* @param {*} arg
* @return {boolean}
*/
Wombat.prototype.isString = function(arg) {
return arg != null && Object.getPrototypeOf(arg) === String.prototype;
};
/**
* Create blob for content, convert to service-worker based blob URL
* set iframe to remove blob URL on unload
*
*/
Wombat.prototype.blobUrlForIframe = function(iframe, string) {
var blob = new Blob([string], {type: 'text/html'});
var url = URL.createObjectURL(blob);
iframe.__wb_blobSrc = url;
iframe.addEventListener('load', function() {
if (iframe.__wb_blobSrc) {
URL.revokeObjectURL(iframe.__wb_blobSrc);
iframe.__wb_blobSrc = null;
}
}, {once: true});
iframe.__wb_origSrc = iframe.src;
var blobIdUrl = url.slice(url.lastIndexOf('/') + 1) + '/' + this.wb_info.url;
iframe.src = this.wb_info.prefix + this.wb_info.request_ts + 'mp_/blob:' + blobIdUrl;
};
/**
* Returns T/F indicating if the supplied element may have attributes that
* are auto-fetched
* @param {Element} elem
* @return {boolean}
*/
Wombat.prototype.isSavedSrcSrcset = function(elem) {
switch (elem.tagName) {
case 'IMG':
case 'VIDEO':
case 'AUDIO':
return true;
case 'SOURCE':
if (!elem.parentElement) return false;
switch (elem.parentElement.tagName) {
case 'PICTURE':
case 'VIDEO':
case 'AUDIO':
return true;
default:
return false;
}
default:
return false;
}
};
/**
* Returns T/F indicating if the supplied element is an Image element that
* may have srcset values to be sent to the backing auto-fetch worker
* @param {Element} elem
* @return {boolean}
*/
Wombat.prototype.isSavedDataSrcSrcset = function(elem) {
if (elem.dataset && elem.dataset.srcset != null) {
return this.isSavedSrcSrcset(elem);
}
return false;
};
/**
* Determines if the supplied string is an host URL
* @param {string} str
* @return {boolean}
*/
Wombat.prototype.isHostUrl = function(str) {
// Good guess that's its a hostname
if (str.indexOf('www.') === 0) {
return true;
}
// hostname:port (port required)
var matches = str.match(this.hostnamePortRe);
if (matches && matches[0].length < 64) {
return true;
}
// ip:port
matches = str.match(this.ipPortRe);
if (matches) {
return matches[0].length < 64;
}
return false;
};
/**
* Returns T/F indicating if the supplied object is the arguments object
* @param {*} maybeArgumentsObj
* @return {boolean}
*/
Wombat.prototype.isArgumentsObj = function(maybeArgumentsObj) {
if (
!maybeArgumentsObj ||
!(typeof maybeArgumentsObj.toString === 'function')
) {
return false;
}
try {
return (
this.utilFns.objToString.call(maybeArgumentsObj) === '[object Arguments]'
);
} catch (e) {
return false;
}
};
/**
* Ensures that each element in the supplied arguments object or
* array is deproxied handling cases where we can not modify the
* supplied object returning a new or modified object with the
* exect elements/properties
* @param {*} maybeArgumentsObj
* @return {*}
*/
Wombat.prototype.deproxyArrayHandlingArgumentsObj = function(
maybeArgumentsObj
) {
if (
!maybeArgumentsObj ||
maybeArgumentsObj instanceof NodeList ||
!maybeArgumentsObj.length
) {
return maybeArgumentsObj;
}
var args = this.isArgumentsObj(maybeArgumentsObj)
? new Array(maybeArgumentsObj.length)
: maybeArgumentsObj;
for (var i = 0; i < maybeArgumentsObj.length; ++i) {
const res = this.proxyToObj(maybeArgumentsObj[i]);
if (res !== args[i]) {
args[i] = res;
}
}
return args;
};
/**
* Determines if a string starts with the supplied prefix.
* If it does the matching prefix is returned otherwise undefined.
* @param {?string} string
* @param {string} prefix
* @return {?string}
*/
Wombat.prototype.startsWith = function(string, prefix) {
if (!string) return undefined;
return string.indexOf(prefix) === 0 ? prefix : undefined;
};
/**
* Determines if a string starts with the supplied array of prefixes.
* If it does the matching prefix is returned otherwise undefined.
* @param {?string} string
* @param {Array<string>} prefixes
* @return {?string}
*/
Wombat.prototype.startsWithOneOf = function(string, prefixes) {
if (!string) return undefined;
for (var i = 0; i < prefixes.length; i++) {
if (string.indexOf(prefixes[i]) === 0) {
return prefixes[i];
}
}
return undefined;
};
/**
* Determines if a string ends with the supplied suffix.
* If it does the suffix is returned otherwise undefined.
* @param {?string} str
* @param {string} suffix
* @return {?string}
*/
Wombat.prototype.endsWith = function(str, suffix) {
if (!str) return undefined;
if (str.indexOf(suffix, str.length - suffix.length) !== -1) {
return suffix;
}
return undefined;
};
/**
* Returns T/F indicating if the supplied tag name and attribute name
* combination are to be rewritten
* @param {string} tagName
* @param {string} attr
* @return {boolean}
*/
Wombat.prototype.shouldRewriteAttr = function(tagName, attr) {
switch (attr) {
case 'href':
case 'src':
case 'xlink:href':
return true;
}
if (
tagName &&
this.tagToMod[tagName] &&
this.tagToMod[tagName][attr] !== undefined
) {
return true;
}
return (
(tagName === 'VIDEO' && attr === 'poster') ||
(tagName === 'META' && attr === 'content')
);
};
/**
* Returns T/F indicating if the script tag being rewritten should not
* have its text contents wrapped based on the supplied script type.
* @param {?string} scriptType
* @return {boolean}
*/
Wombat.prototype.skipWrapScriptBasedOnType = function(scriptType) {
if (!scriptType) return false;
if (scriptType.indexOf('javascript') >= 0 || scriptType.indexOf('ecmascript') >= 0) return false;
if (scriptType.indexOf('json') >= 0) return true;
if (scriptType.indexOf('text/') >= 0) return true;
return false;
};
/**
* Returns T/F indicating if the script tag being rewritten should not
* have its text contents wrapped based on heuristic analysis of its
* text contents.
* @param {?string} text
* @return {boolean}
*/
Wombat.prototype.skipWrapScriptTextBasedOnText = function(text) {
if (
!text ||
text.indexOf(this.WB_ASSIGN_FUNC) >= 0 ||
text.indexOf('<') === 0
) {
return true;
}
var override_props = [
'window',
'self',
'document',
'location',
'top',
'parent',
'frames',
'opener'
];
for (var i = 0; i < override_props.length; i++) {
if (text.indexOf(override_props[i]) >= 0) {
return false;
}
}
return true;
};
/**
* Returns T/F indicating if the supplied DOM Node has child Elements/Nodes.
* Note this function should be used when the Node(s) being considered can
* be null/undefined.
* @param {Node} node
* @return {boolean}
*/
Wombat.prototype.nodeHasChildren = function(node) {
if (!node) return false;
if (typeof node.hasChildNodes === 'function') return node.hasChildNodes();
var kids = node.children || node.childNodes;
if (kids) return kids.length > 0;
return false;
};
/**
* Returns the correct rewrite modifier for the supplied element and
* attribute combination if one exists otherwise mp_.
* Used by
* - {@link performAttributeRewrite}
* - {@link rewriteFrameSrc}
* - {@link initElementGetSetAttributeOverride}
* - {@link overrideHrefAttr}
*
* @param {*} elem
* @param {string} attrName
* @return {?string}
*/
Wombat.prototype.rwModForElement = function(elem, attrName) {
if (!elem) return undefined;
// the default modifier, if none is supplied to rewrite_url, is mp_
var mod = 'mp_';
if (elem.tagName === 'LINK' && attrName === 'href') {
// link types are always ASCII case-insensitive, and must be compared as such.
// https://html.spec.whatwg.org/multipage/links.html#linkTypes
if (elem.rel) {
var relV = elem.rel.trim().toLowerCase();
var asV = this.wb_getAttribute.call(elem, 'as');
if (asV && this.linkTagMods.linkRelToAs[relV] != null) {
var asMods = this.linkTagMods.linkRelToAs[relV];
mod = asMods[asV.toLowerCase()];
} else if (this.linkTagMods[relV] != null) {
mod = this.linkTagMods[relV];
}
}
} else {
// check if this element has an rewrite modifiers and set mod to it if it does
var maybeMod = this.tagToMod[elem.tagName];
if (maybeMod != null) {
mod = maybeMod[attrName];
}
}
return mod;
};
/**
* If the supplied element is a script tag and has the server-side rewrite added
* property "__wb_orig_src" it is removed and the "__$removedWBOSRC$__" property
* is added to element as an internal flag indicating no further checks are to be
* made.
*
* See also {@link retrieveWBOSRC}
* @param {Element} elem
*/
Wombat.prototype.removeWBOSRC = function(elem) {
if (elem.tagName === 'SCRIPT' && !elem.__$removedWBOSRC$__) {
if (elem.hasAttribute('__wb_orig_src')) {
elem.removeAttribute('__wb_orig_src');
}
elem.__$removedWBOSRC$__ = true;
}
};
/**
* If the supplied element is a script tag and has the server-side rewrite added
* property "__wb_orig_src" its value is returned otherwise undefined is returned.
* If the element did not have the "__wb_orig_src" property the
* "__$removedWBOSRC$__" property is added to element as an internal flag
* indicating no further checks are to be made.
*
* See also {@link removeWBOSRC}
* @param {Element} elem
* @return {?string}
*/
Wombat.prototype.retrieveWBOSRC = function(elem) {
if (elem.tagName === 'SCRIPT' && !elem.__$removedWBOSRC$__) {
var maybeWBOSRC;
if (this.wb_getAttribute) {
maybeWBOSRC = this.wb_getAttribute.call(elem, '__wb_orig_src');
} else {
maybeWBOSRC = elem.getAttribute('__wb_orig_src');
}
if (maybeWBOSRC == null) elem.__$removedWBOSRC$__ = true;
return maybeWBOSRC;
}
return undefined;
};
/**
* Wraps the supplied text contents of a script tag with the required Wombat setup
* @param {?string} scriptText
* @return {string}
*/
Wombat.prototype.wrapScriptTextJsProxy = function(scriptText) {
return (
'var _____WB$wombat$assign$function_____ = function(name) {return ' +
'(self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };\n' +
'if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { ' +
'this.__WB_source = obj; return this; } }\n{\n' +
'let window = _____WB$wombat$assign$function_____("window");\n' +
'let globalThis = _____WB$wombat$assign$function_____("globalThis");\n' +
'let self = _____WB$wombat$assign$function_____("self");\n' +
'let document = _____WB$wombat$assign$function_____("document");\n' +
'let location = _____WB$wombat$assign$function_____("location");\n' +
'let top = _____WB$wombat$assign$function_____("top");\n' +
'let parent = _____WB$wombat$assign$function_____("parent");\n' +
'let frames = _____WB$wombat$assign$function_____("frames");\n' +
'let opener = _____WB$wombat$assign$function_____("opener");\n{\n' +
scriptText.replace(this.DotPostMessageRe, '.__WB_pmw(self.window)$1') +
'\n\n}}'
);
};
/**
* Calls the supplied function when the supplied element undergoes mutations
* @param elem
* @param func
* @return {boolean}
*/
Wombat.prototype.watchElem = function(elem, func) {
if (!this.$wbwindow.MutationObserver) {
return false;
}
var m = new this.$wbwindow.MutationObserver(function(records, observer) {
for (var i = 0; i < records.length; i++) {
var r = records[i];
if (r.type === 'childList') {
for (var j = 0; j < r.addedNodes.length; j++) {
func(r.addedNodes[j]);
}
}
}
});
m.observe(elem, {
childList: true,
subtree: true
});
};
/**
* Reconstructs the doctype string if the supplied doctype object
* is non null/undefined. This function is used by {@link rewriteHtmlFull}
* in order to ensure correctness of rewriting full string of HTML that
* started with <!doctype ...> since the innerHTML and outerHTML properties
* do not include that.
* @param {DocumentType} doctype
* @return {string}
*/
Wombat.prototype.reconstructDocType = function(doctype) {
if (doctype == null) return '';
return (
'<!doctype ' +
doctype.name +
(doctype.publicId ? ' PUBLIC "' + doctype.publicId + '"' : '') +
(!doctype.publicId && doctype.systemId ? ' SYSTEM' : '') +
(doctype.systemId ? ' "' + doctype.systemId + '"' : '') +
'>'
);
};
/**
* Constructs the final URL for the URL rewriting process
* @param {boolean} useRel
* @param {string} mod
* @param {string} url
* @return {string}
*/
Wombat.prototype.getFinalUrl = function(useRel, mod, url) {
var prefix = useRel ? this.wb_rel_prefix : this.wb_abs_prefix;
if (mod == null) {
mod = this.wb_info.mod;
}
// if live, don't add the timestamp
if (!this.wb_info.is_live) {
prefix += this.wb_info.wombat_ts;
}
prefix += mod;
if (prefix[prefix.length - 1] !== '/') {
prefix += '/';
}
return prefix + url;
};
/**
* Converts the supplied relative URL to an absolute URL using an A tag
* @param {string} url
* @param {?Document} doc
* @return {string}
*/
Wombat.prototype.resolveRelUrl = function(url, doc) {
var docObj = doc || this.$wbwindow.document;
var parser = this.makeParser(docObj.baseURI, docObj);
var hash = parser.href.lastIndexOf('#');
var href = hash >= 0 ? parser.href.substring(0, hash) : parser.href;
var lastslash = href.lastIndexOf('/');
if (lastslash >= 0 && lastslash !== href.length - 1) {
parser.href = href.substring(0, lastslash + 1) + url;
} else {
parser.href = href + url;
}
return parser.href;
};
/**
* Extracts the original URL from the supplied rewritten URL
* @param {?string} rewrittenUrl
* @return {string}
*/
Wombat.prototype.extractOriginalURL = function(rewrittenUrl) {
if (!rewrittenUrl) {
return '';
} else if (this.wb_is_proxy) {
// proxy mode: no extraction needed
return rewrittenUrl;
}
var rwURLString = rewrittenUrl.toString();
var url = rwURLString;
// ignore certain urls
if (this.startsWithOneOf(url, this.IGNORE_PREFIXES)) {
return url;
}
if (url.startsWith(this.wb_info.static_prefix)) {
return url;
}
var start;
if (this.startsWith(url, this.wb_abs_prefix)) {
start = this.wb_abs_prefix.length;
} else if (this.wb_rel_prefix && this.startsWith(url, this.wb_rel_prefix)) {
start = this.wb_rel_prefix.length;
} else {
// if no coll, start from beginning, otherwise could be part of coll..
start = this.wb_rel_prefix ? 1 : 0;
}
var index = url.indexOf('/http', start);
if (index < 0) {
index = url.indexOf('///', start);
}
if (index < 0) {
index = url.indexOf('/blob:', start);
}
if (index < 0) {
index = url.indexOf('/about:blank', start);
}
// extract original url from wburl
if (index >= 0) {
url = url.substr(index + 1);
} else {
index = url.indexOf(this.wb_replay_prefix);
if (index >= 0) {
url = url.substr(index + this.wb_replay_prefix.length);
}
if (url.length > 4 && url.charAt(2) === '_' && url.charAt(3) === '/') {
url = url.substr(4);