ses 1.9.1 → 1.11.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.
package/dist/types.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @file Types of the SES environment
2
+ * @module Types of the SES environment
3
3
  */
4
4
 
5
5
  /* eslint-disable no-restricted-globals, vars-on-top, no-var */
@@ -24,10 +24,17 @@ export interface RepairOptions {
24
24
  localeTaming?: 'safe' | 'unsafe';
25
25
  consoleTaming?: 'safe' | 'unsafe';
26
26
  errorTrapping?: 'platform' | 'exit' | 'abort' | 'report' | 'none';
27
+ reporting?: 'platform' | 'console' | 'none';
27
28
  unhandledRejectionTrapping?: 'report' | 'none';
28
29
  errorTaming?: 'safe' | 'unsafe' | 'unsafe-debug';
29
- dateTaming?: 'safe' | 'unsafe'; // deprecated
30
- mathTaming?: 'safe' | 'unsafe'; // deprecated
30
+ /**
31
+ * @deprecated Deprecated and does nothing. In the future specifying it will be an error.
32
+ */
33
+ dateTaming?: 'safe' | 'unsafe';
34
+ /**
35
+ * @deprecated Deprecated and does nothing. In the future specifying it will be an error.
36
+ */
37
+ mathTaming?: 'safe' | 'unsafe';
31
38
  evalTaming?: 'safeEval' | 'unsafeEval' | 'noEval';
32
39
  stackFiltering?: 'concise' | 'verbose';
33
40
  overrideTaming?: 'moderate' | 'min' | 'severe';
@@ -551,12 +558,12 @@ declare global {
551
558
 
552
559
  // Deprecated:
553
560
  constructor(
554
- globals?: Record<string, any> | undefined,
561
+ globals?: Record<PropertyKey, any> | undefined,
555
562
  modules?: Record<string, ModuleDescriptor>,
556
563
  options?: CompartmentOptions,
557
564
  );
558
565
 
559
- get globalThis(): Record<string, any>;
566
+ get globalThis(): Record<PropertyKey, any>;
560
567
 
561
568
  get name(): string;
562
569
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ses",
3
- "version": "1.9.1",
3
+ "version": "1.11.0",
4
4
  "description": "Hardened JavaScript for Fearless Cooperation",
5
5
  "keywords": [
6
6
  "lockdown",
@@ -38,6 +38,7 @@
38
38
  ".": {
39
39
  "import": {
40
40
  "types": "./types.d.ts",
41
+ "xs": "./src-xs/index.js",
41
42
  "default": "./index.js"
42
43
  },
43
44
  "require": {
@@ -57,8 +58,14 @@
57
58
  },
58
59
  "./tools.js": "./tools.js",
59
60
  "./assert-shim.js": "./assert-shim.js",
60
- "./lockdown-shim.js": "./lockdown-shim.js",
61
- "./compartment-shim.js": "./compartment-shim.js",
61
+ "./lockdown-shim.js": {
62
+ "xs": "./src-xs/lockdown-shim.js",
63
+ "default": "./lockdown-shim.js"
64
+ },
65
+ "./compartment-shim.js": {
66
+ "xs": "./src-xs/compartment-shim.js",
67
+ "default": "./compartment-shim.js"
68
+ },
62
69
  "./console-shim.js": "./console-shim.js",
63
70
  "./package.json": "./package.json"
64
71
  },
@@ -74,16 +81,16 @@
74
81
  "prepare": "npm run clean && npm run build",
75
82
  "qt": "ava",
76
83
  "test": "tsd && ava",
77
- "test:xs": "xst dist/ses.umd.js test/_lockdown-safe.js",
84
+ "test:xs": "xst dist/ses.umd.js test/_lockdown-safe.js && node scripts/generate-test-xs.js && xst tmp/test-xs.js && rm -rf tmp",
78
85
  "postpack": "git clean -f '*.d.ts*' '*.tsbuildinfo'"
79
86
  },
80
87
  "dependencies": {
81
- "@endo/env-options": "^1.1.7"
88
+ "@endo/env-options": "^1.1.8"
82
89
  },
83
90
  "devDependencies": {
84
- "@endo/compartment-mapper": "^1.3.1",
85
- "@endo/module-source": "^1.1.1",
86
- "@endo/test262-runner": "^0.1.42",
91
+ "@endo/compartment-mapper": "^1.5.0",
92
+ "@endo/module-source": "^1.2.0",
93
+ "@endo/test262-runner": "^0.1.44",
87
94
  "ava": "^6.1.3",
88
95
  "babel-eslint": "^10.1.0",
89
96
  "c8": "^7.14.0",
@@ -93,10 +100,10 @@
93
100
  "eslint-config-prettier": "^9.1.0",
94
101
  "eslint-plugin-eslint-comments": "^3.2.0",
95
102
  "eslint-plugin-import": "^2.29.1",
96
- "prettier": "^3.2.5",
103
+ "prettier": "^3.3.3",
97
104
  "terser": "^5.16.6",
98
105
  "tsd": "^0.31.2",
99
- "typescript": "~5.6.2"
106
+ "typescript": "~5.6.3"
100
107
  },
101
108
  "files": [
102
109
  "./*.d.ts",
@@ -203,5 +210,5 @@
203
210
  "typeCoverage": {
204
211
  "atLeast": 81.17
205
212
  },
206
- "gitHead": "c242c28a68d1af29475150e44b5f3e9d0feda8cd"
213
+ "gitHead": "e0683e0bfdbfc84351af332c9e78813d7b67ef89"
207
214
  }
@@ -0,0 +1,69 @@
1
+ import { objectHasOwnProperty } from './commons.js';
2
+
3
+ /**
4
+ * @import {Reporter} from './reporting-types.js'
5
+ */
6
+
7
+ /**
8
+ * Delete `obj[prop]` or at least make it harmless.
9
+ *
10
+ * If the property was not expected, then emit a reporter-dependent warning
11
+ * to bring attention to this case, so someone can determine what to do with it.
12
+ *
13
+ * If the property to be deleted is a function's `.prototype` property, this
14
+ * will normally be because the function was supposed to be a
15
+ * - builtin method or non-constructor function
16
+ * - arrow function
17
+ * - concise method
18
+ *
19
+ * all of whom are not supposed to have a `.prototype` property. Nevertheless,
20
+ * on some platforms (like older versions of Hermes), or as a result of
21
+ * some shim-based mods to the primordials (like core-js?), some of these
22
+ * functions may accidentally be more like `function` functions with
23
+ * an undeletable `.prototype` property. In these cases, if we can
24
+ * set the value of that bogus `.prototype` property to `undefined`,
25
+ * we do so, issuing a warning, rather than failing to initialize ses.
26
+ *
27
+ * @param {object} obj
28
+ * @param {PropertyKey} prop
29
+ * @param {boolean} known If deletion is expected, don't warn
30
+ * @param {string} subPath Used for warning messages
31
+ * @param {Reporter} reporter Where to issue warning or error.
32
+ * @returns {void}
33
+ */
34
+ export const cauterizeProperty = (
35
+ obj,
36
+ prop,
37
+ known,
38
+ subPath,
39
+ { warn, error },
40
+ ) => {
41
+ // Either the object lacks a permit or the object doesn't match the
42
+ // permit.
43
+ // If the permit is specifically false, not merely undefined,
44
+ // this is a property we expect to see because we know it exists in
45
+ // some environments and we have expressly decided to exclude it.
46
+ // Any other disallowed property is one we have not audited and we log
47
+ // that we are removing it so we know to look into it, as happens when
48
+ // the language evolves new features to existing intrinsics.
49
+ if (!known) {
50
+ warn(`Removing ${subPath}`);
51
+ }
52
+ try {
53
+ delete obj[prop];
54
+ } catch (err) {
55
+ if (objectHasOwnProperty(obj, prop)) {
56
+ if (typeof obj === 'function' && prop === 'prototype') {
57
+ obj.prototype = undefined;
58
+ if (obj.prototype === undefined) {
59
+ warn(`Tolerating undeletable ${subPath} === undefined`);
60
+ return;
61
+ }
62
+ }
63
+ error(`failed to delete ${subPath}`, err);
64
+ } else {
65
+ error(`deleting ${subPath} threw`, err);
66
+ }
67
+ throw err;
68
+ }
69
+ };
package/src/commons.js CHANGED
@@ -1,17 +1,19 @@
1
- /* global globalThis */
2
- /* eslint-disable no-restricted-globals */
3
-
4
1
  /**
5
- * commons.js
6
- * Declare shorthand functions. Sharing these declarations across modules
7
- * improves on consistency and minification. Unused declarations are
8
- * dropped by the tree shaking process.
2
+ * @module Captures native intrinsics during initialization, so vetted shims
3
+ * (running between initialization of SES and calling lockdown) are free to
4
+ * modify the environment without compromising the integrity of SES. For
5
+ * example, a vetted shim can modify Object.assign because we capture and
6
+ * export Object and assign here, then never again consult Object to get its
7
+ * assign property.
9
8
  *
10
- * We capture these, not just for brevity, but for security. If any code
11
- * modifies Object to change what 'assign' points to, the Compartment shim
12
- * would be corrupted.
9
+ * This pattern of use is enforced by eslint rules no-restricted-globals and
10
+ * no-polymorphic-call.
11
+ * We maintain the list of restricted globals in ../package.json.
13
12
  */
14
13
 
14
+ /* global globalThis */
15
+ /* eslint-disable no-restricted-globals */
16
+
15
17
  // We cannot use globalThis as the local name since it would capture the
16
18
  // lexical name.
17
19
  const universalThis = globalThis;
@@ -267,12 +269,6 @@ export const finalizationRegistryUnregister =
267
269
  export const getConstructorOf = fn =>
268
270
  reflectGet(getPrototypeOf(fn), 'constructor');
269
271
 
270
- /**
271
- * immutableObject
272
- * An immutable (frozen) empty object that is safe to share.
273
- */
274
- export const immutableObject = freeze(create(null));
275
-
276
272
  /**
277
273
  * isObject tests whether a value is an object.
278
274
  * Today, this is equivalent to:
@@ -305,6 +301,12 @@ export const isObject = value => Object(value) === value;
305
301
  */
306
302
  export const isError = value => value instanceof FERAL_ERROR;
307
303
 
304
+ /**
305
+ * @template T
306
+ * @param {T} x
307
+ */
308
+ export const identity = x => x;
309
+
308
310
  // The original unsafe untamed eval function, which must not escape.
309
311
  // Sample at module initialization time, which is before lockdown can
310
312
  // repair it. Use it only to build powerless abstractions.
@@ -2,12 +2,21 @@ import { globalThis } from './commons.js';
2
2
  import { makeCompartmentConstructor } from './compartment.js';
3
3
  import { tameFunctionToString } from './tame-function-tostring.js';
4
4
  import { getGlobalIntrinsics } from './intrinsics.js';
5
+ import { chooseReporter } from './reporting.js';
5
6
 
6
7
  const markVirtualizedNativeFunction = tameFunctionToString();
7
8
 
9
+ const muteReporter = chooseReporter('none');
10
+
8
11
  // @ts-ignore Compartment is definitely on globalThis.
9
12
  globalThis.Compartment = makeCompartmentConstructor(
10
13
  makeCompartmentConstructor,
11
- getGlobalIntrinsics(globalThis),
14
+ // Any reporting that would need to be done should have already been done
15
+ // during `lockdown()`.
16
+ // See https://github.com/endojs/endo/pull/2624#discussion_r1840979770
17
+ getGlobalIntrinsics(globalThis, muteReporter),
12
18
  markVirtualizedNativeFunction,
19
+ {
20
+ enforceNew: true,
21
+ },
13
22
  );
@@ -1,3 +1,40 @@
1
+ /**
2
+ * @module Provides the mechanism to create a Compartment constructor that
3
+ * can provide either shim-specific or native XS features depending on
4
+ * the __native__ constructor option.
5
+ * This is necessary because a native Compartment can handle native ModuleSource
6
+ * but cannot handle shim-specific pre-compiled ModuleSources like the JSON
7
+ * representation of a module that Compartment Mapper can put in bundles.
8
+ * Pre-compiling ModuleSource during bundling helps avoid paying the cost
9
+ * of importing Babel and transforming ESM syntax to a form that can be
10
+ * confined by the shim, which is prohibitively expensive for a web runtime
11
+ * and for XS _without this adapter_.
12
+ *
13
+ * Since any invocation of the Compartment constructor may occur standing
14
+ * on a native-flavor or shim-flavor compartment, we create parallel compartment
15
+ * constructor trees for compartments created with the Compartment constructor
16
+ * of a specific compartment.
17
+ *
18
+ * A compartment's importHook, importNowHook, moduleMapHook, and the modules
19
+ * map itself may provide module descriptors that address another compartment,
20
+ * using a compartment instance as a token indicating the compartment the
21
+ * module should be loaded or initialized in.
22
+ * Consequently, the compartment instance must be a suitable token for the
23
+ * underlying native-flavor or shim-flavor compartment.
24
+ * We are not in a position to fidddle with the native compartments behavior,
25
+ * so adapted compartments use the identity of the native compartment.
26
+ * We replace all of the methods of the native compartment prototype with
27
+ * thunks that choose behavior based on whether the compartment was
28
+ * constructed with the __native__ option.
29
+ * The SES shim associates a compartment with its private fields using a weak
30
+ * map exported by ../src/compartment.js and held closely by ses by the
31
+ * enforcement of explicit exports in package.json, since Node.js 12.11.0.
32
+ *
33
+ * Evaluating ./compartment.js does not have global side-effects.
34
+ * We defer modification of the global environment until the evaluation
35
+ * of ./compartment-shim.js.
36
+ */
37
+
1
38
  // @ts-check
2
39
  /* eslint-disable no-underscore-dangle */
3
40
  /// <reference types="ses">
@@ -6,8 +43,10 @@ import {
6
43
  Map,
7
44
  TypeError,
8
45
  WeakMap,
46
+ arrayFlatMap,
9
47
  assign,
10
48
  defineProperties,
49
+ identity,
11
50
  promiseThen,
12
51
  toStringTagSymbol,
13
52
  weakmapGet,
@@ -19,7 +58,7 @@ import {
19
58
  setGlobalObjectMutableProperties,
20
59
  setGlobalObjectEvaluators,
21
60
  } from './global-object.js';
22
- import { assert, assertEqual } from './error/assert.js';
61
+ import { assert, assertEqual, q } from './error/assert.js';
23
62
  import { sharedGlobalPropertyNames } from './permits.js';
24
63
  import { load, loadNow } from './module-load.js';
25
64
  import { link } from './module-link.js';
@@ -27,7 +66,7 @@ import { getDeferredExports } from './module-proxy.js';
27
66
  import { compartmentEvaluate } from './compartment-evaluate.js';
28
67
  import { makeSafeEvaluator } from './make-safe-evaluator.js';
29
68
 
30
- /** @import {ModuleDescriptor} from '../types.js' */
69
+ /** @import {ModuleDescriptor, ModuleExportsNamespace} from '../types.js' */
31
70
 
32
71
  // moduleAliases associates every public module exports namespace with its
33
72
  // corresponding compartment and specifier so they can be used to link modules
@@ -171,7 +210,9 @@ defineProperties(InertCompartment, {
171
210
  * @param {MakeCompartmentConstructor} targetMakeCompartmentConstructor
172
211
  * @param {Record<string, any>} intrinsics
173
212
  * @param {(object: object) => void} markVirtualizedNativeFunction
174
- * @param {Compartment} [parentCompartment]
213
+ * @param {object} [options]
214
+ * @param {Compartment} [options.parentCompartment]
215
+ * @param {boolean} [options.enforceNew]
175
216
  * @returns {Compartment['constructor']}
176
217
  */
177
218
 
@@ -184,7 +225,7 @@ defineProperties(InertCompartment, {
184
225
  // positional arguments, this function detects the temporary sigil __options__
185
226
  // on the first argument and coerces compartments arguments into a single
186
227
  // compartments object.
187
- const compartmentOptions = (...args) => {
228
+ export const compartmentOptions = (...args) => {
188
229
  if (args.length === 0) {
189
230
  return {};
190
231
  }
@@ -229,10 +270,10 @@ export const makeCompartmentConstructor = (
229
270
  targetMakeCompartmentConstructor,
230
271
  intrinsics,
231
272
  markVirtualizedNativeFunction,
232
- parentCompartment = undefined,
273
+ { parentCompartment = undefined, enforceNew = false } = {},
233
274
  ) => {
234
275
  function Compartment(...args) {
235
- if (new.target === undefined) {
276
+ if (enforceNew && new.target === undefined) {
236
277
  throw TypeError(
237
278
  "Class constructor Compartment cannot be invoked without 'new'",
238
279
  );
@@ -252,7 +293,10 @@ export const makeCompartmentConstructor = (
252
293
  importMetaHook,
253
294
  __noNamespaceBox__: noNamespaceBox = false,
254
295
  } = compartmentOptions(...args);
255
- const globalTransforms = [...transforms, ...__shimTransforms__];
296
+ const globalTransforms = arrayFlatMap(
297
+ [transforms, __shimTransforms__],
298
+ identity,
299
+ );
256
300
  const endowments = { __proto__: null, ...endowmentsOption };
257
301
  const moduleMap = { __proto__: null, ...moduleMapOption };
258
302
 
@@ -297,6 +341,43 @@ export const makeCompartmentConstructor = (
297
341
 
298
342
  assign(globalObject, endowments);
299
343
 
344
+ /**
345
+ * In support dynamic import in a module source loaded by this compartment,
346
+ * like `await import(importSpecifier)`, induces this compartment to import
347
+ * a module, returning a promise for the resulting module exports
348
+ * namespace.
349
+ * Unlike `compartment.import`, never creates a box object for the
350
+ * namespace as that behavior is deprecated and inconsistent with the
351
+ * standard behavior of dynamic import.
352
+ * Obliges the caller to resolve import specifiers to their corresponding
353
+ * full specifier.
354
+ * That is, every module must have its own dynamic import function that
355
+ * closes over the surrounding module's full module specifier and calls
356
+ * through to this function.
357
+ * @param {string} fullSpecifier - A full specifier is a key in the
358
+ * compartment's module memo.
359
+ * The method `compartment.import` accepts a full specifier, but dynamic
360
+ * import accepts an import specifier and resolves it to a full specifier
361
+ * relative to the calling module's full specifier.
362
+ * @returns {Promise<ModuleExportsNamespace>}
363
+ */
364
+ const compartmentImport = async fullSpecifier => {
365
+ if (typeof resolveHook !== 'function') {
366
+ throw TypeError(
367
+ `Compartment does not support dynamic import: no configured resolveHook for compartment ${q(name)}`,
368
+ );
369
+ }
370
+ await load(privateFields, moduleAliases, this, fullSpecifier);
371
+ const { execute, exportsProxy } = link(
372
+ privateFields,
373
+ moduleAliases,
374
+ this,
375
+ fullSpecifier,
376
+ );
377
+ execute();
378
+ return exportsProxy;
379
+ };
380
+
300
381
  weakmapSet(privateFields, this, {
301
382
  name: `${name}`,
302
383
  globalTransforms,
@@ -314,6 +395,7 @@ export const makeCompartmentConstructor = (
314
395
  instances,
315
396
  parentCompartment,
316
397
  noNamespaceBox,
398
+ compartmentImport,
317
399
  });
318
400
  }
319
401
 
@@ -23,8 +23,10 @@ import {
23
23
  severeEnablements,
24
24
  } from './enablements.js';
25
25
 
26
+ /** @import {Reporter} from './reporting-types.js' */
27
+
26
28
  /**
27
- * For a special set of properties defined in the `enablement` whitelist,
29
+ * For a special set of properties defined in the `enablement` list,
28
30
  * `enablePropertyOverrides` ensures that the effect of freezing does not
29
31
  * suppress the ability to override these properties on derived objects by
30
32
  * simple assignment.
@@ -75,11 +77,13 @@ import {
75
77
  *
76
78
  * @param {Record<string, any>} intrinsics
77
79
  * @param {'min' | 'moderate' | 'severe'} overrideTaming
80
+ * @param {Reporter} reporter
78
81
  * @param {Iterable<string | symbol>} [overrideDebug]
79
82
  */
80
83
  export default function enablePropertyOverrides(
81
84
  intrinsics,
82
85
  overrideTaming,
86
+ { warn },
83
87
  overrideDebug = [],
84
88
  ) {
85
89
  const debugProperties = new Set(overrideDebug);
@@ -109,8 +113,7 @@ export default function enablePropertyOverrides(
109
113
  this[prop] = newValue;
110
114
  } else {
111
115
  if (isDebug) {
112
- // eslint-disable-next-line @endo/no-polymorphic-call
113
- console.error(TypeError(`Override property ${prop}`));
116
+ warn(TypeError(`Override property ${prop}`));
114
117
  }
115
118
  defineProperty(this, prop, {
116
119
  value: newValue,
@@ -1,7 +1,7 @@
1
1
  import { toStringTagSymbol, iteratorSymbol } from './commons.js';
2
2
 
3
3
  /**
4
- * @file Exports {@code enablements}, a recursively defined
4
+ * @module Exports {@code enablements}, a recursively defined
5
5
  * JSON record defining the optimum set of intrinsics properties
6
6
  * that need to be "repaired" before hardening is applied on
7
7
  * enviromments subject to the override mistake.
@@ -62,9 +62,9 @@ Before repair or `lockdown`, we assume there is some prior "system" console boun
62
62
 
63
63
  The default `{ consoleTaming: 'safe' }` setting replaces the system console with a root console that does use all these side tables to generate a more informative log. This root console wraps the prior system console. This root console outputs its log information only by invoking this wrapped system console, which therefore determines how this log information is made available to the external world. To support determinism, we will also need to support a no-op console setting, as explained at [deterministic handling of adversarial code calling console.log with a Proxy #1852](https://github.com/Agoric/agoric-sdk/issues/1852) and [Need no-op console setting for determinism #487](https://github.com/Agoric/SES-shim/issues/487).
64
64
 
65
- SES considers both `assert` and `console` to be powerful objects, appearing initially in the start compartment, and not whitelisted for implicit propagation to created compartments. Rather, we recommend an endowment pattern where the global `assert` is passed forward as is, but only filtered forms of the `console` are. As compartments create each other in a tree, they create a corresponding filtering tree of consoles. Information sent to any compartment's console is then sent up the filtering tree. Only information that survives all the filters in its path arrive at the root console, producing log output. The others have no effect. Given the expected pattern of a compartment per package, the per-compartment console filter is effectly a topic filter, treating the package identity as a topic. We plan to also support coordinated stack-frame filters, as explained at [Need source-prefix-based stackframe filter #488](https://github.com/Agoric/SES-shim/issues/488).
65
+ SES considers both `assert` and `console` to be powerful objects, appearing initially in the start compartment, and not permitted for implicit propagation to created compartments. Rather, we recommend an endowment pattern where the global `assert` is passed forward as-is, but only filtered forms of the `console` are. As compartments create each other in a tree, they create a corresponding filtering tree of consoles. Information sent to any compartment's console is then sent up the filtering tree. Only information that survives all the filters in its path arrive at the root console, producing log output. The others have no effect. Given the expected pattern of a compartment per package, the per-compartment console filter is effectly a topic filter, treating the package identity as a topic. We plan to also support coordinated stack-frame filters, as explained at [Need source-prefix-based stackframe filter #488](https://github.com/Agoric/SES-shim/issues/488).
66
66
 
67
- For security and determinism, we normally reason from the *in-band frame of reference* where the console logging output does not exist, is not an effect, and `console` operations are write-only. Within this frame of reference, the `assert` and `console` powers are not very powerful. They are almost as safe as the whitelisted powerless shared primordials, which is why we're willing to recommend this endowment pattern be habitual.
67
+ For security and determinism, we normally reason from the *in-band frame of reference* where the console logging output does not exist, is not an effect, and `console` operations are write-only. Within this frame of reference, the `assert` and `console` powers are not very powerful. They are almost as safe as the permitted, powerless, shared primordials, which is why we're willing to recommend this endowment pattern be habitual.
68
68
 
69
69
  ## Hiding and Revealing Distributed Diagnostic Information
70
70