-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.js
703 lines (552 loc) · 21 KB
/
proxy.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
//
// Documentation:
// ================
// This project is a template script you can customize then insert at the begining of your document.
// It will enable you to log which native functions are being called by your application.
// You can filter the log to only include particular instances like slow function calls.
// You can also log more information like the call stack at the time of the log.
//
void function() {
//
// Import stuff we want to use (before we wrap or replace them, eventually)
//
var console = window.console;
/** @type {ObjectConstructor} */ var Object = window.Object;
/** @type {FunctionConstructor} */ var Function = window.Function;
/** @type {SetConstructor} */ var Set = window.Set;
/** @type {ProxyConstructor} */ var Proxy = window.Proxy;
/** @type {WeakMapConstructor} */ var WeakMap = window.WeakMap;
/** @type {SymbolConstructor} */ var Symbol = window.Symbol;
var functionToString = Function.prototype.toString;
var objectToString = Object.prototype.toString;
var bindFunction = Function.prototype.bind;
//
// Prerequirement: be able to distinguish between native and bound functions
// This is done by adding a tag to user-functions returned by "func.bind(obj)"
//
var isNativeFunction_map = new WeakMap();
var isNativeFunction = function(f) {
if(typeof(f) != 'function') { /*debugger;*/ return false; }
var isKnownNativeFunction = isNativeFunction_map.get(f);
if(isKnownNativeFunction !== undefined) return isKnownNativeFunction;
var isNative = (
/^function[^]*?\([^]*?\)[^]*?\{[^]*?\[native code\][^]*?\}$/m.test(functionToString.call(f))
);
isNativeFunction_map.set(f, isNative);
return isNative;
};
var shouldBeWrapped = function(f) {
return !isAlreadyWrapped(f) && isFromThisRealm(f) && (!~objectsToNeverWrapProperties.indexOf(f)) && (typeof(f) == 'function' ? isNativeFunction(f) : (f.constructor ? f.constructor !== Object && isNativeFunction(unbox(f.constructor)) : false));
}
Function.prototype.bind = function() {
var boundFunction = bindFunction.apply(this, arguments);
isNativeFunction_map.set(boundFunction, false);
return boundFunction;
};
//
// Sepcial logic to try to catch Event objects before they leak unwrapped to event listeners callbacks
//
var aEL = EventTarget.prototype.addEventListener;
var rEL = EventTarget.prototype.removeEventListener;
var aEL_map = new WeakMap();
var aEL_box = function(fn) {
var aEL_fn = aEL_map.get(fn);
if(!aEL_fn) {
aEL_fn = function(...args) {
return fn.apply(wrapInProxy(this,undefined), args.map(arg => wrapInProxy(arg,undefined)))
}
aEL_map.set(fn, aEL_fn);
}
return aEL_fn;
}
EventTarget.prototype.addEventListener = function(eventName, callback, options) {
if(!callback) return;
var This = unbox(this);
var boxed_callback = aEL_box(callback)
aEL.call(This, eventName, boxed_callback, options);
}
EventTarget.prototype.removeEventListener = function(eventName, callback, options) {
if(!callback) return;
var This = unbox(this);
var wrapper = aEL_map.get(callback) || callback;
rEL.call(This, eventName, wrapper, options);
}
//
// Helper:
// Returns trus if the object is from this window
// Returns false if the object is from another iframe/window
//
var isFromThisRealm = function(obj) {
return (obj instanceof Object);
}
//
// Helper:
// Returns "Object", "Array", "Window", or another native type value
//
var getNativeTypeOf = function(o) {
try { o = unbox(o); } catch(ex) {}
var s = objectToString.call(o);
var i = '[object '.length;
return s.substr(i,s.length-i-1);
};
//
// Helper:
// Returns "Object", "Array", "Window", or another native type value
// The difference with the above function is that if possible the name of the prototype linked to property "key" is used
//
function getNativePrototypeTypeOf(obj, key) {
var fallbackName = getNativeTypeOf(obj);
try {
while(!Object.hasOwnProperty.call(obj, key)) {
obj = Object.getPrototypeOf(obj);
}
return getNativeTypeOf(obj);
} catch (ex) {
// give up
}
return fallbackName;
}
//
// Helper:
// Returns a string representation of an object key (o[key] or o.key)
//
var getKeyAsStringFrom = function(o) {
try { if(typeof(o) == 'symbol') { return `[${o.toString()}]`; } } catch(ex) { return '[symbol]' }
try { if(/^[0-9]+$/.test(o)) { return '[int]'; } } catch (ex) {}
try { return `${o}` } catch (ex) {}
try { return `[${o.toString()}]`; } catch (ex) {}
try { if(o.constructor) return '['+o.constructor.name+']'; } catch (ex) {}
return '[???]';
}
//
// Helper:
// Returns the property descriptor, eventually from a prototype
//
var getPropertyDescriptorOf = function(o, k) {
try {
var property = Object.getOwnPropertyDescriptor(o,k);
let proto = o;
while(!property && proto) {
proto=Object.getPrototypeOf(proto);
property = proto ? Object.getOwnPropertyDescriptor(proto,k) : null;
}
} catch (ex) {/*debugger;*/}
return property;
}
//
// Storage of the proxy-object to/from source-object links
//
var stp_map = new WeakMap();
var pts_map = new WeakMap();
var unbox = function(obj) { var proxyInfo = pts_map.get(obj); return proxyInfo && proxyInfo.this ? proxyInfo.this : obj; }
var unboxName = function(obj) { var proxyInfo = pts_map.get(obj); return proxyInfo ? proxyInfo.name : undefined; }
var isAlreadyWrapped = function(obj) { return obj === null || obj === undefined || (typeof(obj) != 'object' && typeof(obj) != 'function') || pts_map.has(obj); };
//
// This is the algorithm we want to run when an API is being used
//
// CUSTOMIZE HERE:
// this is where we will store our information, we will export it as window.log on the page
var log = new Array();
function add_log(name) {
log.push(name);
}
/*
var log = new Set();
function add_log(name) {
log.add(name);
}
*/
// this is how operations on the proxies will work:
var proxyCode = {
// htmlElement.innerHTML (o = htmlElement, k = "innerHTML")
get(o,k) {
try {
// if we want to measure how long this operation took:
//var operationTime = -performance.now()
// get the value from the source object
var returnValue = o[k];
} finally {
// if we want to know how long this operation took:
//operationTime += performance.now();
// CUSTOMIZE HERE:
var property = getPropertyDescriptorOf(o, k);
if(!property.get || isNativeFunction(property.get)) {
try { var name = `${getNativePrototypeTypeOf(o,k)}.${getKeyAsStringFrom(k)}`; } catch (ex) {/*debugger;*/};
try { if(name) add_log(`${name}`) } catch (ex) {/*debugger;*/};
}
}
// since we want to continue to receive usage info for the object we are about to return...
if(returnValue && shouldBeWrapped(returnValue)) {
// first, we need to know if we can wrap it in a proxy...
var property = getPropertyDescriptorOf(o, k);
var doesPropertyAllowProxyWrapping = !property || (property.set || property.writable) || property.configurable;
if(doesPropertyAllowProxyWrapping) {
// if we can, that is the best option
returnValue = wrapInProxy(returnValue, undefined);
} else {
// if not (rare) we will do our best by special-casing the object
try { wrapPropertiesOf(returnValue,name); } catch (ex) {/*debugger;*/}
}
}
return returnValue;
},
// htmlElement.innerHTML = responseText; (o = htmlElement, k = "innerHTML", v = responseText)
set(o,k,v) {
try {
// if we want to measure how long this operation took:
//var operationTime = -performance.now()
// set the value on the source object
o[k]=v;
} finally {
// if we want to know how long this operation took:
//operationTime += performance.now();
// CUSTOMIZE HERE:
var property = getPropertyDescriptorOf(o, k);
if(!property.set || isNativeFunction(property.set)) {
try {
var name = `${getNativePrototypeTypeOf(o,k)}.${getKeyAsStringFrom(k)}=${getNativeTypeOf(v)}`;
add_log(name)
} catch (ex) {/*debugger;*/};
}
}
return true;
},
// htmlElement.focus(); (o = htmlElement.focus, t = htmlElement, a = [])
apply(o,t,a) {
// special rule: if we are calling a native function, none of the arguments can be proxies
if(isNativeFunction(o)) {
t = unbox(t);
a=a.map(a => unbox(a));
}
try {
// if we want to measure how long this operation took:
//var operationTime = -performance.now()
// call the function and return its result
var returnValue = o.apply(t,a);
} finally {
// if we want to know how long this operation took:
//operationTime += performance.now();
// CUSTOMIZE HERE:
if(isNativeFunction(o)) {
var name = `${unboxName(o) || ''}`;
if(!name && o.name) {
try {name = `${unboxName(o)||(getNativePrototypeTypeOf(t||window,o.name)+'.'+getKeyAsStringFrom(o.name))}`; } catch (ex) {/*debugger;*/};
}
if(!name) {
try { name = `${unboxName(o)||(getNativeTypeOf(t||window)+'.'+'[???]')}`; } catch (ex) {/*debugger;*/};
}
try { name = `${name}(${a.map(x=>getNativeTypeOf(x)).join(',')})`; } catch (ex) { /*debugger;*/ };
try { add_log(`${name}`) } catch (ex) {}
}
}
return wrapInProxy(returnValue,name);
},
// new CustomEvent("click"); (o = CustomEvent, a = ["click"])
construct(o,a) {
// special rule: if we are calling a native function, none of the arguments can be proxies
if(isNativeFunction(o)) {
a=a.map(a => unbox(a));
}
try {
// if we want to measure how long this operation took:
//var operationTime = -performance.now()
// create a new instance of the object, and return it
var returnValue = wrapInProxy(Reflect.construct(o,a), undefined);
} finally {
// if we want to know how long this operation took:
//operationTime += performance.now();
// CUSTOMIZE HERE:
if(isNativeFunction(o)) {
var name = `${unboxName(o) || ''}`;
if(!name && o.name) {
try {name = `${unboxName(o)||getKeyAsStringFrom(o.name)}`; } catch (ex) {/*debugger;*/};
}
if(!name) {
try { name = `${unboxName(o)||getNativeTypeOf(returnValue)}`; } catch (ex) {/*debugger;*/};
}
try { name = `new ${name}`; } catch (ex) { /*debugger;*/ };
try { name = `${name}(${a.map(x=>getNativeTypeOf(x)).join(',')})`; } catch (ex) { /*debugger;*/ };
try { add_log(`${name}`) } catch (ex) {}
}
}
return returnValue;
}
};
//
// Helper:
// Creates a proxy for the given source object and name, if needed (and return it)
//
function wrapInProxy(obj,name) {
// special rule: non-objects do not need a proxy
if(obj === null) return obj;
if(obj === undefined) return obj;
if(!(typeof(obj) == 'function' || typeof(obj) == 'object')) return obj;
if(~objectsToNeverWrapInProxy.indexOf(obj)) return obj;
// special rule: do not try to track cross-document objects
if(!isFromThisRealm(obj)) { console.warn('Cross-document object detected: ', obj); return obj; }
// special rule: do not proxy an object that has been special-cased
if(isAlreadyWrapped(obj)) {
let pxy = stp_map.get(obj) || obj;
let objData = pts_map.get(pxy);
if(!objData.name) { objData.name = name; }
return pxy;
}
// special rule: do not touch an object that is already a proxy
{
let pxy = stp_map.get(obj);
if(pxy) return pxy;
}
// do not wrap non-native objects (TODO: expand detection?)
if(!shouldBeWrapped(obj)) { /*debugger;*/ return obj; }
// wrap the object in proxy, and add some metadata
try {
let objData = { this: obj, name: name };
let pxy = new Proxy(obj, proxyCode);
stp_map.set(obj, pxy);
pts_map.set(pxy, objData);
isNativeFunction_map.set(pxy, false); // HACK: Edge fix
try {
// wrap the properties of all prototypes
let proto = Object.getPrototypeOf(obj);
while(proto && !isAlreadyWrapped(proto)) {
wrapPropertiesOf(proto, proto.constructor ? proto.constructor.name : undefined);
proto = Object.getPrototypeOf(proto);
}
} catch (ex) {
/*debugger;*/
}
return pxy;
} catch (ex) {
return obj;
}
}
//
// Helper:
// Tries to catch get/set on an object without creating a proxy for it (unsafe special case)
//
function wrapPropertiesOf(obj, name) {
// special rule: don't rewrap a wrapped object
if(isAlreadyWrapped(obj)) return;
// mark the object as wrapped already
let objData = { this: obj, name: name };
pts_map.set(obj, objData);
// wrap the properties of all prototypes
let proto = Object.getPrototypeOf(obj);
while(proto && !isAlreadyWrapped(proto)) {
wrapPropertiesOf(proto, proto.constructor ? proto.constructor.name : undefined);
proto = Object.getPrototypeOf(proto);
}
if(~objectsToNeverWrapProperties.indexOf(obj)) return;
// for all the keys of this object
let objKeys = new Set(Object.getOwnPropertyNames(obj));
for(let key in obj) { objKeys.add(key) };
for(let key of objKeys) {
try {
// special rule: avoid problematic global properties
if(obj === window && (key == 'window' || key=='top' || key=='self' || key=='document' || key=='location' || key=='Object' || key=='Array' || key=='Function' || key=='Date' || key=='Number' || key=='String' || key=='Boolean' || key == 'Symbol')) {
continue;
}
if(obj === window.document && (key =='location')) {
continue;
}
if(key == '__proto__' || key == '__lookupGetter__' || key == '__lookupSetter__' || key == '__defineGetter__' || key == '__defineSetter__') {
continue;
}
if(obj == Function.prototype && (key == 'toString')) {
continue;
}
if(obj instanceof Function && (key == 'name' || key == 'length' || key == 'prototype')) {
continue;
}
// TODO?
// key=='contentWindow' || key=='contentDocument' || key=='parentWindow' || key=='parentDocument' || key=='ownerDocument'
// try to find where the property has been defined in the prototype chain
let property = Object.getOwnPropertyDescriptor(obj,key);
let proto = obj;
while(!property && proto) {
proto=Object.getPrototypeOf(proto);
property = proto ? Object.getOwnPropertyDescriptor(proto,key) : null;
}
if(!property) continue;
// try to find if we can override the property
// we only need to do this if this is an own property, or we could not configure the property on a prototype
if((proto !== obj && property.configurable)) { continue; }
if((proto === obj && property.configurable) || (proto !== obj && !property.configurable)) {
if(property.get) {
// in the case of a getter/setter, we can just duplicate
Object.defineProperty(obj, key, {
get() {
// special rule: when setting a value in the native world, we need to unwrap the value
var t = this;
if(isNativeFunction(property.get)) {
t = unbox(this);
}
try {
// if we want to measure how long this operation took:
//var operationTime = -performance.now()
// set the value on the source object
var returnValue = property.get.call(t);
} finally {
// if we want to know how long this operation took:
//operationTime += performance.now();
// CUSTOMIZE HERE:
if(isNativeFunction(property.get)) {
try { add_log(`${getNativeTypeOf(proto)}.${getKeyAsStringFrom(key)}`) } catch (ex) {/*debugger;*/};
}
}
return wrapInProxy(returnValue, name+'.'+key);
},
set(v) {
// special rule: when setting a value in the native world, we need to unwrap the value
var t = this;
if(isNativeFunction(property.set)) {
t = unbox(this);
v = unbox(v);
}
try {
// if we want to measure how long this operation took:
//var operationTime = -performance.now()
// set the value on the source object
var returnValue = property.set.call(t, v);
} finally {
// if we want to know how long this operation took:
//operationTime += performance.now();
// CUSTOMIZE HERE:
if(isNativeFunction(property.set)) {
try {
var name = `${getNativeTypeOf(proto)}.${getKeyAsStringFrom(key)}=${getNativeTypeOf(v)}`;
add_log(name);
} catch (ex) {/*debugger;*/};
}
}
return returnValue;
}
});
} else if(proto === obj && property.writable) {
// in the case of a read-write data field, we can only wrap preventively
if(property.value && shouldBeWrapped(property.value)) {
try {
obj[key] = wrapInProxy(property.value,name+'.'+key);
} catch (ex) {
console.warn("Read-write property " + key + " of " + getNativeTypeOf(obj) + " object was left unwrapped");
/*debugger;*/
}
}
} else if(proto !== obj && !property.writable && "value" in property && shouldBeWrapped(property.value)) {
// in the case of a readonly inherited data field, we can just duplicate
Object.defineProperty(obj, key, {
value: wrapInProxy(property.value,name+'.'+key),
enumerable:property.enumerable,
writable:false,
});
} else if(proto === obj && !property.writable) {
// we cannot redefine the value of a non-configurable read-only property
if(property.value && shouldBeWrapped(property.value)) {
console.warn("Unable to wrap readonly property at this level: ", name, key);
}
} else if(proto === obj) {
if(key != 'URLUnencoded') { // HACK: Edge hack
console.warn("Unable to wrap strange property: ", name, key);
/*debugger;*/
}
} else {
// this doesn't need wrapping anyway
}
} else if (property.writable) {
// in the case of a read-write data field, we can try to wrap preventively
if(property.value && (typeof(property.value) == 'object' || typeof(property.value) == 'function')) {
try { obj[key] = wrapInProxy(property.value,name+'.'+key); } catch (ex) {/*debugger;*/}
}
} else if("value" in property) {
// in the case of a direct read-only data field, there is nothing we can do
if(shouldBeWrapped(property.value)) {
console.warn("Unable to wrap readonly property: ", name, key);
}
} else {
// wtf?
if(key != 'URLUnencoded') { // HACK: Edge hack
console.warn("Unable to wrap strange property: ", name, key);
/*debugger;*/
}
}
} catch (ex) {
console.warn("Unable to wrap property: ", name, key, ex);
}
}
}
//
// There are a few objects we don't want to wrap for performance reason
//
let objectsToNeverWrapInProxy = [
Object, Object.prototype, String, String.prototype, Number, Number.prototype, Boolean, Boolean.prototype,
RegExp, RegExp.prototype, Reflect, Function, Function.prototype,
Error, Error.prototype, DOMError, DOMError.prototype, DOMException, DOMException.prototype,
Set, Set.prototype, Set.prototype.add,
Array, Array.prototype,
document.location, window.location,
document, window, parent, top,
console, console.log, console.__proto__
// TODO: add more here
]
let objectsToNeverWrapProperties = [
Object, Object.prototype, String, String.prototype, Number, Number.prototype, Boolean, Boolean.prototype,
RegExp, RegExp.prototype, Reflect, Function, Function.prototype,
Error, Error.prototype, DOMError, DOMError.prototype, DOMException, DOMException.prototype,
Set, Set.prototype, Set.prototype.add,
Array, Array.prototype,
document.location, window.location,
parent != window ? parent : undefined,
top != window ? top : undefined,
console, console.log, console.__proto__
// TODO: add more here
]
// add all typed arrays and array buffers at once
for(var key of Object.getOwnPropertyNames(window)) {
if(typeof(key) == 'string' && ~key.indexOf('Array')) {
objectsToNeverWrapInProxy.push(window[key]);
objectsToNeverWrapProperties.push(window[key]);
if(window[key].prototype) {
objectsToNeverWrapInProxy.push(window[key].prototype);
objectsToNeverWrapProperties.push(window[key].prototype);
}
}
}
// add special support for "call" and "apply"
var functionCall = Function.prototype.call;
var functionApply = Function.prototype.apply;
functionToString.call = functionCall.call = functionApply.call = functionCall;
functionToString.apply = functionCall.apply = functionApply.apply = functionApply;
Function.prototype.call = function(obj, ...args) {
return wrapInProxy(functionCall.call(this, obj, ...args));
}
Function.prototype.apply = function(obj, args) {
return wrapInProxy(functionCall.call(this, obj, ...args));
}
//
// Now it is time to wrap the important objects of this realm
//
if(window.document) {
wrapPropertiesOf(window.document, 'document');
}
if(window.parent !== window) {
wrapPropertiesOf(window.parent, 'parent');
}
if(window.top !== window) {
wrapPropertiesOf(window.top, 'top');
}
wrapPropertiesOf(window, 'window');
//
// Disabled alternatives:
//
//wrapPropertiesOf(location, 'location');
//__window = wrapInProxy(window, 'window');
//__document = wrapInProxy(document, 'document');
//__location = wrapInProxy(location, 'location');
//__top = wrapInProxy(location, 'top');
//
// CUSTOMIZE HERE:
//
window.log = log;
log.length = 0;
/*log.clear();*/
}();