-
Notifications
You must be signed in to change notification settings - Fork 4
/
initSESPlus.js
6339 lines (5953 loc) · 221 KB
/
initSESPlus.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
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Exports a {@code ses.logger} which logs to the
* console if one exists.
*
* <p>This <code>logger.js</code> file both defines the logger API and
* provides default implementations for its methods. Because
* <code>logger.js</code> is normally packaged in
* <code>initSES.js</code>, it is built to support being overridden by
* a script run <i>earlier</i>. For example, for better diagnostics,
* consider loading and initializing <code>useHTMLLogger.js</code> first.
*
* <p>The {@code ses.logger} API consists of
* <dl>
* <dt>log, info, warn, and error methods</dt>
* <dd>each of which take a list of arguments which should be
* stringified and appended together. The logger should
* display this string associated with that severity level. If
* any of the arguments has an associated stack trace
* (presumably Error objects), then the logger <i>may</i> also
* show this stack trace. If no {@code ses.logger} already
* exists, the default provided here forwards to the
* pre-existing global {@code console} if one
* exists. Otherwise, all four of these do nothing. If we
* default to forwarding to the pre-existing {@code console} ,
* we prepend an empty string as first argument since we do
* not want to obligate all loggers to implement the console's
* "%" formatting. </dd>
* <dt>classify(postSeverity)</dt>
* <dd>where postSeverity is a severity
* record as defined by {@code ses.severities} in
* <code>repairES5.js</code>, and returns a helpful record
* consisting of a
* <dl>
* <dt>consoleLevel:</dt>
* <dd>which is one of 'log', 'info', 'warn', or
* 'error', which can be used to select one of the above
* methods.</dd>
* <dt>note:</dt>
* <dd>containing some helpful text to display
* explaining the impact of this severity on SES.</dd>
* </dl>
* <dt>reportRepairs(reports)</dt>
* <dd>where {@code reports} is the list of repair reports, each
* of which contains
* <dl>
* <dt>description:</dt>
* <dd>a string describing the problem</dd>
* <dt>preSeverity:</dt>
* <dd>a severity record (as defined by {@code
* ses.severities} in <code>repairES5.js</code>)
* indicating the level of severity of this problem if
* unrepaired. Or, if !canRepair, then the severity
* whether or not repaired.</dd>
* <dt>canRepair:</dt>
* <dd>a boolean indicating "if the repair exists and the test
* subsequently does not detect a problem, are we now ok?"</dd>
* <dt>urls:</dt>
* <dd>a list of URL strings, each of which points at a page
* relevant for documenting or tracking the bug in
* question. These are typically into bug-threads in issue
* trackers for the various browsers.</dd>
* <dt>sections:</dt>
* <dd>a list of strings, each of which is a relevant ES5.1
* section number.</dd>
* <dt>tests:</dt>
* <dd>a list of strings, each of which is the name of a
* relevant test262 or sputnik test case.</dd>
* <dt>postSeverity:</dt>
* <dd>a severity record (as defined by {@code
* ses.severities} in <code>repairES5.js</code>)
* indicating the level of severity of this problem
* after all repairs have been attempted.</dd>
* <dt>beforeFailure:</dt>
* <dd>The outcome of the test associated with this record
* as run before any attempted repairs. If {@code
* false}, it means there was no failure. If {@code
* true}, it means that the test fails in some way that
* the authors of <code>repairES5.js</code>
* expected. Otherwise it returns a string describing
* the symptoms of an unexpected form of failure. This
* is typically considered a more severe form of failure
* than {@code true}, since the authors have not
* anticipated the consequences and safety
* implications.</dd>
* <dt>afterFailure:</dt>
* <dd>The outcome of the test associated with this record
* as run after all attempted repairs.</dd>
* </dl>
* The default behavior here is to be silent.</dd>
* <dt>reportMax()</dt>
* <dd>Displays only a summary of the worst case
* severity seen so far, according to {@code ses.maxSeverity} as
* interpreted by {@code ses.logger.classify}.</dd>
* <dt>reportDiagnosis(severity, status, problemList)</dt>
* <dd>where {@code severity} is a severity record, {@code status}
* is a brief string description of a list of problems, and
* {@code problemList} is a list of strings, each of which is
* one occurrence of the described problem.
* The default behavior here should only the number of
* problems, not the individual problems.</dd>
* </dl>
*
* <p>Assumes only ES3. Compatible with ES5, ES5-strict, or
* anticipated ES6.
*
* //provides ses.logger
* @author Mark S. Miller
* @requires console
* @overrides ses, loggerModule
*/
var ses;
if (!ses) { ses = {}; }
(function loggerModule() {
"use strict";
var logger;
function logNowhere(str) {}
var slice = [].slice;
var apply = slice.apply;
if (ses.logger) {
logger = ses.logger;
} else if (typeof console !== 'undefined' && 'log' in console) {
// We no longer test (typeof console.log === 'function') since,
// on IE9 and IE10preview, in violation of the ES5 spec, it
// is callable but has typeof "object".
// See https://connect.microsoft.com/IE/feedback/details/685962/
// console-log-and-others-are-callable-but-arent-typeof-function
// We manually wrap each call to a console method because <ul>
// <li>On some platforms, these methods depend on their
// this-binding being the console.
// <li>All this has to work on platforms that might not have their
// own {@code Function.prototype.bind}, and has to work before
// we install an emulated bind.
// </ul>
var forward = function(level, args) {
args = slice.call(args, 0);
// We don't do "console.apply" because "console" is not a function
// on IE 10 preview 2 and it has no apply method. But it is a
// callable that Function.prototype.apply can successfully apply.
// This code most work on ES3 where there's no bind. When we
// decide support defensiveness in contexts (frames) with mutable
// primordials, we will need to revisit the "call" below.
apply.call(console[level], console, [''].concat(args));
// See debug.js
var getStack = ses.getStack;
if (getStack) {
for (var i = 0, len = args.length; i < len; i++) {
var stack = getStack(args[i]);
if (stack) {
console[level]('', stack);
}
}
}
};
logger = {
log: function log(var_args) { forward('log', arguments); },
info: function info(var_args) { forward('info', arguments); },
warn: function warn(var_args) { forward('warn', arguments); },
error: function error(var_args) { forward('error', arguments); }
};
} else {
logger = {
log: logNowhere,
info: logNowhere,
warn: logNowhere,
error: logNowhere
};
}
/**
* Returns a record that's helpful for displaying a severity.
*
* <p>The record contains {@code consoleLevel} and {@code note}
* properties whose values are strings. The {@code consoleLevel} is
* {@code "log", "info", "warn", or "error"}, which can be used as
* method names for {@code logger}, or, in an html context, as a css
* class name. The {@code note} is a string stating the severity
* level and its consequences for SES.
*/
function defaultClassify(postSeverity) {
var MAX_SES_SAFE = ses.severities.SAFE_SPEC_VIOLATION;
var consoleLevel = 'log';
var note = '';
if (postSeverity.level > ses.severities.SAFE.level) {
consoleLevel = 'info';
note = postSeverity.description + '(' + postSeverity.level + ')';
if (postSeverity.level > ses.maxAcceptableSeverity.level) {
consoleLevel = 'error';
note += ' is not suitable for SES';
} else if (postSeverity.level > MAX_SES_SAFE.level) {
consoleLevel = 'warn';
note += ' is not SES-safe';
}
note += '.';
}
return {
consoleLevel: consoleLevel,
note: note
};
}
if (!logger.classify) {
logger.classify = defaultClassify;
}
/**
* By default is silent
*/
function defaultReportRepairs(reports) {}
if (!logger.reportRepairs) {
logger.reportRepairs = defaultReportRepairs;
}
/**
* By default, logs a report suitable for display on the console.
*/
function defaultReportMax() {
if (ses.maxSeverity.level > ses.severities.SAFE.level) {
var maxClassification = ses.logger.classify(ses.maxSeverity);
logger[maxClassification.consoleLevel](
'Max Severity: ' + maxClassification.note);
}
}
if (!logger.reportMax) {
logger.reportMax = defaultReportMax;
}
function defaultReportDiagnosis(severity, status, problemList) {
var classification = ses.logger.classify(severity);
ses.logger[classification.consoleLevel](
problemList.length + ' ' + status);
}
if (!logger.reportDiagnosis) {
logger.reportDiagnosis = defaultReportDiagnosis;
}
ses.logger = logger;
})();
;
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Monkey patch almost ES5 platforms into a closer
* emulation of full <a href=
* "http://code.google.com/p/es-lab/wiki/SecureableES5">Secureable
* ES5</a>.
*
* <p>Assumes only ES3, but only proceeds to do useful repairs when
* the platform is close enough to ES5 to be worth attempting
* repairs. Compatible with almost-ES5, ES5, ES5-strict, and
* anticipated ES6.
*
* <p>Ignore the "...requires ___global_test_function___" below. We
* create it, use it, and delete it all within this module. But we
* need to lie to the linter since it can't tell.
*
* //provides ses.statuses, ses.ok, ses.is, ses.makeDelayedTamperProof
* //provides ses.makeCallerHarmless, ses.makeArgumentsHarmless
* //provides ses.severities, ses.maxSeverity, ses.updateMaxSeverity
* //provides ses.maxAcceptableSeverityName, ses.maxAcceptableSeverity
*
* @author Mark S. Miller
* @requires ___global_test_function___, ___global_valueOf_function___
* @requires JSON, navigator, this, eval, document
* @overrides ses, RegExp, WeakMap, Object, parseInt, repairES5Module
*/
var RegExp;
var ses;
/**
* <p>Qualifying platforms generally include all JavaScript platforms
* shown on <a href="http://kangax.github.com/es5-compat-table/"
* >ECMAScript 5 compatibility table</a> that implement {@code
* Object.getOwnPropertyNames}. At the time of this writing,
* qualifying browsers already include the latest released versions of
* Internet Explorer (9), Firefox (4), Chrome (11), and Safari
* (5.0.5), their corresponding standalone (e.g., server-side) JavaScript
* engines, Rhino 1.73, and BESEN.
*
* <p>On such not-quite-ES5 platforms, some elements of these
* emulations may lose SES safety, as enumerated in the comment on
* each kludge record in the {@code kludges} array below. The platform
* must at least provide {@code Object.getOwnPropertyNames}, because
* it cannot reasonably be emulated.
*
* <p>This file is useful by itself, as it has no dependencies on the
* rest of SES. It creates no new global bindings, but merely repairs
* standard globals or standard elements reachable from standard
* globals. If the future-standard {@code WeakMap} global is present,
* as it is currently on FF7.0a1, then it will repair it in place. The
* one non-standard element that this file uses is {@code console} if
* present, in order to report the repairs it found necessary, in
* which case we use its {@code log, info, warn}, and {@code error}
* methods. If {@code console.log} is absent, then this file performs
* its repairs silently.
*
* <p>Generally, this file should be run as the first script in a
* JavaScript context (i.e. a browser frame), as it relies on other
* primordial objects and methods not yet being perturbed.
*
* <p>TODO(erights): This file tries to protect itself from some
* post-initialization perturbation by stashing some of the
* primordials it needs for later use, but this attempt is currently
* incomplete. We need to revisit this when we support Confined-ES5,
* as a variant of SES in which the primordials are not frozen. See
* previous failed attempt at <a
* href="http://codereview.appspot.com/5278046/" >Speeds up
* WeakMap. Preparing to support unfrozen primordials.</a>. From
* analysis of this failed attempt, it seems that the only practical
* way to support CES is by use of two frames, where most of initSES
* runs in a SES frame, and so can avoid worrying about most of these
* perturbations.
*/
(function repairES5Module(global) {
"use strict";
/**
* The severity levels.
*
* <dl>
* <dt>SAFE</dt><dd>no problem.
* <dt>SAFE_SPEC_VIOLATION</dt>
* <dd>safe (in an integrity sense) even if unrepaired. May
* still lead to inappropriate failures.</dd>
* <dt>UNSAFE_SPEC_VIOLATION</dt>
* <dd>a safety issue only indirectly, in that this spec
* violation may lead to the corruption of assumptions made
* by other security critical or defensive code.</dd>
* <dt>NOT_OCAP_SAFE</dt>
* <dd>a violation of object-capability rules among objects
* within a coarse-grained unit of isolation.</dd>
* <dt>NOT_ISOLATED</dt>
* <dd>an inability to reliably sandbox even coarse-grain units
* of isolation.</dd>
* <dt>NEW_SYMPTOM</dt>
* <dd>some test failed in a way we did not expect.</dd>
* <dt>NOT_SUPPORTED</dt>
* <dd>this platform cannot even support SES development in an
* unsafe manner.</dd>
* </dl>
*/
ses.severities = {
SAFE: { level: 0, description: 'Safe' },
SAFE_SPEC_VIOLATION: { level: 1, description: 'Safe spec violation' },
UNSAFE_SPEC_VIOLATION: { level: 2, description: 'Unsafe spec violation' },
NOT_OCAP_SAFE: { level: 3, description: 'Not ocap safe' },
NOT_ISOLATED: { level: 4, description: 'Not isolated' },
NEW_SYMPTOM: { level: 5, description: 'New symptom' },
NOT_SUPPORTED: { level: 6, description: 'Not supported' }
};
/**
* Statuses.
*
* <dl>
* <dt>ALL_FINE</dt>
* <dd>test passed before and after.</dd>
* <dt>REPAIR_FAILED</dt>
* <dd>test failed before and after repair attempt.</dd>
* <dt>NOT_REPAIRED</dt>
* <dd>test failed before and after, with no repair to attempt.</dd>
* <dt>REPAIRED_UNSAFELY</dt>
* <dd>test failed before and passed after repair attempt, but
* the repair is known to be inadequate for security, so the
* real problem remains.</dd>
* <dt>REPAIRED</dt>
* <dd>test failed before and passed after repair attempt,
* repairing the problem (canRepair was true).</dd>
* <dt>ACCIDENTALLY_REPAIRED</dt>
* <dd>test failed before and passed after, despite no repair
* to attempt. (Must have been fixed by some other
* attempted repair.)</dd>
* <dt>BROKEN_BY_OTHER_ATTEMPTED_REPAIRS</dt>
* <dd>test passed before and failed after, indicating that
* some other attempted repair created the problem.</dd>
* </dl>
*/
ses.statuses = {
ALL_FINE: 'All fine',
REPAIR_FAILED: 'Repair failed',
NOT_REPAIRED: 'Not repaired',
REPAIRED_UNSAFELY: 'Repaired unsafely',
REPAIRED: 'Repaired',
ACCIDENTALLY_REPAIRED: 'Accidentally repaired',
BROKEN_BY_OTHER_ATTEMPTED_REPAIRS: 'Broken by other attempted repairs'
};
var logger = ses.logger;
/**
* As we start to repair, this will track the worst post-repair
* severity seen so far.
*/
ses.maxSeverity = ses.severities.SAFE;
/**
* {@code ses.maxAcceptableSeverity} is the max post-repair severity
* that is considered acceptable for proceeding with the SES
* verification-only strategy.
*
* <p>Although <code>repairES5.js</code> can be used standalone for
* partial ES5 repairs, its primary purpose is to repair as a first
* stage of <code>initSES.js</code> for purposes of supporting SES
* security. In support of that purpose, we initialize
* {@code ses.maxAcceptableSeverity} to the post-repair severity
* level at which we should report that we are unable to adequately
* support SES security. By default, this is set to
* {@code ses.severities.SAFE_SPEC_VIOLATION}, which is the maximum
* severity that we believe results in no loss of SES security.
*
* <p>If {@code ses.maxAcceptableSeverityName} is already set (to a
* severity property name of a severity below {@code
* ses.NOT_SUPPORTED}), then we use that setting to initialize
* {@code ses.maxAcceptableSeverity} instead. For example, if we are
* using SES only for isolation, then we could set it to
* 'NOT_OCAP_SAFE', in which case repairs that are inadequate for
* object-capability (ocap) safety would still be judged safe for
* our purposes.
*
* <p>As repairs proceed, they update {@code ses.maxSeverity} to
* track the worst case post-repair severity seen so far. When
* {@code ses.ok()} is called, it return whether {@code
* ses.maxSeverity} is still less than or equal to
* {@code ses.maxAcceptableSeverity}, indicating that this platform
* still seems adequate for supporting SES. In the Caja context, we
* have the choice of using SES on those platforms which we judge to
* be adequately repairable, or otherwise falling back to Caja's
* ES5/3 translator.
*/
if (ses.maxAcceptableSeverityName) {
var maxSev = ses.severities[ses.maxAcceptableSeverityName];
if (maxSev && typeof maxSev.level === 'number' &&
maxSev.level >= ses.severities.SAFE.level &&
maxSev.level < ses.severities.NOT_SUPPORTED.level) {
// do nothing
} else {
logger.error('Ignoring bad maxAcceptableSeverityName: ' +
ses.maxAcceptableSeverityName + '.') ;
ses.maxAcceptableSeverityName = 'SAFE_SPEC_VIOLATION';
}
} else {
ses.maxAcceptableSeverityName = 'SAFE_SPEC_VIOLATION';
}
ses.maxAcceptableSeverity = ses.severities[ses.maxAcceptableSeverityName];
/**
* Once this returns false, we can give up on the SES
* verification-only strategy and fall back to ES5/3 translation.
*/
ses.ok = function ok() {
return ses.maxSeverity.level <= ses.maxAcceptableSeverity.level;
};
/**
* Update the max based on the provided severity.
*
* <p>If the provided severity exceeds the max so far, update the
* max to match.
*/
ses.updateMaxSeverity = function updateMaxSeverity(severity) {
if (severity.level > ses.maxSeverity.level) {
ses.maxSeverity = severity;
}
};
//////// Prepare for "caller" and "argument" testing and repair /////////
/**
* Needs to work on ES3, since repairES5.js may be run on an ES3
* platform.
*/
function strictForEachFn(list, callback) {
for (var i = 0, len = list.length; i < len; i++) {
callback(list[i], i);
}
}
/**
* Needs to work on ES3, since repairES5.js may be run on an ES3
* platform.
*
* <p>Also serves as our representative strict function, by contrast
* to builtInMapMethod below, for testing what the "caller" and
* "arguments" properties of a strict function reveals.
*/
function strictMapFn(list, callback) {
var result = [];
for (var i = 0, len = list.length; i < len; i++) {
result.push(callback(list[i], i));
}
return result;
}
var objToString = Object.prototype.toString;
/**
* Sample map early, to obtain a representative built-in for testing.
*
* <p>There is no reliable test for whether a function is a
* built-in, and it is possible some of the tests below might
* replace the built-in Array.prototype.map, though currently none
* do. Since we <i>assume</i> (but with no reliable way to check)
* that repairES5.js runs in its JavaScript context before anything
* which might have replaced map, we sample it now. The map method
* is a particularly nice one to sample, since it can easily be used
* to test what the "caller" and "arguments" properties on a
* in-progress built-in method reveals.
*/
var builtInMapMethod = Array.prototype.map;
var builtInForEach = Array.prototype.forEach;
/**
* http://wiki.ecmascript.org/doku.php?id=harmony:egal
*/
var is = ses.is = Object.is || function(x, y) {
if (x === y) {
// 0 === -0, but they are not identical
return x !== 0 || 1 / x === 1 / y;
}
// NaN !== NaN, but they are identical.
// NaNs are the only non-reflexive value, i.e., if x !== x,
// then x is a NaN.
// isNaN is broken: it converts its argument to number, so
// isNaN("foo") => true
return x !== x && y !== y;
};
/**
* By the time this module exits, either this is repaired to be a
* function that is adequate to make the "caller" property of a
* strict or built-in function harmess, or this module has reported
* a failure to repair.
*
* <p>Start off with the optimistic assumption that nothing is
* needed to make the "caller" property of a strict or built-in
* function harmless. We are not concerned with the "caller"
* property of non-strict functions. It is not the responsibility of
* this module to actually make these "caller" properties
* harmless. Rather, this module only provides this function so
* clients such as startSES.js can use it to do so on the functions
* they whitelist.
*
* <p>If the "caller" property of strict functions are not already
* harmless, then this platform cannot be repaired to be
* SES-safe. The only reason why {@code makeCallerHarmless} must
* work on strict functions in addition to built-in is that some of
* the other repairs below will replace some of the built-ins with
* strict functions, so startSES.js will apply {@code
* makeCallerHarmless} blindly to both strict and built-in
* functions. {@code makeCallerHarmless} simply need not to complete
* without breaking anything when given a strict function argument.
*/
ses.makeCallerHarmless = function assumeCallerHarmless(func, path) {
return 'Apparently fine';
};
/**
* By the time this module exits, either this is repaired to be a
* function that is adequate to make the "arguments" property of a
* strict or built-in function harmess, or this module has reported
* a failure to repair.
*
* Exactly analogous to {@code makeCallerHarmless}, but for
* "arguments" rather than "caller".
*/
ses.makeArgumentsHarmless = function assumeArgumentsHarmless(func, path) {
return 'Apparently fine';
};
/**
* "makeTamperProof()" returns a "tamperProof(obj)" function that
* acts like "Object.freeze(obj)", except that, if obj is a
* <i>prototypical</i> object (defined below), it ensures that the
* effect of freezing properties of obj does not suppress the
* ability to override these properties on derived objects by simple
* assignment.
*
* <p>Because of lack of sufficient foresight at the time, ES5
* unifortunately specified that a simple assignment to a
* non-existent property must fail if it would override a
* non-writable data property of the same name. (In retrospect, this
* was a mistake, but it is now too late and we must live with the
* consequences.) As a result, simply freezing an object to make it
* tamper proof has the unfortunate side effect of breaking
* previously correct code that is considered to have followed JS
* best practices, of this previous code used assignment to
* override.
*
* <p>To work around this mistake, tamperProof(obj) detects if obj
* is <i>prototypical</i>, i.e., is an object whose own
* "constructor" is a function whose "prototype" is this obj. If so,
* then when tamper proofing it, prior to freezing, replace all its
* configurable own data properties with accessor properties which
* simulate what we should have specified -- that assignments to
* derived objects succeed if otherwise possible.
*
* <p>Some platforms (Chrome and Safari as of this writing)
* implement the assignment semantics ES5 should have specified
* rather than what it did specify.
* "test_ASSIGN_CAN_OVERRIDE_FROZEN()" below tests whether we are on
* such a platform. If so, "repair_ASSIGN_CAN_OVERRIDE_FROZEN()"
* replaces "makeTamperProof" with a function that simply returns
* "Object.freeze", since the complex workaround here is not needed
* on those platforms.
*
* <p>"makeTamperProof" should only be called after the trusted
* initialization has done all the monkey patching that it is going
* to do on the Object.* methods, but before any untrusted code runs
* in this context.
*/
var makeTamperProof = function defaultMakeTamperProof() {
// Sample these after all trusted monkey patching initialization
// but before any untrusted code runs in this frame.
var gopd = Object.getOwnPropertyDescriptor;
var gopn = Object.getOwnPropertyNames;
var getProtoOf = Object.getPrototypeOf;
var freeze = Object.freeze;
var isFrozen = Object.isFrozen;
var defProp = Object.defineProperty;
function tamperProof(obj) {
if (obj !== Object(obj)) { return obj; }
var func;
if (typeof obj === 'object' &&
!!gopd(obj, 'constructor') &&
typeof (func = obj.constructor) === 'function' &&
func.prototype === obj &&
!isFrozen(obj)) {
strictForEachFn(gopn(obj), function(name) {
var value;
function getter() {
if (obj === this) { return value; }
if (this === void 0 || this === null) { return void 0; }
var thisObj = Object(this);
if (!!gopd(thisObj, name)) { return this[name]; }
// TODO(erights): If we can reliably uncurryThis() in
// repairES5.js, the next line should be:
// return callFn(getter, getProtoOf(thisObj));
return getter.call(getProtoOf(thisObj));
}
function setter(newValue) {
if (obj === this) {
throw new TypeError('Cannot set virtually frozen property: ' +
name);
}
if (!!gopd(this, name)) {
this[name] = newValue;
}
// TODO(erights): Do all the inherited property checks
defProp(this, name, {
value: newValue,
writable: true,
enumerable: true,
configurable: true
});
}
var desc = gopd(obj, name);
if (desc.configurable && 'value' in desc) {
value = desc.value;
getter.prototype = null;
setter.prototype = null;
defProp(obj, name, {
get: getter,
set: setter,
// We should be able to omit the enumerable line, since it
// should default to its existing setting.
enumerable: desc.enumerable,
configurable: false
});
}
});
}
return freeze(obj);
}
return tamperProof;
};
var needToTamperProof = [];
/**
* Various repairs may expose non-standard objects that are not
* reachable from startSES's root, and therefore not freezable by
* startSES's normal whitelist traversal. However, freezing these
* during repairES5.js may be too early, as it is before WeakMap.js
* has had a chance to monkey patch Object.freeze if necessary, in
* order to install hidden properties for its own use before the
* object becomes non-extensible.
*/
function rememberToTamperProof(obj) {
needToTamperProof.push(obj);
}
/**
* Makes and returns a tamperProof(obj) function, and uses it to
* tamper proof all objects whose tamper proofing had been delayed.
*
* <p>"makeDelayedTamperProof()" must only be called once.
*/
ses.makeDelayedTamperProof = function makeDelayedTamperProof() {
var tamperProof = makeTamperProof();
strictForEachFn(needToTamperProof, tamperProof);
needToTamperProof = void 0;
return tamperProof;
};
/**
* Where the "that" parameter represents a "this" that should have
* been bound to "undefined" but may be bound to a global or
* globaloid object.
*
* <p>The "desc" parameter is a string to describe the "that" if it
* is something unexpected.
*/
function testGlobalLeak(desc, that) {
if (that === void 0) { return false; }
if (that === global) { return true; }
if ({}.toString.call(that) === '[object Window]') { return true; }
return desc + ' leaked as: ' + that;
}
////////////////////// Tests /////////////////////
//
// Each test is a function of no arguments that should not leave any
// significant side effects, which tests for the presence of a
// problem. It returns either
// <ul>
// <li>false, meaning that the problem does not seem to be present.
// <li>true, meaning that the problem is present in a form that we expect.
// <li>a non-empty string, meaning that there seems to be a related
// problem, but we're seeing a symptom different than what we
// expect. The string should describe the new symptom. It must
// be non-empty so that it is truthy.
// </ul>
// All the tests are run first to determine which corresponding
// repairs to attempt. Then these repairs are run. Then all the
// tests are rerun to see how they were effected by these repair
// attempts. Finally, we report what happened.
/**
* If {@code Object.getOwnPropertyNames} is missing, we consider
* this to be an ES3 browser which is unsuitable for attempting to
* run SES.
*
* <p>If {@code Object.getOwnPropertyNames} is missing, there is no
* way to emulate it.
*/
function test_MISSING_GETOWNPROPNAMES() {
return !('getOwnPropertyNames' in Object);
}
/**
* Detects https://bugs.webkit.org/show_bug.cgi?id=64250
*
* <p>No workaround attempted. Just reporting that this platform is
* not SES-safe.
*/
function test_GLOBAL_LEAKS_FROM_GLOBAL_FUNCTION_CALLS() {
global.___global_test_function___ = function() { return this; };
var that = ___global_test_function___();
delete global.___global_test_function___;
return testGlobalLeak('Global func "this"', that);
}
/**
* Detects whether the most painful ES3 leak is still with us.
*/
function test_GLOBAL_LEAKS_FROM_ANON_FUNCTION_CALLS() {
var that = (function(){ return this; })();
return testGlobalLeak('Anon func "this"', that);
}
var strictThis = this;
/**
*
*/
function test_GLOBAL_LEAKS_FROM_STRICT_THIS() {
return testGlobalLeak('Strict "this"', strictThis);
}
/**
* Detects
* https://bugs.webkit.org/show_bug.cgi?id=51097
* https://bugs.webkit.org/show_bug.cgi?id=58338
* http://code.google.com/p/v8/issues/detail?id=1437
*
* <p>No workaround attempted. Just reporting that this platform is
* not SES-safe.
*/
function test_GLOBAL_LEAKS_FROM_BUILTINS() {
var v = {}.valueOf;
var that = 'dummy';
try {
that = v();
} catch (err) {
if (err instanceof TypeError) { return false; }
return 'valueOf() threw: ' + err;
}
if (that === void 0) {
// Should report as a safe spec violation
return false;
}
return testGlobalLeak('valueOf()', that);
}
/**
*
*/
function test_GLOBAL_LEAKS_FROM_GLOBALLY_CALLED_BUILTINS() {
global.___global_valueOf_function___ = {}.valueOf;
var that = 'dummy';
try {
that = ___global_valueOf_function___();
} catch (err) {
if (err instanceof TypeError) { return false; }
return 'valueOf() threw: ' + err;
} finally {
delete global.___global_valueOf_function___;
}
if (that === void 0) {
// Should report as a safe spec violation
return false;
}
return testGlobalLeak('Global valueOf()', that);
}
/**
* Detects https://bugs.webkit.org/show_bug.cgi?id=55736
*
* <p>As of this writing, the only major browser that does implement
* Object.getOwnPropertyNames but not Object.freeze etc is the
* released Safari 5 (JavaScriptCore). The Safari beta 5.0.4
* (5533.20.27, r84622) already does implement freeze, which is why
* this WebKit bug is listed as closed. When the released Safari has
* this fix, we can retire this kludge.
*
* <p>This kludge is <b>not</b> safety preserving. The emulations it
* installs if needed do not actually provide the safety that the
* rest of SES relies on.
*/
function test_MISSING_FREEZE_ETC() {
return !('freeze' in Object);
}
/**
* Detects http://code.google.com/p/v8/issues/detail?id=1530
*
* <p>Detects whether the value of a function's "prototype" property
* as seen by normal object operations might deviate from the value
* as seem by the reflective {@code Object.getOwnPropertyDescriptor}
*/
function test_FUNCTION_PROTOTYPE_DESCRIPTOR_LIES() {
function foo() {}
Object.defineProperty(foo, 'prototype', { value: {} });
return foo.prototype !==
Object.getOwnPropertyDescriptor(foo, 'prototype').value;
}
/**
* Detects https://bugs.webkit.org/show_bug.cgi?id=55537
*
* This bug is fixed on the latest Safari beta 5.0.5 (5533.21.1,
* r88603). When the released Safari has this fix, we can retire
* this kludge.
*
* <p>This kludge is safety preserving.
*/
function test_MISSING_CALLEE_DESCRIPTOR() {
function foo(){}
if (Object.getOwnPropertyNames(foo).indexOf('callee') < 0) { return false; }
if (foo.hasOwnProperty('callee')) {
return 'Empty strict function has own callee';
}
return true;
}
/**
* A strict delete should either succeed, returning true, or it
* should fail by throwing a TypeError. Under no circumstances
* should a strict delete return false.
*
* <p>This case occurs on IE10preview2.
*/
function test_STRICT_DELETE_RETURNS_FALSE() {
if (!RegExp.hasOwnProperty('rightContext')) { return false; }
var deleted;
try {
deleted = delete RegExp.rightContext;
} catch (err) {
if (err instanceof TypeError) { return false; }
return 'Deletion failed with: ' + err;
}
if (deleted) { return false; }
return true;
}
/**
* Detects https://bugzilla.mozilla.org/show_bug.cgi?id=591846
* as applied to the RegExp constructor.
*
* <p>Note that Mozilla lists this bug as closed. But reading that
* bug thread clarifies that is partially because the code in {@code
* repair_REGEXP_CANT_BE_NEUTERED} enables us to work around the
* non-configurability of the RegExp statics.
*/
function test_REGEXP_CANT_BE_NEUTERED() {
if (!RegExp.hasOwnProperty('leftContext')) { return false; }
var deleted;
try {
deleted = delete RegExp.leftContext;
} catch (err) {
if (err instanceof TypeError) { return true; }
return 'Deletion failed with: ' + err;
}
if (!RegExp.hasOwnProperty('leftContext')) { return false; }
if (deleted) {
return 'Deletion of RegExp.leftContext did not succeed.';
} else {
// This case happens on IE10preview2, as demonstrated by
// test_STRICT_DELETE_RETURNS_FALSE.
return true;
}
}
/**
* Detects http://code.google.com/p/v8/issues/detail?id=1393
*
* <p>This kludge is safety preserving.
*/
function test_REGEXP_TEST_EXEC_UNSAFE() {
(/foo/).test('xfoox');
var match = new RegExp('(.|\r|\n)*','').exec()[0];
if (match === 'undefined') { return false; }
if (match === 'xfoox') { return true; }
return 'regExp.exec() does not match against "undefined".';
}
/**
* Detects https://bugs.webkit.org/show_bug.cgi?id=26382
*
* <p>As of this writing, the only major browser that does implement
* Object.getOwnPropertyNames but not Function.prototype.bind is
* Safari 5 (JavaScriptCore), including the current Safari beta
* 5.0.4 (5533.20.27, r84622).
*
* <p>This kludge is safety preserving. But see
* https://bugs.webkit.org/show_bug.cgi?id=26382#c25 for why this
* kludge cannot faithfully implement the specified semantics.
*
* <p>See also https://bugs.webkit.org/show_bug.cgi?id=42371
*/
function test_MISSING_BIND() {
return !('bind' in Function.prototype);
}