ses 1.4.1 → 1.5.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/src/commons.js CHANGED
@@ -133,6 +133,10 @@ export const { prototype: weakmapPrototype } = WeakMap;
133
133
  export const { prototype: weaksetPrototype } = WeakSet;
134
134
  export const { prototype: functionPrototype } = Function;
135
135
  export const { prototype: promisePrototype } = Promise;
136
+ export const { prototype: generatorPrototype } = getPrototypeOf(
137
+ // eslint-disable-next-line no-empty-function, func-names
138
+ function* () {},
139
+ );
136
140
 
137
141
  export const typedArrayPrototype = getPrototypeOf(Uint8Array.prototype);
138
142
 
@@ -191,6 +195,9 @@ export const stringEndsWith = uncurryThis(stringPrototype.endsWith);
191
195
  export const stringIncludes = uncurryThis(stringPrototype.includes);
192
196
  export const stringIndexOf = uncurryThis(stringPrototype.indexOf);
193
197
  export const stringMatch = uncurryThis(stringPrototype.match);
198
+ export const generatorNext = uncurryThis(generatorPrototype.next);
199
+ export const generatorThrow = uncurryThis(generatorPrototype.throw);
200
+
194
201
  /**
195
202
  * @type { &
196
203
  * ((thisArg: string, searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string) => string) &
@@ -217,6 +224,7 @@ export const weaksetAdd = uncurryThis(weaksetPrototype.add);
217
224
  export const weaksetHas = uncurryThis(weaksetPrototype.has);
218
225
  //
219
226
  export const functionToString = uncurryThis(functionPrototype.toString);
227
+ export const functionBind = uncurryThis(bind);
220
228
  //
221
229
  const { all } = Promise;
222
230
  export const promiseAll = promises => apply(all, Promise, [promises]);
@@ -294,3 +302,61 @@ export const noEvalEvaluate = () => {
294
302
  // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_NO_EVAL.md
295
303
  throw TypeError('Cannot eval with evalTaming set to "noEval" (SES_NO_EVAL)');
296
304
  };
305
+
306
+ // ////////////////// FERAL_STACK_GETTER FERAL_STACK_SETTER ////////////////////
307
+
308
+ const er1StackDesc = getOwnPropertyDescriptor(Error('er1'), 'stack');
309
+ const er2StackDesc = getOwnPropertyDescriptor(TypeError('er2'), 'stack');
310
+
311
+ let feralStackGetter;
312
+ let feralStackSetter;
313
+ if (er1StackDesc && er2StackDesc && er1StackDesc.get) {
314
+ // We should only encounter this case on v8 because of its problematic
315
+ // error own stack accessor behavior.
316
+ // Note that FF/SpiderMonkey, Moddable/XS, and the error stack proposal
317
+ // all inherit a stack accessor property from Error.prototype, which is
318
+ // great. That case needs no heroics to secure.
319
+ if (
320
+ // In the v8 case as we understand it, all errors have an own stack
321
+ // accessor property, but within the same realm, all these accessor
322
+ // properties have the same getter and have the same setter.
323
+ // This is therefore the case that we repair.
324
+ typeof er1StackDesc.get === 'function' &&
325
+ er1StackDesc.get === er2StackDesc.get &&
326
+ typeof er1StackDesc.set === 'function' &&
327
+ er1StackDesc.set === er2StackDesc.set
328
+ ) {
329
+ // Otherwise, we have own stack accessor properties that are outside
330
+ // our expectations, that therefore need to be understood better
331
+ // before we know how to repair them.
332
+ feralStackGetter = freeze(er1StackDesc.get);
333
+ feralStackSetter = freeze(er1StackDesc.set);
334
+ } else {
335
+ // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_UNEXPECTED_ERROR_OWN_STACK_ACCESSOR.md
336
+ throw TypeError(
337
+ 'Unexpected Error own stack accessor functions (SES_UNEXPECTED_ERROR_OWN_STACK_ACCESSOR)',
338
+ );
339
+ }
340
+ }
341
+
342
+ /**
343
+ * If on a v8 with the problematic error own stack accessor behavior,
344
+ * `FERAL_STACK_GETTER` will be the shared getter of all those accessors
345
+ * and `FERAL_STACK_SETTER` will be the shared setter. On any platform
346
+ * without this problem, `FERAL_STACK_GETTER` and `FERAL_STACK_SETTER` are
347
+ * both `undefined`.
348
+ *
349
+ * @type {(() => any) | undefined}
350
+ */
351
+ export const FERAL_STACK_GETTER = feralStackGetter;
352
+
353
+ /**
354
+ * If on a v8 with the problematic error own stack accessor behavior,
355
+ * `FERAL_STACK_GETTER` will be the shared getter of all those accessors
356
+ * and `FERAL_STACK_SETTER` will be the shared setter. On any platform
357
+ * without this problem, `FERAL_STACK_GETTER` and `FERAL_STACK_SETTER` are
358
+ * both `undefined`.
359
+ *
360
+ * @type {((newValue: any) => void) | undefined}
361
+ */
362
+ export const FERAL_STACK_SETTER = feralStackSetter;
@@ -22,7 +22,7 @@ import {
22
22
  setGlobalObjectEvaluators,
23
23
  } from './global-object.js';
