ses 0.18.7 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,409 @@
1
+ // Copyright (C) 2018 Agoric
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ // @ts-check
16
+
17
+ import { makeEnvironmentCaptor } from '@endo/env-options';
18
+ import {
19
+ FERAL_FUNCTION,
20
+ FERAL_EVAL,
21
+ TypeError,
22
+ arrayFilter,
23
+ globalThis,
24
+ is,
25
+ ownKeys,
26
+ stringSplit,
27
+ noEvalEvaluate,
28
+ getOwnPropertyNames,
29
+ } from './commons.js';
30
+ import { makeHardener } from './make-hardener.js';
31
+ import { makeIntrinsicsCollector } from './intrinsics.js';
32
+ import whitelistIntrinsics from './permits-intrinsics.js';
33
+ import tameFunctionConstructors from './tame-function-constructors.js';
34
+ import tameDateConstructor from './tame-date-constructor.js';
35
+ import tameMathObject from './tame-math-object.js';
36
+ import tameRegExpConstructor from './tame-regexp-constructor.js';
37
+ import enablePropertyOverrides from './enable-property-overrides.js';
38
+ import tameLocaleMethods from './tame-locale-methods.js';
39
+ import {
40
+ setGlobalObjectConstantProperties,
41
+ setGlobalObjectMutableProperties,
42
+ setGlobalObjectEvaluators,
43
+ } from './global-object.js';
44
+ import { makeSafeEvaluator } from './make-safe-evaluator.js';
45
+ import { initialGlobalPropertyNames } from './permits.js';
46
+ import { tameFunctionToString } from './tame-function-tostring.js';
47
+ import { tameDomains } from './tame-domains.js';
48
+
49
+ import { tameConsole } from './error/tame-console.js';
50
+ import tameErrorConstructor from './error/tame-error-constructor.js';
51
+ import { assert, makeAssert } from './error/assert.js';
52
+ import { getAnonymousIntrinsics } from './get-anonymous-intrinsics.js';
53
+ import { makeCompartmentConstructor } from './compartment.js';
54
+ import { tameHarden } from './tame-harden.js';
55
+ import { tameSymbolConstructor } from './tame-symbol-constructor.js';
56
+
57
+ /** @typedef {import('../types.js').LockdownOptions} LockdownOptions */
58
+
59
+ const { Fail, details: d, quote: q } = assert;
60
+
61
+ /** @type {Error=} */
62
+ let priorRepairIntrinsics;
63
+
64
+ /** @type {Error=} */
65
+ let priorHardenIntrinsics;
66
+
67
+ // Build a harden() with an empty fringe.
68
+ // Gate it on lockdown.
69
+ /**
70
+ * @template T
71
+ * @param {T} ref
72
+ * @returns {T}
73
+ */
74
+ const safeHarden = makeHardener();
75
+
76
+ /**
77
+ * @callback Transform
78
+ * @param {string} source
79
+ * @returns {string}
80
+ */
81
+
82
+ /**
83
+ * @callback CompartmentConstructor
84
+ * @param {object} endowments
85
+ * @param {object} moduleMap
86
+ * @param {object} [options]
87
+ * @param {Array<Transform>} [options.transforms]
88
+ * @param {Array<Transform>} [options.__shimTransforms__]
89
+ */
90
+
91
+ // TODO https://github.com/endojs/endo/issues/814
92
+ // Lockdown currently allows multiple calls provided that the specified options
93
+ // of every call agree. With experience, we have observed that lockdown should
94
+ // only ever need to be called once and that simplifying lockdown will improve
95
+ // the quality of audits.
96
+
97
+ const assertDirectEvalAvailable = () => {
98
+ let allowed = false;
99
+ try {
100
+ allowed = FERAL_FUNCTION(
101
+ 'eval',
102
+ 'SES_changed',
103
+ `\
104
+ eval("SES_changed = true");
105
+ return SES_changed;
106
+ `,
107
+ )(FERAL_EVAL, false);
108
+ // If we get here and SES_changed stayed false, that means the eval was sloppy
109
+ // and indirect, which generally creates a new global.
110
+ // We are going to throw an exception for failing to initialize SES, but
111
+ // good neighbors clean up.
112
+ if (!allowed) {
113
+ delete globalThis.SES_changed;
114
+ }
115
+ } catch (_error) {
116
+ // We reach here if eval is outright forbidden by a Content Security Policy.
117
+ // We allow this for SES usage that delegates the responsibility to isolate
118
+ // guest code to production code generation.
119
+ allowed = true;
120
+ }
121
+ if (!allowed) {
122
+ // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_DIRECT_EVAL.md
123
+ throw TypeError(
124
+ `SES cannot initialize unless 'eval' is the original intrinsic 'eval', suitable for direct-eval (dynamically scoped eval) (SES_DIRECT_EVAL)`,
125
+ );
126
+ }
127
+ };
128
+
129
+ /**
130
+ * @param {LockdownOptions} [options]
131
+ */
132
+ export const repairIntrinsics = (options = {}) => {
133
+ // First time, absent options default to 'safe'.
134
+ // Subsequent times, absent options default to first options.
135
+ // Thus, all present options must agree with first options.
136
+ // Reconstructing `option` here also ensures that it is a well
137
+ // behaved record, with only own data properties.
138
+ //
139
+ // The `overrideTaming` is not a safety issue. Rather it is a tradeoff
140
+ // between code compatibility, which is better with the `'moderate'`
141
+ // setting, and tool compatibility, which is better with the `'min'`
142
+ // setting. See
143
+ // https://github.com/Agoric/SES-shim/blob/master/packages/ses/README.md#enabling-override-by-assignment)
144
+ // for an explanation of when to use which.
145
+ //
146
+ // The `stackFiltering` is not a safety issue. Rather it is a tradeoff
147
+ // between relevance and completeness of the stack frames shown on the
148
+ // console. Setting`stackFiltering` to `'verbose'` applies no filters, providing
149
+ // the raw stack frames that can be quite versbose. Setting
150
+ // `stackFrameFiltering` to`'concise'` limits the display to the stack frame
151
+ // information most likely to be relevant, eliminating distracting frames
152
+ // such as those from the infrastructure. However, the bug you're trying to
153
+ // track down might be in the infrastrure, in which case the `'verbose'` setting
154
+ // is useful. See
155
+ // [`stackFiltering` options](https://github.com/Agoric/SES-shim/blob/master/packages/ses/docs/lockdown.md#stackfiltering-options)
156
+ // for an explanation.
157
+
158
+ const { getEnvironmentOption: getenv } = makeEnvironmentCaptor(globalThis);
159
+
160
+ const {
161
+ errorTaming = getenv('LOCKDOWN_ERROR_TAMING', 'safe'),
162
+ errorTrapping = /** @type {"platform" | "none" | "report" | "abort" | "exit" | undefined} */ (
163
+ getenv('LOCKDOWN_ERROR_TRAPPING', 'platform')
164
+ ),
165
+ unhandledRejectionTrapping = /** @type {"none" | "report" | undefined} */ (
166
+ getenv('LOCKDOWN_UNHANDLED_REJECTION_TRAPPING', 'report')
167
+ ),
168
+ regExpTaming = getenv('LOCKDOWN_REGEXP_TAMING', 'safe'),
169
+ localeTaming = getenv('LOCKDOWN_LOCALE_TAMING', 'safe'),
170
+
171
+ consoleTaming = /** @type {'unsafe' | 'safe' | undefined} */ (
172
+ getenv('LOCKDOWN_CONSOLE_TAMING', 'safe')
173
+ ),
174
+ overrideTaming = getenv('LOCKDOWN_OVERRIDE_TAMING', 'moderate'),
175
+ stackFiltering = getenv('LOCKDOWN_STACK_FILTERING', 'concise'),
176
+ domainTaming = getenv('LOCKDOWN_DOMAIN_TAMING', 'safe'),
177
+ evalTaming = getenv('LOCKDOWN_EVAL_TAMING', 'safeEval'),
178
+ overrideDebug = arrayFilter(
179
+ stringSplit(getenv('LOCKDOWN_OVERRIDE_DEBUG', ''), ','),
180
+ /** @param {string} debugName */
181
+ debugName => debugName !== '',
182
+ ),
183
+ __hardenTaming__ = getenv('LOCKDOWN_HARDEN_TAMING', 'safe'),
184
+ dateTaming = 'safe', // deprecated
185
+ mathTaming = 'safe', // deprecated
186
+ ...extraOptions
187
+ } = options;
188
+
189
+ evalTaming === 'unsafeEval' ||
190
+ evalTaming === 'safeEval' ||
191
+ evalTaming === 'noEval' ||
192
+ Fail`lockdown(): non supported option evalTaming: ${q(evalTaming)}`;
193
+
194
+ // Assert that only supported options were passed.
195
+ // Use Reflect.ownKeys to reject symbol-named properties as well.
196
+ const extraOptionsNames = ownKeys(extraOptions);
197
+ extraOptionsNames.length === 0 ||
198
+ Fail`lockdown(): non supported option ${q(extraOptionsNames)}`;
199
+
200
+ priorRepairIntrinsics === undefined ||
201
+ // eslint-disable-next-line @endo/no-polymorphic-call
202
+ assert.fail(
203
+ d`Already locked down at ${priorRepairIntrinsics} (SES_ALREADY_LOCKED_DOWN)`,
204
+ TypeError,
205
+ );
206
+ // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_ALREADY_LOCKED_DOWN.md
207
+ priorRepairIntrinsics = TypeError('Prior lockdown (SES_ALREADY_LOCKED_DOWN)');
208
+ // Tease V8 to generate the stack string and release the closures the stack
209
+ // trace retained:
210
+ priorRepairIntrinsics.stack;
211
+
212
+ assertDirectEvalAvailable();
213
+
214
+ /**
215
+ * Because of packagers and bundlers, etc, multiple invocations of lockdown
216
+ * might happen in separate instantiations of the source of this module.
217
+ * In that case, each one sees its own `firstOptions` variable, so the test
218
+ * above will not detect that lockdown has already happened. We
219
+ * unreliably test some telltale signs that lockdown has run, to avoid
220
+ * trying to lock down a locked down environment. Although the test is
221
+ * unreliable, this is consistent with the SES threat model. SES provides
222
+ * security only if it runs first in a given realm, or if everything that
223
+ * runs before it is SES-aware and cooperative. Neither SES nor anything
224
+ * can protect itself from corrupting code that runs first. For these
225
+ * purposes, code that turns a realm into something that passes these
226
+ * tests without actually locking down counts as corrupting code.
227
+ *
228
+ * The specifics of what this tests for may change over time, but it
229
+ * should be consistent with any setting of the lockdown options.
230
+ */
231
+ const seemsToBeLockedDown = () => {
232
+ return (
233
+ globalThis.Function.prototype.constructor !== globalThis.Function &&
234
+ // @ts-ignore harden is absent on globalThis type def.
235
+ typeof globalThis.harden === 'function' &&
236
+ // @ts-ignore lockdown is absent on globalThis type def.
237
+ typeof globalThis.lockdown === 'function' &&
238
+ globalThis.Date.prototype.constructor !== globalThis.Date &&
239
+ typeof globalThis.Date.now === 'function' &&
240
+ // @ts-ignore does not recognize that Date constructor is a special
241
+ // Function.
242
+ // eslint-disable-next-line @endo/no-polymorphic-call
243
+ is(globalThis.Date.prototype.constructor.now(), NaN)
244
+ );
245
+ };
246
+
247
+ if (seemsToBeLockedDown()) {
248
+ // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_MULTIPLE_INSTANCES.md
249
+ throw TypeError(
250
+ `Already locked down but not by this SES instance (SES_MULTIPLE_INSTANCES)`,
251
+ );
252
+ }
253
+
254
+ /**
255
+ * 1. TAME powers & gather intrinsics first.
256
+ */
257
+
258
+ tameDomains(domainTaming);
259
+
260
+ // Replace Function.prototype.toString with one that recognizes
261
+ // shimmed functions as honorary native functions.
262
+ const markVirtualizedNativeFunction = tameFunctionToString();
263
+
264
+ const { addIntrinsics, completePrototypes, finalIntrinsics } =
265
+ makeIntrinsicsCollector();
266
+
267
+ const tamedHarden = tameHarden(safeHarden, __hardenTaming__);
268
+ addIntrinsics({ harden: tamedHarden });
269
+
270
+ addIntrinsics(tameFunctionConstructors());
271
+
272
+ addIntrinsics(tameDateConstructor(dateTaming));
273
+ addIntrinsics(tameErrorConstructor(errorTaming, stackFiltering));
274
+ addIntrinsics(tameMathObject(mathTaming));
275
+ addIntrinsics(tameRegExpConstructor(regExpTaming));
276
+ addIntrinsics(tameSymbolConstructor());
277
+
278
+ addIntrinsics(getAnonymousIntrinsics());
279
+
280
+ completePrototypes();
281
+
282
+ const intrinsics = finalIntrinsics();
283
+
284
+ /**
285
+ * Wrap console unless suppressed.
286
+ * At the moment, the console is considered a host power in the start
287
+ * compartment, and not a primordial. Hence it is absent from the whilelist
288
+ * and bypasses the intrinsicsCollector.
289
+ *
290
+ * @type {((error: any) => string | undefined) | undefined}
291
+ */
292
+ let optGetStackString;
293
+ if (errorTaming !== 'unsafe') {
294
+ optGetStackString = intrinsics['%InitialGetStackString%'];
295
+ }
296
+ const consoleRecord = tameConsole(
297
+ consoleTaming,
298
+ errorTrapping,
299
+ unhandledRejectionTrapping,
300
+ optGetStackString,
301
+ );
302
+ globalThis.console = /** @type {Console} */ (consoleRecord.console);
303
+
304
+ // @ts-ignore assert is absent on globalThis type def.
305
+ if (errorTaming === 'unsafe' && globalThis.assert === assert) {
306
+ // If errorTaming is 'unsafe' we replace the global assert with
307
+ // one whose `details` template literal tag does not redact
308
+ // unmarked substitution values. IOW, it blabs information that
309
+ // was supposed to be secret from callers, as an aid to debugging
310
+ // at a further cost in safety.
311
+ // @ts-ignore assert is absent on globalThis type def.
312
+ globalThis.assert = makeAssert(undefined, true);
313
+ }
314
+
315
+ // Replace *Locale* methods with their non-locale equivalents
316
+ tameLocaleMethods(intrinsics, localeTaming);
317
+
318
+ /**
319
+ * 2. WHITELIST to standardize the environment.
320
+ */
321
+
322
+ // Remove non-standard properties.
323
+ // All remaining function encountered during whitelisting are
324
+ // branded as honorary native functions.
325
+ whitelistIntrinsics(intrinsics, markVirtualizedNativeFunction);
326
+
327
+ // Initialize the powerful initial global, i.e., the global of the
328
+ // start compartment, from the intrinsics.
329
+
330
+ setGlobalObjectConstantProperties(globalThis);
331
+
332
+ setGlobalObjectMutableProperties(globalThis, {
333
+ intrinsics,
334
+ newGlobalPropertyNames: initialGlobalPropertyNames,
335
+ makeCompartmentConstructor,
336
+ markVirtualizedNativeFunction,
337
+ });
338
+
339
+ if (evalTaming === 'noEval') {
340
+ setGlobalObjectEvaluators(
341
+ globalThis,
342
+ noEvalEvaluate,
343
+ markVirtualizedNativeFunction,
344
+ );
345
+ } else if (evalTaming === 'safeEval') {
346
+ const { safeEvaluate } = makeSafeEvaluator({ globalObject: globalThis });
347
+ setGlobalObjectEvaluators(
348
+ globalThis,
349
+ safeEvaluate,
350
+ markVirtualizedNativeFunction,
351
+ );
352
+ } else if (evalTaming === 'unsafeEval') {
353
+ // Leave eval function and Function constructor of the initial compartment in-tact.
354
+ // Other compartments will not have access to these evaluators unless a guest program
355
+ // escapes containment.
356
+ }
357
+
358
+ /**
359
+ * 3. HARDEN to share the intrinsics.
360
+ *
361
+ * We define hardenIntrinsics here so that options are in scope, but return
362
+ * it to the caller because we intend to eventually allow vetted shims to run
363
+ * between repairs and the hardening of intrinsics and so we can benchmark
364
+ * repair separately from hardening.
365
+ */
366
+
367
+ const hardenIntrinsics = () => {
368
+ priorHardenIntrinsics === undefined ||
369
+ // eslint-disable-next-line @endo/no-polymorphic-call
370
+ assert.fail(
371
+ d`Already locked down at ${priorHardenIntrinsics} (SES_ALREADY_LOCKED_DOWN)`,
372
+ TypeError,
373
+ );
374
+ // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_ALREADY_LOCKED_DOWN.md
375
+ priorHardenIntrinsics = TypeError(
376
+ 'Prior lockdown (SES_ALREADY_LOCKED_DOWN)',
377
+ );
378
+ // Tease V8 to generate the stack string and release the closures the stack
379
+ // trace retained:
380
+ priorHardenIntrinsics.stack;
381
+
382
+ // Circumvent the override mistake.
383
+ // TODO consider moving this to the end of the repair phase, and
384
+ // therefore before vetted shims rather than afterwards. It is not
385
+ // clear yet which is better.
386
+ // @ts-ignore enablePropertyOverrides does its own input validation
387
+ enablePropertyOverrides(intrinsics, overrideTaming, overrideDebug);
388
+
389
+ // Finally register and optionally freeze all the intrinsics. This
390
+ // must be the operation that modifies the intrinsics.
391
+ tamedHarden(intrinsics);
392
+
393
+ // Harden evaluators
394
+ tamedHarden(globalThis.Function);
395
+ tamedHarden(globalThis.eval);
396
+ // @ts-ignore Compartment does exist on globalThis
397
+ tamedHarden(globalThis.Compartment);
398
+
399
+ // Harden Symbol and properties for initialGlobalPropertyNames in the host realm
400
+ tamedHarden(globalThis.Symbol);
401
+ for (const prop of getOwnPropertyNames(initialGlobalPropertyNames)) {
402
+ tamedHarden(globalThis[prop]);
403
+ }
404
+
405
+ return tamedHarden;
406
+ };
407
+
408
+ return hardenIntrinsics;
409
+ };
@@ -19,7 +19,7 @@ const { Fail } = assert;
19
19
  * @param {object} options
