ses 0.14.2 → 0.15.1

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.
Files changed (50) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/NEWS.md +60 -1
  3. package/README.md +0 -1
  4. package/dist/lockdown.cjs +1769 -992
  5. package/dist/lockdown.mjs +1769 -992
  6. package/dist/lockdown.umd.js +1769 -992
  7. package/dist/lockdown.umd.min.js +1 -1
  8. package/dist/ses.cjs +1769 -992
  9. package/dist/ses.mjs +1769 -992
  10. package/dist/ses.umd.js +1769 -992
  11. package/dist/ses.umd.min.js +1 -1
  12. package/index.d.ts +2 -1
  13. package/index.js +6 -13
  14. package/package.json +24 -11
  15. package/src/commons.js +44 -9
  16. package/src/compartment-evaluate.js +102 -0
  17. package/src/compartment-shim.js +78 -106
  18. package/src/enable-property-overrides.js +5 -4
  19. package/src/enablements.js +7 -2
  20. package/src/environment-options.js +125 -0
  21. package/src/error/assert.js +51 -39
  22. package/src/error/console.js +32 -14
  23. package/src/error/fatal-assert.js +2 -0
  24. package/src/error/stringify-utils.js +26 -3
  25. package/src/error/tame-console.js +12 -4
  26. package/src/error/tame-error-constructor.js +18 -17
  27. package/src/error/tame-v8-error-constructor.js +30 -14
  28. package/src/get-anonymous-intrinsics.js +11 -8
  29. package/src/get-source-url.js +4 -4
  30. package/src/global-object.js +33 -26
  31. package/src/intrinsics.js +76 -67
  32. package/src/lockdown-shim.js +111 -119
  33. package/src/make-eval-function.js +3 -5
  34. package/src/make-function-constructor.js +3 -4
  35. package/src/make-safe-evaluator.js +117 -0
  36. package/src/module-instance.js +31 -17
  37. package/src/module-link.js +11 -4
  38. package/src/module-load.js +169 -44
  39. package/src/module-proxy.js +12 -4
  40. package/src/scope-constants.js +6 -3
  41. package/src/scope-handler.js +41 -17
  42. package/src/tame-date-constructor.js +8 -2
  43. package/src/tame-domains.js +46 -0
  44. package/src/tame-function-constructors.js +1 -0
  45. package/src/tame-locale-methods.js +6 -6
  46. package/src/tame-math-object.js +2 -2
  47. package/src/tame-regexp-constructor.js +7 -7
  48. package/src/transforms.js +13 -6
  49. package/src/whitelist-intrinsics.js +9 -3
  50. package/src/evaluate.js +0 -98
package/index.d.ts CHANGED
@@ -18,13 +18,14 @@ export interface LockdownOptions {
18
18
  regExpTaming?: 'safe' | 'unsafe';
19
19
  localeTaming?: 'safe' | 'unsafe';
20
20
  consoleTaming?: 'safe' | 'unsafe';
21
- errorTrapping?: 'platform' | 'exit' | 'abort' | 'report';
21
+ errorTrapping?: 'platform' | 'exit' | 'abort' | 'report' | 'none';
22
22
  errorTaming?: 'safe' | 'unsafe';
23
23
  dateTaming?: 'safe' | 'unsafe'; // deprecated
24
24
  mathTaming?: 'safe' | 'unsafe'; // deprecated
25
25
  stackFiltering?: 'concise' | 'verbose';
26
26
  overrideTaming?: 'moderate' | 'min' | 'severe';
27
27
  overrideDebug?: Array<string>;
28
+ domainTaming?: 'safe' | 'unsafe';
28
29
  __allowUnsafeMonkeyPatching__?: 'safe' | 'unsafe';
29
30
  }
30
31
 
package/index.js CHANGED
@@ -12,15 +12,12 @@
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
14
 
15
- import { globalThis, Error, assign } from './src/commons.js';
15
+ import { globalThis, TypeError, assign } from './src/commons.js';
16
+
16
17
  import { tameFunctionToString } from './src/tame-function-tostring.js';