24
24
  import { sharedGlobalPropertyNames } from './permits.js';
25
- import { load } from './module-load.js';
25
+ import { load, loadNow } from './module-load.js';
26
26
  import { link } from './module-link.js';
27
27
  import { getDeferredExports } from './module-proxy.js';
28
28
  import { assert } from './error/assert.js';
@@ -160,7 +160,7 @@ export const CompartmentPrototype = {
160
160
  }
161
161
 
162
162
  assertModuleHooks(this);
163
-
163
+ loadNow(privateFields, moduleAliases, this, specifier);
164
164
  return compartmentImportNow(/** @type {Compartment} */ (this), specifier);
165
165
  },
166
166
  };
@@ -209,6 +209,7 @@ export const makeCompartmentConstructor = (
209
209
  __shimTransforms__ = [],
210
210
  resolveHook,
211
211
  importHook,
212
+ importNowHook,
212
213
  moduleMapHook,
213
214
  importMetaHook,
214
215
  } = options;
@@ -285,6 +286,7 @@ export const makeCompartmentConstructor = (
285
286
  safeEvaluate,
286
287
  resolveHook,
287
288
  importHook,
289
+ importNowHook,
288
290
  moduleMap,
289
291
  moduleMapHook,
290
292
  importMetaHook,
@@ -35,12 +35,21 @@ import {
35
35
  weakmapHas,
36
36
  weakmapSet,
37
37
  AggregateError,
38
+ getOwnPropertyDescriptors,
39
+ ownKeys,
40
+ create,
41
+ objectPrototype,
42
+ objectHasOwnProperty,
38
43
  } from '../commons.js';
39
44
  import { an, bestEffortStringify } from './stringify-utils.js';
40
45
  import './types.js';
41
46
  import './internal-types.js';
42
47
  import { makeNoteLogArgsArrayKit } from './note-log-args.js';
43
48
 
49
+ /**
50
+ * @import {BaseAssert, Assert, AssertionFunctions, AssertionUtilities, StringablePayload, DetailsToken, MakeAssert} from '../../types.js'
51
+ */
52
+
44
53
  // For our internal debugging purposes, uncomment
45
54
  // const internalDebugConsole = console;
46
55
 
@@ -49,7 +58,7 @@ import { makeNoteLogArgsArrayKit } from './note-log-args.js';
49
58
  /** @type {WeakMap<StringablePayload, any>} */
50
59
  const declassifiers = new WeakMap();
51
60
 
52
- /** @type {AssertQuote} */
61
+ /** @type {AssertionUtilities['quote']} */
53
62
  const quote = (payload, spaces = undefined) => {
54
63
  const result = freeze({
55
64
  toString: freeze(() => bestEffortStringify(payload, spaces)),
@@ -62,19 +71,7 @@ freeze(quote);
62
71
  const canBeBare = freeze(/^[\w:-]( ?[\w:-])*$/);
63
72
 
64
73
  /**
65
- * Embed a string directly into error details without wrapping punctuation.
66
- * To avoid injection attacks that exploit quoting confusion, this must NEVER
67
- * be used with data that is possibly attacker-controlled.
68
- * As a further safeguard, we fall back to quoting any input that is not a
69
- * string of sufficiently word-like parts separated by isolated spaces (rather
70
- * than throwing an exception, which could hide the original problem for which
71
- * explanatory details are being constructed---i.e., ``` assert.details`...` ```
72
- * should never be the source of a new exception, nor should an attempt to
73
- * render its output, although we _could_ instead decide to handle the latter
74
- * by inline replacement similar to that of `bestEffortStringify` for producing
75
- * rendered messages like `(an object) was tagged "[Unsafe bare string]"`).
76
- *
77
- * @type {AssertQuote}
74
+ * @type {AssertionUtilities['bare']}
78
75
  */
79
76
  const bare = (payload, spaces = undefined) => {
80
77
  if (typeof payload !== 'string' || !regexpTest(canBeBare, payload)) {
@@ -160,7 +157,7 @@ freeze(DetailsTokenProto.toString);
160
157
  * of them should be uses where the template literal has no redacted
161
158
  * substitution values. In those cases, the two are equivalent.
162
159
  *
163
- * @type {DetailsTag}
160
+ * @type {AssertionUtilities['details']}
164
161
  */
165
162
  const redactedDetails = (template, ...args) => {
166
163
  // Keep in mind that the vast majority of calls to `details` creates
@@ -169,7 +166,7 @@ const redactedDetails = (template, ...args) => {
169
166
  // all the work to happen only if needed, for example, if an assertion fails.
170
167
  const detailsToken = freeze({ __proto__: DetailsTokenProto });
171
168
  weakmapSet(hiddenDetailsMap, detailsToken, { template, args });
172
- return detailsToken;
169
+ return /** @type {DetailsToken} */ (/** @type {unknown} */ (detailsToken));
173
170
  };
174
171
  freeze(redactedDetails);
175
172
 
@@ -184,7 +181,7 @@ freeze(redactedDetails);
184
181
  * of safety. `unredactedDetails` also sacrifices the speed of `details`,
185
182
  * which is usually fine in debugging and testing.
186
183
  *
187
- * @type {DetailsTag}
184
+ * @type {AssertionUtilities['details']}
188
185
  */
189
186
  const unredactedDetails = (template, ...args) => {
190
187
  args = arrayMap(args, arg =>
@@ -255,12 +252,79 @@ const tagError = (err, optErrorName = err.name) => {
255
252
  };
256
253
 
257
254
  /**
258
- * @type {AssertMakeError}
255
+ * Make reasonable best efforts to make a `Passable` error.
256
+ * - `sanitizeError` will remove any "extraneous" own properties already added
257
+ * by the host,
258
+ * such as `fileName`,`lineNumber` on FireFox or `line` on Safari.
259
+ * - If any such "extraneous" properties were removed, `sanitizeError` will
260
+ * annotate
261
+ * the error with them, so they still appear on the causal console
262
+ * log output for diagnostic purposes, but not be otherwise visible.
263
+ * - `sanitizeError` will ensure that any expected properties already
264
+ * added by the host are data
265
+ * properties, converting accessor properties to data properties as needed,
266
+ * such as `stack` on v8 (Chrome, Brave, Edge?)
267
+ * - `sanitizeError` will freeze the error, preventing any correct engine from
268
+ * adding or
269
+ * altering any of the error's own properties `sanitizeError` is done.
270
+ *
271
+ * However, `sanitizeError` will not, for example, `harden`
272
+ * (i.e., deeply freeze)
273
+ * or ensure that the `cause` or `errors` property satisfy the `Passable`
274
+ * constraints. The purpose of `sanitizeError` is only to protect against
275
+ * mischief the host may have already added to the error as created,
276
+ * not to ensure that the error is actually Passable. For that,
277
+ * see `toPassableError` in `@endo/pass-style`.
278
+ *
279
+ * @param {Error} error
280
+ */
281
+ export const sanitizeError = error => {
282
+ const descs = getOwnPropertyDescriptors(error);
283
+ const {
284
+ name: _nameDesc,
285
+ message: _messageDesc,
286
+ errors: _errorsDesc = undefined,
287
+ cause: _causeDesc = undefined,
288
+ stack: _stackDesc = undefined,
289
+ ...restDescs
290
+ } = descs;
291
+
292
+ const restNames = ownKeys(restDescs);
293
+ if (restNames.length >= 1) {
294
+ for (const name of restNames) {
295
+ delete error[name];
296
+ }
297
+ const droppedNote = create(objectPrototype, restDescs);
298
+ // eslint-disable-next-line no-use-before-define
299
+ note(
300
+ error,
301
+ redactedDetails`originally with properties ${quote(droppedNote)}`,
302
+ );
303
+ }
304
+ for (const name of ownKeys(error)) {
305
+ // @ts-expect-error TS still confused by symbols as property names
306
+ const desc = descs[name];
307
+ if (desc && objectHasOwnProperty(desc, 'get')) {
308
+ defineProperty(error, name, {
309
+ value: error[name], // invoke the getter to convert to data property
310
+ });
311
+ }
312
+ }
313
+ freeze(error);
314
+ };
315
+
316
+ /**
317
+ * @type {AssertionUtilities['error']}
259
318
  */
260
319
  const makeError = (
261
320
  optDetails = redactedDetails`Assert failed`,
262
321
  errConstructor = globalThis.Error,
263
- { errorName = undefined, cause = undefined, errors = undefined } = {},
322
+ {
323
+ errorName = undefined,
324
+ cause = undefined,
325
+ errors = undefined,
326
+ sanitize = true,
327
+ } = {},
264
328
  ) => {
265
329
  if (typeof optDetails === 'string') {
266
330
  // If it is a string, use it as the literal part of the template so
@@ -299,6 +363,9 @@ const makeError = (
299
363
  if (errorName !== undefined) {
300
364
  tagError(error, errorName);
301
365
  }
366
+ if (sanitize) {
367
+ sanitizeError(error);
368
+ }
302
369
  // The next line is a particularly fruitful place to put a breakpoint.
303
370
  return error;
304
371
  };
@@ -322,7 +389,7 @@ const { addLogArgs, takeLogArgsArray } = makeNoteLogArgsArrayKit();
322
389
  */
323
390
  const hiddenNoteCallbackArrays = new WeakMap();
324
391
 
325
- /** @type {AssertNote} */
392
+ /** @type {AssertionUtilities['note']} */
326
393
  const note = (error, detailsNote) => {
327
394
  if (typeof detailsNote === 'string') {
328
395
  // If it is a string, use it as the literal part of the template so
@@ -403,7 +470,7 @@ const makeAssert = (optRaise = undefined, unredacted = false) => {
403
470
  const details = unredacted ? unredactedDetails : redactedDetails;
404
471
  const assertFailedDetails = details`Check failed`;
405
472
 
406
- /** @type {AssertFail} */
473
+ /** @type {AssertionFunctions['fail']} */
407
474
  const fail = (
408
475
  optDetails = assertFailedDetails,
409
476
  errConstructor = undefined,
@@ -411,13 +478,14 @@ const makeAssert = (optRaise = undefined, unredacted = false) => {
411
478
  ) => {
412
479
  const reason = makeError(optDetails, errConstructor, options);
413
480
  if (optRaise !== undefined) {
481
+ // @ts-ignore returns `never` doesn't mean it isn't callable
414
482
  optRaise(reason);
415
483
  }
416
484
  throw reason;
417
485
  };
418
486
  freeze(fail);
419
487
 
420
- /** @type {FailTag} */
488
+ /** @type {AssertionUtilities['Fail']} */
421
489
  const Fail = (template, ...args) => fail(details(template, ...args));
422
490
 
423
491
  // Don't freeze or export `baseAssert` until we add methods.
@@ -433,7 +501,7 @@ const makeAssert = (optRaise = undefined, unredacted = false) => {
433
501
  flag || fail(optDetails, errConstructor, options);
434
502
  }
435
503
 
436
- /** @type {AssertEqual} */
504
+ /** @type {AssertionFunctions['equal']} */
437
505
  const equal = (
438
506
  actual,
439
507
  expected,
@@ -450,7 +518,7 @@ const makeAssert = (optRaise = undefined, unredacted = false) => {
450
518
  };
451
519
  freeze(equal);
452
520
 
453
- /** @type {AssertTypeof} */
521
+ /** @type {AssertionFunctions['typeof']} */
454
522
  const assertTypeof = (specimen, typename, optDetails) => {
455
523
  // This will safely fall through if typename is not a string,
456
524
  // which is what we want.
@@ -469,7 +537,7 @@ const makeAssert = (optRaise = undefined, unredacted = false) => {
469
537
  };
470
538
  freeze(assertTypeof);
471
539
 
472
- /** @type {AssertString} */
540
+ /** @type {AssertionFunctions['string']} */
473
541
  const assertString = (specimen, optDetails = undefined) =>
474
542
  assertTypeof(specimen, 'string', optDetails);
475
543
 
@@ -5,6 +5,8 @@ import { freeze } from '../commons.js';
5
5
  import { makeAssert } from './assert.js';
6
6
  import './types.js';
7
7
 
8
+ /** @import {Assert} from '../../types.js' */
9
+
8
10
  let abandon;
9
11
  // Sniff for host-provided functions for terminating the enclosing UOPT (see
10
12
  // below). Currently it only checks for the `process.abort` or `process.exit`
@@ -21,6 +21,8 @@ import {
21
21
  toStringTagSymbol,
22
22
  } from '../commons.js';
23
23
 
24
+ /** @import {StringablePayload} from '../../types.js' */
25
+
24
26
  /**
25
27
  * Joins English terms with commas and an optional conjunction.
26
28
  *
@@ -58,14 +58,14 @@ export const tameConsole = (
58
58
  typeof globalThis.console !== 'undefined'
59
59
  ? globalThis.console
60
60
  : typeof globalThis.print === 'function'
61
- ? // Make a good-enough console for eshost (including only functions that
62
- // log at a specific level with no special argument interpretation).
63
- // https://console.spec.whatwg.org/#logging
64
- (p => freeze({ debug: p, log: p, info: p, warn: p, error: p }))(
65
- // eslint-disable-next-line no-undef
66
- wrapLogger(globalThis.print),
67
- )
68
- : undefined
61
+ ? // Make a good-enough console for eshost (including only functions that
62
+ // log at a specific level with no special argument interpretation).
63
+ // https://console.spec.whatwg.org/#logging
64
+ (p => freeze({ debug: p, log: p, info: p, warn: p, error: p }))(
65
+ // eslint-disable-next-line no-undef
66
+ wrapLogger(globalThis.print),
67
+ )
68
+ : undefined
69
69
  );
70
70
 
71
71
  // Upgrade a log-only console (as in `eshost -h SpiderMonkey`).