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,292 @@
1
+ // @ts-check
2
+ /* eslint-disable no-underscore-dangle */
3
+ /// <reference types="ses">
4
+
5
+ import {
6
+ Map,
7
+ ReferenceError,
8
+ TypeError,
9
+ WeakMap,
10
+ assign,
11
+ defineProperties,
12
+ entries,
13
+ promiseThen,
14
+ weakmapGet,
15
+ weakmapSet,
16
+ } from './commons.js';
17
+ import {
18
+ setGlobalObjectSymbolUnscopables,
19
+ setGlobalObjectConstantProperties,
20
+ setGlobalObjectMutableProperties,
21
+ setGlobalObjectEvaluators,
22
+ } from './global-object.js';
23
+ import { sharedGlobalPropertyNames } from './permits.js';
24
+ import { load } from './module-load.js';
25
+ import { link } from './module-link.js';
26
+ import { getDeferredExports } from './module-proxy.js';
27
+ import { assert } from './error/assert.js';
28
+ import { compartmentEvaluate } from './compartment-evaluate.js';
29
+ import { makeSafeEvaluator } from './make-safe-evaluator.js';
30
+
31
+ const { quote: q } = assert;
32
+
33
+ // moduleAliases associates every public module exports namespace with its
34
+ // corresponding compartment and specifier so they can be used to link modules
35
+ // across compartments.
36
+ // The mechanism to thread an alias is to use the compartment.module function
37
+ // to obtain the exports namespace of a foreign module and pass it into another
38
+ // compartment's moduleMap constructor option.
39
+ const moduleAliases = new WeakMap();
40
+
41
+ // privateFields captures the private state for each compartment.
42
+ const privateFields = new WeakMap();
43
+
44
+ // Compartments do not need an importHook or resolveHook to be useful
45
+ // as a vessel for evaluating programs.
46
+ // However, any method that operates the module system will throw an exception
47
+ // if these hooks are not available.
48
+ const assertModuleHooks = compartment => {
49
+ const { importHook, resolveHook } = weakmapGet(privateFields, compartment);
50
+ if (typeof importHook !== 'function' || typeof resolveHook !== 'function') {
51
+ throw TypeError(
52
+ 'Compartment must be constructed with an importHook and a resolveHook for it to be able to load modules',
53
+ );
54
+ }
55
+ };
56
+
57
+ export const InertCompartment = function Compartment(
58
+ _endowments = {},
59
+ _modules = {},
60
+ _options = {},
61
+ ) {
62
+ throw TypeError(
63
+ 'Compartment.prototype.constructor is not a valid constructor.',
64
+ );
65
+ };
66
+
67
+ /**
68
+ * @param {Compartment} compartment
69
+ * @param {string} specifier
70
+ */
71
+ const compartmentImportNow = (compartment, specifier) => {
72
+ const { execute, exportsProxy } = link(
73
+ privateFields,
74
+ moduleAliases,
75
+ compartment,
76
+ specifier,
77
+ );
78
+ execute();
79
+ return exportsProxy;
80
+ };
81
+
82
+ export const CompartmentPrototype = {
83
+ constructor: InertCompartment,
84
+
85
+ get globalThis() {
86
+ return weakmapGet(privateFields, this).globalObject;
87
+ },
88
+
89
+ get name() {
90
+ return weakmapGet(privateFields, this).name;
91
+ },
92
+
93
+ /**
94
+ * @param {string} source is a JavaScript program grammar construction.
95
+ * @param {object} [options]
96
+ * @param {Array<import('./lockdown-shim').Transform>} [options.transforms]
97
+ * @param {boolean} [options.sloppyGlobalsMode]
98
+ * @param {object} [options.__moduleShimLexicals__]
99
+ * @param {boolean} [options.__evadeHtmlCommentTest__]
100
+ * @param {boolean} [options.__evadeImportExpressionTest__]
101
+ * @param {boolean} [options.__rejectSomeDirectEvalExpressions__]
102
+ */
103
+ evaluate(source, options = {}) {
104
+ const compartmentFields = weakmapGet(privateFields, this);
105
+ return compartmentEvaluate(compartmentFields, source, options);
106
+ },
107
+
108
+ toString() {
109
+ return '[object Compartment]';
110
+ },
111
+
112
+ module(specifier) {
113
+ if (typeof specifier !== 'string') {
114
+ throw TypeError('first argument of module() must be a string');
115
+ }
116
+
117
+ assertModuleHooks(this);
118
+
119
+ const { exportsProxy } = getDeferredExports(
120
+ this,
121
+ weakmapGet(privateFields, this),
122
+ moduleAliases,
123
+ specifier,
124
+ );
125
+
126
+ return exportsProxy;
127
+ },
128
+
129
+ async import(specifier) {
130
+ if (typeof specifier !== 'string') {
131
+ throw TypeError('first argument of import() must be a string');
132
+ }
133
+
134
+ assertModuleHooks(this);
135
+
136
+ return promiseThen(
137
+ load(privateFields, moduleAliases, this, specifier),
138
+ () => {
139
+ // The namespace box is a contentious design and likely to be a breaking
140
+ // change in an appropriately numbered future version.
141
+ const namespace = compartmentImportNow(
142
+ /** @type {Compartment} */ (this),
143
+ specifier,
144
+ );
145
+ return { namespace };
146
+ },
147
+ );
148
+ },
149
+
150
+ async load(specifier) {
151
+ if (typeof specifier !== 'string') {
152
+ throw TypeError('first argument of load() must be a string');
153
+ }
154
+
155
+ assertModuleHooks(this);
156
+
157
+ return load(privateFields, moduleAliases, this, specifier);
158
+ },
159
+
160
+ importNow(specifier) {
161
+ if (typeof specifier !== 'string') {
162
+ throw TypeError('first argument of importNow() must be a string');
163
+ }
164
+
165
+ assertModuleHooks(this);
166
+
167
+ return compartmentImportNow(/** @type {Compartment} */ (this), specifier);
168
+ },
169
+ };
170
+
171
+ defineProperties(InertCompartment, {
172
+ prototype: { value: CompartmentPrototype },
173
+ });
174
+
175
+ /**
176
+ * @callback MakeCompartmentConstructor
177
+ * @param {MakeCompartmentConstructor} targetMakeCompartmentConstructor
178
+ * @param {Record<string, any>} intrinsics
179
+ * @param {(object: object) => void} markVirtualizedNativeFunction
180
+ * @returns {Compartment['constructor']}
181
+ */
182
+
183
+ /** @type {MakeCompartmentConstructor} */
184
+ export const makeCompartmentConstructor = (
185
+ targetMakeCompartmentConstructor,
186
+ intrinsics,
187
+ markVirtualizedNativeFunction,
188
+ ) => {
189
+ function Compartment(endowments = {}, moduleMap = {}, options = {}) {
190
+ if (new.target === undefined) {
191
+ throw TypeError(
192
+ "Class constructor Compartment cannot be invoked without 'new'",
193
+ );
194
+ }
195
+
196
+ // Extract options, and shallow-clone transforms.
197
+ const {
198
+ name = '<unknown>',
199
+ transforms = [],
200
+ __shimTransforms__ = [],
201
+ resolveHook,
202
+ importHook,
203
+ moduleMapHook,
204
+ importMetaHook,
205
+ } = options;
206
+ const globalTransforms = [...transforms, ...__shimTransforms__];
207
+
208
+ // Map<FullSpecifier, ModuleCompartmentRecord>
209
+ const moduleRecords = new Map();
210
+ // Map<FullSpecifier, ModuleInstance>
211
+ const instances = new Map();
212
+ // Map<FullSpecifier, {ExportsProxy, ProxiedExports, activate()}>
213
+ const deferredExports = new Map();
214
+
215
+ // Validate given moduleMap.
216
+ // The module map gets translated on-demand in module-load.js and the
217
+ // moduleMap can be invalid in ways that cannot be detected in the
218
+ // constructor, but these checks allow us to throw early for a better
219
+ // developer experience.
220
+ for (const [specifier, aliasNamespace] of entries(moduleMap || {})) {
221
+ if (typeof aliasNamespace === 'string') {
222
+ // TODO implement parent module record retrieval.
223
+ throw TypeError(
224
+ `Cannot map module ${q(specifier)} to ${q(
225
+ aliasNamespace,
226
+ )} in parent compartment`,
227
+ );
228
+ } else if (weakmapGet(moduleAliases, aliasNamespace) === undefined) {
229
+ // TODO create and link a synthetic module instance from the given
230
+ // namespace object.
231
+ throw ReferenceError(
232
+ `Cannot map module ${q(
233
+ specifier,
234
+ )} because it has no known compartment in this realm`,
235
+ );
236
+ }
237
+ }
238
+
239
+ const globalObject = {};
240
+
241
+ setGlobalObjectSymbolUnscopables(globalObject);
242
+
243
+ // We must initialize all constant properties first because
244
+ // `makeSafeEvaluator` may use them to create optimized bindings
245
+ // in the evaluator.
246
+ // TODO: consider merging into a single initialization if internal
247
+ // evaluator is no longer eagerly created
248
+ setGlobalObjectConstantProperties(globalObject);
249
+
250
+ const { safeEvaluate } = makeSafeEvaluator({
251
+ globalObject,
252
+ globalTransforms,
253
+ sloppyGlobalsMode: false,
254
+ });
255
+
256
+ setGlobalObjectMutableProperties(globalObject, {
257
+ intrinsics,
258
+ newGlobalPropertyNames: sharedGlobalPropertyNames,
259
+ makeCompartmentConstructor: targetMakeCompartmentConstructor,
260
+ markVirtualizedNativeFunction,
261
+ });
262
+
263
+ // TODO: maybe add evalTaming to the Compartment constructor 3rd options?
264
+ setGlobalObjectEvaluators(
265
+ globalObject,
266
+ safeEvaluate,
267
+ markVirtualizedNativeFunction,
268
+ );
269
+
270
+ assign(globalObject, endowments);
271
+
272
+ weakmapSet(privateFields, this, {
273
+ name: `${name}`,
274
+ globalTransforms,
275
+ globalObject,
276
+ safeEvaluate,
277
+ resolveHook,
278
+ importHook,
279
+ moduleMap,
280
+ moduleMapHook,
281
+ importMetaHook,
282
+ moduleRecords,
283
+ __shimTransforms__,
284
+ deferredExports,
285
+ instances,
286
+ });
287
+ }
288
+
289
+ Compartment.prototype = CompartmentPrototype;
290
+
291
+ return Compartment;
292
+ };
@@ -193,7 +193,7 @@ export const severeEnablements = {
193
193
  * With the `'*'` setting here, all the properties inherited from
194
194
  * `Object.prototype` are accessors, creating an unusable display as seen
195
195
  * at As explained at
196
- * https://github.com/endojs/endo/blob/master/packages/ses/lockdown-options.md#overridetaming-options
196
+ * https://github.com/endojs/endo/blob/master/packages/ses/docs/lockdown.md#overridetaming-options
197
197
  * Open the triangles at the bottom of that section.
198
198
  */
199
199
  '%ObjectPrototype%': '*',
@@ -174,6 +174,10 @@ freeze(ErrorInfo);
174
174
 
175
175
  /** @type {MakeCausalConsole} */
176
176
  const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
177
+ if (!baseConsole) {
178
+ return undefined;
179
+ }
180
+
177
181
  const { getStackString, tagError, takeMessageLogArgs, takeNoteLogArgsArray } =
178
182
  loggedErrorHandler;
179
183
 
@@ -83,7 +83,7 @@
83
83
  * calls methods of the `loggedErrorHandler` to customize how it handles logged
84
84
  * errors.
85
85
  *
86
- * @param {VirtualConsole} baseConsole
86
+ * @param {VirtualConsole | undefined} baseConsole
87
87
  * @param {LoggedErrorHandler} loggedErrorHandler
88
- * @returns {VirtualConsole}
88
+ * @returns {VirtualConsole | undefined}
89
89
  */
@@ -133,9 +133,8 @@ export const makeLRUCacheMap = keysBudget => {
133
133
  /**
134
134
  * @param {K} key
135
135
  */
136
- // TODO Change to the following line, once our tools don't choke on `?.`.
137
- // See https://github.com/endojs/endo/issues/1514
138
- // const get = key => touchCell(key)?.data?.get(key);
136
+ // UNTIL https://github.com/endojs/endo/issues/1514
137
+ // Prefer: const get = key => touchCell(key)?.data?.get(key);
139
138
  const get = key => {
140
139
  const cell = touchCell(key);
141
140
  return cell && cell.data && cell.data.get(key);
@@ -1,14 +1,47 @@
1
1
  // @ts-check
2
2
 
3
- import { TypeError, globalThis } from '../commons.js';
3
+ import {
4
+ TypeError,
5
+ apply,
6
+ defineProperty,
7
+ freeze,
8
+ globalThis,
9
+ } from '../commons.js';
4
10
  import { loggedErrorHandler as defaultHandler } from './assert.js';
5
11
  import { makeCausalConsole } from './console.js';
6
12
  import { makeRejectionHandlers } from './unhandled-rejection.js';
7
13
  import './types.js';
8
14
  import './internal-types.js';
9
15
 
16
+ const wrapLogger = (logger, thisArg) =>
17
+ freeze((...args) => apply(logger, thisArg, args));
18
+
10
19
  // eslint-disable-next-line no-restricted-globals
11
- const originalConsole = console;
20
+ const originalConsole = /** @type {VirtualConsole} */ (
21
+ // eslint-disable-next-line no-nested-ternary
22
+ typeof console !== 'undefined'
23
+ ? console
24
+ : typeof print === 'function'
25
+ ? // Make a good-enough console for eshost (including only functions that
26
+ // log at a specific level with no special argument interpretation).
27
+ // https://console.spec.whatwg.org/#logging
28
+ (p => freeze({ debug: p, log: p, info: p, warn: p, error: p }))(
29
+ // eslint-disable-next-line no-undef
30
+ wrapLogger(print),
31
+ )
32
+ : undefined
33
+ );
34
+
35
+ // Upgrade a log-only console (as in `eshost -h SpiderMonkey`).
36
+ if (originalConsole && originalConsole.log) {
37
+ for (const methodName of ['warn', 'error']) {
38
+ if (!originalConsole[methodName]) {
39
+ defineProperty(originalConsole, methodName, {
40
+ value: wrapLogger(originalConsole.log, originalConsole),
41
+ });
42
+ }
43
+ }
44
+ }
12
45
 
13
46
  /**
14
47
  * Wrap console unless suppressed.
@@ -40,10 +73,11 @@ export const tameConsole = (
40
73
  getStackString: optGetStackString,
41
74
  };
42
75
  }
43
- const ourConsole =
76
+ const ourConsole = /** @type {VirtualConsole} */ (
44
77
  consoleTaming === 'unsafe'
45
78
  ? originalConsole
46
- : makeCausalConsole(originalConsole, loggedErrorHandler);
79
+ : makeCausalConsole(originalConsole, loggedErrorHandler)
80
+ );
47
81
 
48
82
  // Attach platform-specific error traps such that any error that gets thrown
49
83
  // at top-of-turn (the bottom of stack) will get logged by our causal
@@ -4,7 +4,7 @@
4
4
  * @callback BaseAssert
5
5
  * The `assert` function itself.
6
6
  *
7
- * @param {*} flag The truthy/falsy value
7
+ * @param {any} flag The truthy/falsy value
8
8
  * @param {Details=} optDetails The details to throw
9
9
  * @param {ErrorConstructor=} ErrorConstructor An optional alternate error
10
10
  * constructor to use.
@@ -51,8 +51,8 @@
51
51
  * The `assert.equal` method
52
52
  *
53
53
  * Assert that two values must be `Object.is`.
54
- * @param {*} actual The value we received
55
- * @param {*} expected What we wanted
54
+ * @param {any} actual The value we received
55
+ * @param {any} expected What we wanted
56
56
  * @param {Details=} optDetails The details to throw
57
57
  * @param {ErrorConstructor=} ErrorConstructor An optional alternate error
58
58
  * constructor to use.
@@ -201,7 +201,7 @@
201
201
  * ```
202
202
  *
203
203
  * @callback AssertQuote
204
- * @param {*} payload What to declassify
204
+ * @param {any} payload What to declassify
205
205
  * @param {(string|number)=} spaces
206
206
  * @returns {StringablePayload} The declassified payload
207
207
  */
@@ -15,7 +15,7 @@ import {
15
15
  regexpPrototype,
16
16
  globalThis,
17
17
  } from './commons.js';
18
- import { InertCompartment } from './compartment-shim.js';
18
+ import { InertCompartment } from './compartment.js';
19
19
 
20
20
  /**
21
21
  * Object.getConstructorOf()
@@ -110,10 +110,12 @@ export const setGlobalObjectMutableProperties = (
110
110
  globalThis: globalObject,
111
111
  };
112
112
 
113
- perCompartmentGlobals.Compartment = makeCompartmentConstructor(
114
- makeCompartmentConstructor,
115
- intrinsics,
116
- markVirtualizedNativeFunction,
113
+ perCompartmentGlobals.Compartment = freeze(
114
+ makeCompartmentConstructor(
115
+ makeCompartmentConstructor,
116
+ intrinsics,
117
+ markVirtualizedNativeFunction,
118
+ ),
117
119
  );
118
120
 
119
121
  // TODO These should still be tamed according to the whitelist before
@@ -145,7 +147,7 @@ export const setGlobalObjectEvaluators = (
145
147
  markVirtualizedNativeFunction,
146
148
  ) => {
147
149
  {
148
- const f = makeEvalFunction(evaluator);
150
+ const f = freeze(makeEvalFunction(evaluator));
149
151
  markVirtualizedNativeFunction(f);
150
152
  defineProperty(globalObject, 'eval', {
151
153
  value: f,
@@ -155,7 +157,7 @@ export const setGlobalObjectEvaluators = (
155
157
  });
156
158
  }
157
159
  {
158
- const f = makeFunctionConstructor(evaluator);
160
+ const f = freeze(makeFunctionConstructor(evaluator));
159
161
  markVirtualizedNativeFunction(f);
160
162
  defineProperty(globalObject, 'Function', {
161
163
  value: f,