17
18
  import { getGlobalIntrinsics } from './src/intrinsics.js';
18
- import { getAnonymousIntrinsics } from './src/get-anonymous-intrinsics.js';
19
- import { makeLockdown } from './src/lockdown-shim.js';
20
- import {
21
- makeCompartmentConstructor,
22
- CompartmentPrototype,
23
- } from './src/compartment-shim.js';
19
+ import { lockdown } from './src/lockdown-shim.js';
20
+ import { makeCompartmentConstructor } from './src/compartment-shim.js';
24
21
  import { assert } from './src/error/assert.js';
25
22
 
26
23
  /** getThis returns globalThis in sloppy mode or undefined in strict mode. */
@@ -29,7 +26,7 @@ function getThis() {
29
26
  }
30
27
 
31
28
  if (getThis()) {
32
- throw new Error(`SES failed to initialize, sloppy mode (SES_NO_SLOPPY)`);
29
+ throw new TypeError(`SES failed to initialize, sloppy mode (SES_NO_SLOPPY)`);
33
30
  }
34
31
 
35
32
  const markVirtualizedNativeFunction = tameFunctionToString();
@@ -41,11 +38,7 @@ const Compartment = makeCompartmentConstructor(
41
38
  );
42
39
 
43
40
  assign(globalThis, {
44
- lockdown: makeLockdown(
45
- makeCompartmentConstructor,
46
- CompartmentPrototype,
47
- getAnonymousIntrinsics,
48
- ),
41
+ lockdown,
49
42
  Compartment,
50
43
  assert,
51
44
  });
package/package.json CHANGED
@@ -1,12 +1,22 @@
1
1
  {
2
2
  "name": "ses",
3
- "version": "0.14.2",
4
- "description": "Secure ECMAScript",
3
+ "version": "0.15.1",
4
+ "description": "Hardened JavaScript for Fearless Cooperation",
5
5
  "keywords": [
6
+ "lockdown",
7
+ "harden",
8
+ "Compartment",
9
+ "assert",
10
+ "security",
6
11
  "confinement",
7
12
  "isolation",
13
+ "object capabilities",
14
+ "ocaps",
8
15
  "secure execution",
9
- "third-party code"
16
+ "third-party code",
17
+ "prototype pollution",
18
+ "supply-chain attack",
19
+ "plugin"
10
20
  ],
11
21
  "author": "Agoric",
12
22
  "license": "Apache-2.0",
@@ -49,10 +59,10 @@
49
59
  "test:platform-compatability": "node test/package/test.cjs"
50
60
  },
51
61
  "devDependencies": {
52
- "@endo/compartment-mapper": "^0.5.2",
53
- "@endo/eslint-config": "^0.3.14",
54
- "@endo/static-module-record": "^0.6.2",
55
- "@endo/test262-runner": "^0.1.8",
62
+ "@endo/compartment-mapper": "^0.5.6",
63
+ "@endo/eslint-config": "^0.3.18",
64
+ "@endo/static-module-record": "^0.6.6",
65
+ "@endo/test262-runner": "^0.1.12",
56
66
  "ava": "^3.12.1",
57
67
  "babel-eslint": "^10.0.3",
58
68
  "c8": "^7.7.3",
@@ -142,16 +152,19 @@
142
152
  "parseFloat",
143
153
  "parseInt",
144
154
  "unescape"
145
- ]
155
+ ],
156
+ "@endo/no-polymorphic-call": "error"
146
157
  },
147
158
  "overrides": [
148
159
  {
149
160
  "files": [
150
161
  "test/**/*.js",
151
- "demos/**/*.js"
162
+ "demos/**/*.js",
163
+ "scripts/**/*.js"
152
164
  ],
153
165
  "rules": {
154
- "no-restricted-globals": "off"
166
+ "no-restricted-globals": "off",
167
+ "@endo/no-polymorphic-call": "off"
155
168
  }
156
169
  }
157
170
  ]
@@ -166,5 +179,5 @@
166
179
  ],
167
180
  "timeout": "2m"
168
181
  },