20
20
  * @param {object} options.globalObject
21
21
  * @param {object} [options.moduleLexicals]
22
- * @param {Array<import('./lockdown-shim.js').Transform>} [options.globalTransforms]
22
+ * @param {Array<import('./lockdown.js').Transform>} [options.globalTransforms]
23
23
  * @param {boolean} [options.sloppyGlobalsMode]
24
24
  */
25
25
  export const makeSafeEvaluator = ({
@@ -54,7 +54,7 @@ export const makeSafeEvaluator = ({
54
54
  /**
55
55
  * @param {string} source
56
56
  * @param {object} [options]
57
- * @param {Array<import('./lockdown-shim.js').Transform>} [options.localTransforms]
57
+ * @param {Array<import('./lockdown.js').Transform>} [options.localTransforms]
58
58
  */
59
59
  const safeEvaluate = (source, options) => {
60
60
  const { localTransforms = [] } = options || {};
package/src/permits.js CHANGED
@@ -326,7 +326,7 @@ function TypedArrayPrototype(constructor) {
326
326
  }
327
327
 
328
328
  // Without Math.random
329
- const SharedMath = {
329
+ const CommonMath = {
330
330
  E: 'number',
331
331
  LN10: 'number',
332
332
  LN2: 'number',
@@ -442,7 +442,7 @@ export const permitted = {
442
442
  setPrototypeOf: fn,
443
443
  values: fn,
444
444
  // https://github.com/tc39/proposal-array-grouping
445
- groupBy: 'boolean',
445
+ groupBy: fn,
446
446
  },
447
447
 
448
448
  '%ObjectPrototype%': {
@@ -649,12 +649,16 @@ export const permitted = {
649
649
  },
650
650
 
651
651
  '%InitialMath%': {
652
- ...SharedMath,
653
- // random is standard but omitted from SharedMath
652
+ ...CommonMath,
653
+ // `%InitialMath%.random()` has the standard unsafe behavior
654
654
  random: fn,
655
655
  },
656
656
 
657
- '%SharedMath%': SharedMath,
657
+ '%SharedMath%': {
658
+ ...CommonMath,
659
+ // `%SharedMath%.random()` is tamed to always throw
660
+ random: fn,
661
+ },
658
662
 
659
663
  '%InitialDate%': {
660
664
  // Properties of the Date Constructor
@@ -668,6 +672,7 @@ export const permitted = {
668
672
  '%SharedDate%': {
669
673
  // Properties of the Date Constructor
670
674
  '[[Proto]]': '%FunctionPrototype%',
675
+ // `%SharedDate%.now()` is tamed to always throw
671
676
  now: fn,
672
677
  parse: fn,
673
678
  prototype: '%DatePrototype%',
@@ -1069,6 +1074,8 @@ export const permitted = {
1069
1074
  '[[Proto]]': '%FunctionPrototype%',
1070
1075
  '@@species': getter,
1071
1076
  prototype: '%MapPrototype%',
1077
+ // https://github.com/tc39/proposal-array-grouping
1078
+ groupBy: fn,
1072
1079
  },
1073
1080
 
1074
1081
  '%MapPrototype%': {
@@ -1407,6 +1414,8 @@ export const permitted = {
1407
1414
  race: fn,
1408
1415
  reject: fn,
1409
1416
  resolve: fn,
1417
+ // https://github.com/tc39/proposal-promise-with-resolvers
1418
+ withResolvers: fn,
1410
1419
  '@@species': getter,
1411
1420
  },
1412
1421
 
@@ -17,26 +17,38 @@ export default function tameDateConstructor(dateTaming = 'safe') {
17
17
 
18
18
  // Use concise methods to obtain named functions without constructors.
19
19
  const tamedMethods = {
20
+ /**
21
+ * `%SharedDate%.now()` throw a `TypeError` starting with "secure mode".
22
+ * See https://github.com/endojs/endo/issues/910#issuecomment-1581855420
23
+ */
20
24
  now() {
21
- return NaN;
25
+ throw TypeError('secure mode Calling %SharedDate%.now() throws');
22
26
  },
23
27
  };
24
28
 
25
- // Tame the Date constructor.
26
- // Common behavior
27
- // * new Date(x) coerces x into a number and then returns a Date
28
- // for that number of millis since the epoch
29
- // * new Date(NaN) returns a Date object which stringifies to
30
- // 'Invalid Date'
31
- // * new Date(undefined) returns a Date object which stringifies to
32
- // 'Invalid Date'
33
- // OriginalDate (normal standard) behavior
34
- // * Date(anything) gives a string with the current time
35
- // * new Date() returns the current time, as a Date object
36
- // SharedDate behavior
37
- // * Date(anything) returned 'Invalid Date'
38
- // * new Date() returns a Date object which stringifies to
39
- // 'Invalid Date'
29
+ /**
30
+ * Tame the Date constructor.
31
+ * See https://github.com/endojs/endo/issues/910#issuecomment-1581855420
32
+ *
33
+ * Common behavior
34
+ * * `new Date(x)` coerces x into a number and then returns a Date
35
+ * for that number of millis since the epoch
36
+ * * `new Date(NaN)` returns a Date object which stringifies to
37
+ * 'Invalid Date'
38
+ * * `new Date(undefined)` returns a Date object which stringifies to
39
+ * 'Invalid Date'
40
+ *
41
+ * OriginalDate (normal standard) behavior preserved by
42
+ * `%InitialDate%`.
43
+ * * `Date(anything)` gives a string with the current time
44
+ * * `new Date()` returns the current time, as a Date object
45
+ *
46
+ * `%SharedDate%` behavior
47
+ * * `Date(anything)` throws a TypeError starting with "secure mode"
48
+ * * `new Date()` throws a TypeError starting with "secure mode"
49
+ *
50
+ * @param {{powers?: string}} [opts]
51
+ */
40
52
  const makeDateConstructor = ({ powers = 'none' } = {}) => {
41
53
  let ResultDate;
42
54
  if (powers === 'original') {
@@ -51,10 +63,14 @@ export default function tameDateConstructor(dateTaming = 'safe') {
51
63
  // eslint-disable-next-line no-shadow
52
64
  ResultDate = function Date(...rest) {
53
65
  if (new.target === undefined) {
54
- return 'Invalid Date';
66
+ throw TypeError(
67
+ 'secure mode Calling %SharedDate% constructor as a function throws',
68
+ );
55
69
  }
56
70
  if (rest.length === 0) {
57
- rest = [NaN];
71
+ throw TypeError(
72
+ 'secure mode Calling new %SharedDate%() with no arguments throws',
73
+ );
58
74
  }
59
75
  return construct(OriginalDate, rest, new.target);
60
76
  };
@@ -69,13 +85,13 @@ export default function tameDateConstructor(dateTaming = 'safe') {
69
85
  configurable: false,
70
86
  },
71
87
  parse: {
72
- value: Date.parse,
88
+ value: OriginalDate.parse,
73
89
  writable: true,
74
90
  enumerable: false,
75
91
  configurable: true,
76
92
  },
77
93
  UTC: {
78
- value: Date.UTC,
94
+ value: OriginalDate.UTC,
79
95
  writable: true,
80
96
  enumerable: false,
81
97
  configurable: true,
@@ -88,7 +104,7 @@ export default function tameDateConstructor(dateTaming = 'safe') {
88
104
 
89
105
  defineProperties(InitialDate, {
90
106
  now: {
91
- value: Date.now,
107
+ value: OriginalDate.now,
92
108
  writable: true,
93
109
  enumerable: false,
94
110
  configurable: true,
@@ -16,7 +16,26 @@ export default function tameMathObject(mathTaming = 'safe') {
16
16
  const { random: _, ...otherDescriptors } =
17
17
  getOwnPropertyDescriptors(originalMath);
18
18
 
19
- const sharedMath = create(objectPrototype, otherDescriptors);
19
+ // Use concise methods to obtain named functions without constructors.
20
+ const tamedMethods = {
21
+ /**
22
+ * `%SharedMath%.random()` throws a TypeError starting with "secure mode".
23
+ * See https://github.com/endojs/endo/issues/910#issuecomment-1581855420
24
+ */
25
+ random() {
26
+ throw TypeError('secure mode %SharedMath%.random() throws');
27
+ },
28
+ };
29
+
30
+ const sharedMath = create(objectPrototype, {
31
+ ...otherDescriptors,
32
+ random: {
33
+ value: tamedMethods.random,
34
+ writable: true,
35
+ enumerable: false,
36
+ configurable: true,
37
+ },
38
+ });
20
39
 
21
40
  return {
22
41
  '%InitialMath%': initialMath,