169
- "gitHead": "d95b3951c50dbaf3b6f7cdc52f0fc8ad166d9c4e"
182
+ "gitHead": "f445a041c413195f29c2e929e28f87c62a80d943"
170
183
  }
package/src/commons.js CHANGED
@@ -28,7 +28,7 @@ export const {
28
28
  Promise,
29
29
  Proxy,
30
30
  Reflect,
31
- RegExp,
31
+ RegExp: FERAL_REG_EXP,
32
32
  Set,
33
33
  String,
34
34
  WeakMap,
@@ -36,7 +36,10 @@ export const {
36
36
  } = globalThis;
37
37
 
38
38
  export const {
39
- Error,
39
+ // The feral Error constructor is safe for internal use, but must not be
40
+ // revealed to post-lockdown code in any compartment including the start
41
+ // compartment since in V8 at least it bears stack inspection capabilities.
42
+ Error: FERAL_ERROR,
40
43
  RangeError,
41
44
  ReferenceError,
42
45
  SyntaxError,
@@ -102,7 +105,7 @@ export const defineProperty = (object, prop, descriptor) => {
102
105
  const result = originalDefineProperty(object, prop, descriptor);
103
106
  if (result !== object) {
104
107
  throw TypeError(
105
- `Please report that the original defineProperty silently failed to set ${JSON.stringify(
108
+ `Please report that the original defineProperty silently failed to set ${stringifyJson(
106
109
  String(prop),
107
110
  )}. (SES_DEFINE_PROPERTY_FAILED_SILENTLY)`,
108
111
  );
@@ -131,6 +134,7 @@ export const { prototype: stringPrototype } = String;
131
134
  export const { prototype: weakmapPrototype } = WeakMap;
132
135
  export const { prototype: weaksetPrototype } = WeakSet;
133
136
  export const { prototype: functionPrototype } = Function;
137
+ export const { prototype: promisePrototype } = Promise;
134
138
 
135
139
  /**
136
140
  * uncurryThis()
@@ -151,40 +155,58 @@ export const uncurryThis = fn => (thisArg, ...args) => apply(fn, thisArg, args);
151
155
 
152
156
  export const objectHasOwnProperty = uncurryThis(objectPrototype.hasOwnProperty);
153
157
  //
154
- export const arrayForEach = uncurryThis(arrayPrototype.forEach);
155
158
  export const arrayFilter = uncurryThis(arrayPrototype.filter);
159
+ export const arrayForEach = uncurryThis(arrayPrototype.forEach);
160
+ export const arrayIncludes = uncurryThis(arrayPrototype.includes);
156
161
  export const arrayJoin = uncurryThis(arrayPrototype.join);
157
- export const arrayPush = uncurryThis(arrayPrototype.push);
162
+ export const arrayMap = uncurryThis(arrayPrototype.map);
158
163
  export const arrayPop = uncurryThis(arrayPrototype.pop);
159
- export const arrayIncludes = uncurryThis(arrayPrototype.includes);
164
+ export const arrayPush = uncurryThis(arrayPrototype.push);
165
+ export const arraySlice = uncurryThis(arrayPrototype.slice);
166
+ export const arraySome = uncurryThis(arrayPrototype.some);
167
+ export const arraySort = uncurryThis(arrayPrototype.sort);
168
+ export const iterateArray = uncurryThis(arrayPrototype[iteratorSymbol]);
160
169
  //
161
170
  export const mapSet = uncurryThis(mapPrototype.set);
162
171
  export const mapGet = uncurryThis(mapPrototype.get);
163
172
  export const mapHas = uncurryThis(mapPrototype.has);
173
+ export const iterateMap = uncurryThis(mapPrototype[iteratorSymbol]);
164
174
  //
165
175
  export const setAdd = uncurryThis(setPrototype.add);
166
176
  export const setForEach = uncurryThis(setPrototype.forEach);
167
177
  export const setHas = uncurryThis(setPrototype.has);
178
+ export const iterateSet = uncurryThis(setPrototype[iteratorSymbol]);
168
179
  //
169
180
  export const regexpTest = uncurryThis(regexpPrototype.test);
181
+ export const regexpExec = uncurryThis(regexpPrototype.exec);
182
+ export const matchAllRegExp = uncurryThis(regexpPrototype[matchAllSymbol]);
170
183
  //
171
184
  export const stringEndsWith = uncurryThis(stringPrototype.endsWith);
172
185
  export const stringIncludes = uncurryThis(stringPrototype.includes);
186
+ export const stringIndexOf = uncurryThis(stringPrototype.indexOf);
173
187
  export const stringMatch = uncurryThis(stringPrototype.match);
188
+ export const stringReplace = uncurryThis(stringPrototype.replace);
174
189
  export const stringSearch = uncurryThis(stringPrototype.search);
175
190
  export const stringSlice = uncurryThis(stringPrototype.slice);
176
191
  export const stringSplit = uncurryThis(stringPrototype.split);
177
192
  export const stringStartsWith = uncurryThis(stringPrototype.startsWith);
193
+ export const iterateString = uncurryThis(stringPrototype[iteratorSymbol]);
178
194
  //
195
+ export const weakmapDelete = uncurryThis(weakmapPrototype.delete);
179
196
  export const weakmapGet = uncurryThis(weakmapPrototype.get);
180
- export const weakmapSet = uncurryThis(weakmapPrototype.set);
181
197
  export const weakmapHas = uncurryThis(weakmapPrototype.has);
198
+ export const weakmapSet = uncurryThis(weakmapPrototype.set);
182
199
  //
183
200
  export const weaksetAdd = uncurryThis(weaksetPrototype.add);
184
- export const weaksetSet = uncurryThis(weaksetPrototype.set);
201
+ export const weaksetGet = uncurryThis(weaksetPrototype.get);
185
202
  export const weaksetHas = uncurryThis(weaksetPrototype.has);
186
203
  //
187
204
  export const functionToString = uncurryThis(functionPrototype.toString);
205
+ //
206
+ const { all } = Promise;
207
+ export const promiseAll = promises => apply(all, Promise, [promises]);
208
+ export const promiseCatch = uncurryThis(promisePrototype.catch);
209
+ export const promiseThen = uncurryThis(promisePrototype.then);
188
210
 
189
211
  /**
190
212
  * getConstructorOf()
@@ -197,7 +219,7 @@ export const getConstructorOf = fn =>
197
219
 
198
220
  /**
199
221
  * immutableObject
200
- * An immutable (frozen) exotic object and is safe to share.
222
+ * An immutable (frozen) empty object that is safe to share.
201
223
  */
202
224
  export const immutableObject = freeze(create(null));
203
225
 
@@ -220,6 +242,19 @@ export const immutableObject = freeze(create(null));
220
242
  */
221
243
  export const isObject = value => Object(value) === value;
222
244
 
245
+ /**
246
+ * isError tests whether an object inherits from the intrinsic
247
+ * `Error.prototype`.
248
+ * We capture the original error constructor as FERAL_ERROR to provide a clear
249
+ * signal for reviewers that we are handling an object with excess authority,
250
+ * like stack trace inspection, that we are carefully hiding from client code.
251
+ * Checking instanceof happens to be safe, but to avoid uttering FERAL_ERROR
252
+ * for such a trivial case outside commons.js, we provide a utility function.
253
+ *
254
+ * @param {any} value
255
+ */
256
+ export const isError = value => value instanceof FERAL_ERROR;
257
+
223
258
  // The original unsafe untamed eval function, which must not escape.
224
259
  // Sample at module initialization time, which is before lockdown can
225
260
  // repair it. Use it only to build powerless abstractions.
@@ -0,0 +1,102 @@
1
+ /// <reference types="ses">
2
+ import {
3
+ TypeError,
4
+ arrayPush,
5
+ create,
6
+ defineProperties,
7
+ getOwnPropertyDescriptors,
8
+ } from './commons.js';
9
+ import {
10
+ evadeHtmlCommentTest,
11
+ evadeImportExpressionTest,
12
+ rejectSomeDirectEvalExpressions,
13
+ } from './transforms.js';
14
+ import { makeSafeEvaluator } from './make-safe-evaluator.js';
15
+
16
+ export const provideCompartmentEvaluator = (compartmentFields, options) => {
17
+ const {
18
+ sloppyGlobalsMode = false,
19
+ __moduleShimLexicals__ = undefined,
20
+ } = options;
21
+
22
+ let safeEvaluate;
23
+
24
+ if (__moduleShimLexicals__ === undefined && !sloppyGlobalsMode) {
25
+ ({ safeEvaluate } = compartmentFields);
26
+ } else {
27
+ // The scope proxy or global lexicals are different from the
28
+ // shared evaluator so we need to build a new one
29
+
30
+ let { globalTransforms } = compartmentFields;
31
+ const {
32
+ globalObject,
33
+ globalLexicals,
34
+ knownScopeProxies,
35
+ } = compartmentFields;
36
+
37
+ let localObject = globalLexicals;
38
+ if (__moduleShimLexicals__ !== undefined) {
39
+ // When using `evaluate` for ESM modules, as should only occur from the
40
+ // module-shim's module-instance.js, we do not reveal the SES-shim's
41
+ // module-to-program translation, as this is not standardizable behavior.
42
+ // However, the `localTransforms` will come from the `__shimTransforms__`
43
+ // Compartment option in this case, which is a non-standardizable escape
44
+ // hatch so programs designed specifically for the SES-shim
45
+ // implementation may opt-in to use the same transforms for `evaluate`
46
+ // and `import`, at the expense of being tightly coupled to SES-shim.
47
+ globalTransforms = undefined;
48
+
49
+ localObject = create(null, getOwnPropertyDescriptors(globalLexicals));
50
+ defineProperties(
51
+ localObject,
52
+ getOwnPropertyDescriptors(__moduleShimLexicals__),
53
+ );
54
+ }
55
+
56
+ ({ safeEvaluate } = makeSafeEvaluator({
57
+ globalObject,
58
+ localObject,
59
+ globalTransforms,
60
+ sloppyGlobalsMode,
61
+ knownScopeProxies,
62
+ }));
63
+ }
64
+
65
+ return { safeEvaluate };
66
+ };
67
+
68
+ export const compartmentEvaluate = (compartmentFields, source, options) => {
69
+ // Perform this check first to avoid unecessary sanitizing.
70
+ // TODO Maybe relax string check and coerce instead:
71
+ // https://github.com/tc39/proposal-dynamic-code-brand-checks
72
+ if (typeof source !== 'string') {
73
+ throw new TypeError('first argument of evaluate() must be a string');
74
+ }
75
+
76
+ // Extract options, and shallow-clone transforms.
77
+ const {
78
+ transforms = [],
79
+ __evadeHtmlCommentTest__ = false,
80
+ __evadeImportExpressionTest__ = false,
81
+ __rejectSomeDirectEvalExpressions__ = true, // Note default on
82
+ } = options;
83
+ const localTransforms = [...transforms];
84
+ if (__evadeHtmlCommentTest__ === true) {
85
+ arrayPush(localTransforms, evadeHtmlCommentTest);
86
+ }
87
+ if (__evadeImportExpressionTest__ === true) {
88
+ arrayPush(localTransforms, evadeImportExpressionTest);
89
+ }
90
+ if (__rejectSomeDirectEvalExpressions__ === true) {
91
+ arrayPush(localTransforms, rejectSomeDirectEvalExpressions);
92
+ }
93
+
94
+ const { safeEvaluate } = provideCompartmentEvaluator(
95
+ compartmentFields,
96
+ options,
97
+ );
98
+
99
+ return safeEvaluate(source, {
100
+ localTransforms,
101
+ });
102
+ };
@@ -3,36 +3,35 @@
3
3
  /// <reference types="ses">
4
4
 
5
5
  import {
6
- Error,
7
6
  Map,
8
7
  ReferenceError,
9
8
  TypeError,
10
9
  WeakMap,
11
10
  WeakSet,
11
+ arrayFilter,
12
+ arrayJoin,
12
13
  assign,
13
- create,
14
14
  defineProperties,
15
15
  entries,
16
16
  freeze,
17
- getOwnPropertyDescriptors,
18
17
  getOwnPropertyNames,
18
+ promiseThen,
19
19
  weakmapGet,
20
20
  weakmapSet,
21
21
  weaksetHas,
22
22
  } from './commons.js';
23
- import { initGlobalObject } from './global-object.js';
24
- import { performEval } from './evaluate.js';
23
+ import {
24
+ setGlobalObjectConstantProperties,
25
+ setGlobalObjectMutableProperties,
26
+ } from './global-object.js';
25
27
  import { isValidIdentifierName } from './scope-constants.js';
26
28
  import { sharedGlobalPropertyNames } from './whitelist.js';
27
- import {
28
- evadeHtmlCommentTest,
29
- evadeImportExpressionTest,
30
- rejectSomeDirectEvalExpressions,
31
- } from './transforms.js';
32
29
  import { load } from './module-load.js';
33
30
  import { link } from './module-link.js';
34
31
  import { getDeferredExports } from './module-proxy.js';
35
32
  import { assert } from './error/assert.js';
33
+ import { compartmentEvaluate } from './compartment-evaluate.js';
34
+ import { makeSafeEvaluator } from './make-safe-evaluator.js';
36
35
 
37
36
  const { quote: q } = assert;
38
37
 
@@ -74,6 +73,21 @@ export const InertCompartment = function Compartment(
74
73
  );
75
74
  };
76
75
 
76
+ /**
77
+ * @param {Compartment} compartment
78
+ * @param {string} specifier
79
+ */
80
+ const compartmentImportNow = (compartment, specifier) => {
81
+ const { execute, exportsProxy } = link(
82
+ privateFields,
83
+ moduleAliases,
84
+ compartment,
85
+ specifier,
86
+ );
87
+ execute();
88
+ return exportsProxy;
89
+ };
90
+
77
91
  export const CompartmentPrototype = {
78
92
  constructor: InertCompartment,
79
93
 
@@ -96,66 +110,8 @@ export const CompartmentPrototype = {
96
110
  * @param {boolean} [options.__rejectSomeDirectEvalExpressions__]
97
111
  */
98
112
  evaluate(source, options = {}) {
99
- // Perform this check first to avoid unecessary sanitizing.
100
- // TODO Maybe relax string check and coerce instead:
101
- // https://github.com/tc39/proposal-dynamic-code-brand-checks
102
- if (typeof source !== 'string') {
103
- throw new TypeError('first argument of evaluate() must be a string');
104
- }
105
-
106
- // Extract options, and shallow-clone transforms.
107
- const {
108
- transforms = [],
109
- sloppyGlobalsMode = false,
110
- __moduleShimLexicals__ = undefined,
111
- __evadeHtmlCommentTest__ = false,
112
- __evadeImportExpressionTest__ = false,
113
- __rejectSomeDirectEvalExpressions__ = true, // Note default on
114
- } = options;
115
- const localTransforms = [...transforms];
116
- if (__evadeHtmlCommentTest__ === true) {
117
- localTransforms.push(evadeHtmlCommentTest);
118
- }
119
- if (__evadeImportExpressionTest__ === true) {
120
- localTransforms.push(evadeImportExpressionTest);
121
- }
122
- if (__rejectSomeDirectEvalExpressions__ === true) {
123
- localTransforms.push(rejectSomeDirectEvalExpressions);
124
- }
125
-
126
113
  const compartmentFields = weakmapGet(privateFields, this);
127
- let { globalTransforms } = compartmentFields;
128
- const {
129
- globalObject,
130
- globalLexicals,
131
- knownScopeProxies,
132
- } = compartmentFields;
133
-
134
- let localObject = globalLexicals;
135
- if (__moduleShimLexicals__ !== undefined) {
136
- // When using `evaluate` for ESM modules, as should only occur from the
137
- // module-shim's module-instance.js, we do not reveal the SES-shim's
138
- // module-to-program translation, as this is not standardizable behavior.
139
- // However, the `localTransforms` will come from the `__shimTransforms__`
140
- // Compartment option in this case, which is a non-standardizable escape
141
- // hatch so programs designed specifically for the SES-shim
142
- // implementation may opt-in to use the same transforms for `evaluate`
143
- // and `import`, at the expense of being tightly coupled to SES-shim.
144
- globalTransforms = undefined;
145
-
146
- localObject = create(null, getOwnPropertyDescriptors(globalLexicals));
147
- defineProperties(
148
- localObject,
149
- getOwnPropertyDescriptors(__moduleShimLexicals__),
150
- );
151
- }
152
-
153
- return performEval(source, globalObject, localObject, {
154
- globalTransforms,
155
- localTransforms,
156
- sloppyGlobalsMode,
157
- knownScopeProxies,
158
- });
114
+ return compartmentEvaluate(compartmentFields, source, options);
159
115
  },
160
116
 
161
117
  toString() {
@@ -192,12 +148,15 @@ export const CompartmentPrototype = {
192
148
 
193
149
  assertModuleHooks(this);
194
150
 
195
- return load(privateFields, moduleAliases, this, specifier).then(() => {
196
- // The namespace box is a contentious design and likely to be a breaking
197
- // change in an appropriately numbered future version.
198
- const namespace = this.importNow(specifier);
199
- return { namespace };
200
- });
151
+ return promiseThen(
152
+ load(privateFields, moduleAliases, this, specifier),
153
+ () => {
154
+ // The namespace box is a contentious design and likely to be a breaking
155
+ // change in an appropriately numbered future version.
156
+ const namespace = compartmentImportNow(this, specifier);
157
+ return { namespace };
158
+ },
159
+ );
201
160
  },
202
161
 
203
162
  async load(specifier) {
@@ -217,9 +176,7 @@ export const CompartmentPrototype = {
217
176
 
218
177
  assertModuleHooks(this);
219
178
 
220
- const moduleInstance = link(privateFields, moduleAliases, this, specifier);
221
- moduleInstance.execute();
222
- return moduleInstance.exportsProxy;
179
+ return compartmentImportNow(this, specifier);
223
180
  },
224
181
  };
225
182
 
@@ -253,7 +210,7 @@ export const makeCompartmentConstructor = (
253
210
  name = '<unknown>',
254
211
  transforms = [],
255
212
  __shimTransforms__ = [],
256
- globalLexicals = {},
213
+ globalLexicals: globalLexicalsOption = {},
257
214
  resolveHook,
258
215
  importHook,
259
216
  moduleMapHook,
@@ -291,48 +248,63 @@ export const makeCompartmentConstructor = (
291
248
  }
292
249
  }
293
250
 
294
- const globalObject = {};
295
- initGlobalObject(
296
- globalObject,
297
- intrinsics,
298
- sharedGlobalPropertyNames,
299
- targetMakeCompartmentConstructor,
300
- this.constructor.prototype,
301
- {
302
- globalTransforms,
303
- markVirtualizedNativeFunction,
304
- },
305
- );
306
-
307
- assign(globalObject, endowments);
308
-
309
- const invalidNames = getOwnPropertyNames(globalLexicals).filter(
251
+ const invalidNames = arrayFilter(
252
+ getOwnPropertyNames(globalLexicalsOption),
310
253
  identifier => !isValidIdentifierName(identifier),
311
254
  );
312
255
  if (invalidNames.length) {
313
- throw new Error(
314
- `Cannot create compartment with invalid names for global lexicals: ${invalidNames.join(
256
+ throw new TypeError(
257
+ `Cannot create compartment with invalid names for global lexicals: ${arrayJoin(
258
+ invalidNames,
315
259
  ', ',
316
260
  )}; these names would not be lexically mentionable`,
317
261
  );
318
262
  }
263
+ // The caller continues to own the globalLexicals object they passed to
264
+ // the compartment constructor, but the compartment only respects the
265
+ // original values and they are constants in the scope of evaluated
266
+ // programs and executed modules.
267
+ // This shallow copy captures only the values of enumerable own
268
+ // properties, erasing accessors.
269
+ // The snapshot is frozen to ensure that the properties are immutable
270
+ // when transferred-by-property-descriptor onto local scope objects.
271
+ const globalLexicals = freeze({ ...globalLexicalsOption });
272
+
273
+ const globalObject = {};
274
+
275
+ // We must initialize all constant properties first because
276
+ // `makeSafeEvaluator` may use them to create optimized bindings
277
+ // in the evaluator.
278
+ // TODO: consider merging into a single initialization if internal
279
+ // evaluator is no longer eagerly created
280
+ setGlobalObjectConstantProperties(globalObject);
319
281
 
320
282
  const knownScopeProxies = new WeakSet();
283
+ const { safeEvaluate } = makeSafeEvaluator({
284
+ globalObject,
285
+ localObject: globalLexicals,
286
+ globalTransforms,
287
+ sloppyGlobalsMode: false,
288
+ knownScopeProxies,
289
+ });
290
+
291
+ setGlobalObjectMutableProperties(globalObject, {
292
+ intrinsics,
293
+ newGlobalPropertyNames: sharedGlobalPropertyNames,
294
+ makeCompartmentConstructor: targetMakeCompartmentConstructor,
295
+ safeEvaluate,
296
+ markVirtualizedNativeFunction,
297
+ });
298
+
299
+ assign(globalObject, endowments);
321
300
 
322
301
  weakmapSet(privateFields, this, {
323
302
  name,
324
303
  globalTransforms,
325
304
  globalObject,
326
305
  knownScopeProxies,
327
- // The caller continues to own the globalLexicals object they passed to
328
- // the compartment constructor, but the compartment only respects the
329
- // original values and they are constants in the scope of evaluated
330
- // programs and executed modules.
331
- // This shallow copy captures only the values of enumerable own
332
- // properties, erasing accessors.
333
- // The snapshot is frozen to ensure that the properties are immutable
334
- // when transferred-by-property-descriptor onto local scope objects.
335
- globalLexicals: freeze({ ...globalLexicals }),
306
+ globalLexicals,
307
+ safeEvaluate,
336
308
  resolveHook,
337
309
  importHook,
338
310
  moduleMap,
@@ -4,10 +4,10 @@
4
4
  // @ts-check
5
5
 
6
6
  import {
7
- Error,
8
7
  Set,
9
8
  String,
10
9
  TypeError,
10
+ arrayForEach,
11
11
  defineProperty,
12
12
  getOwnPropertyDescriptor,
13
13
  getOwnPropertyDescriptors,
@@ -112,7 +112,8 @@ export default function enablePropertyOverrides(
112
112
  this[prop] = newValue;
113
113
  } else {
114
114
  if (isDebug) {
115
- console.error(new Error(`Override property ${prop}`));
115
+ // eslint-disable-next-line @endo/no-polymorphic-call
116
+ console.error(new TypeError(`Override property ${prop}`));
116
117
  }
117
118
  defineProperty(this, prop, {
118
119
  value: newValue,
@@ -148,7 +149,7 @@ export default function enablePropertyOverrides(
148
149
  // TypeScript does not allow symbols to be used as indexes because it
149
150
  // cannot recokon types of symbolized properties.
150
151
  // @ts-ignore
151
- ownKeys(descs).forEach(prop => enable(path, obj, prop, descs[prop]));
152
+ arrayForEach(ownKeys(descs), prop => enable(path, obj, prop, descs[prop]));
152
153
  }
153
154
 
154
155
  function enableProperties(path, obj, plan) {
@@ -194,7 +195,7 @@ export default function enablePropertyOverrides(
194
195
  break;
195
196
  }
196
197
  default: {
197
- throw new Error(`unrecognized overrideTaming ${overrideTaming}`);
198
+ throw new TypeError(`unrecognized overrideTaming ${overrideTaming}`);
198
199
  }
199
200
  }
200
201