ses 1.4.1 → 1.6.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/permits.js CHANGED
@@ -3,6 +3,8 @@
3
3
 
4
4
  import { arrayPush } from './commons.js';
5
5
 
6
+ /** @import {GenericErrorConstructor} from '../types.js' */
7
+
6
8
  /**
7
9
  * @file Exports {@code whitelist}, a recursively defined
8
10
  * JSON record enumerating all intrinsics and their properties
@@ -1111,8 +1113,14 @@ export const permitted = {
1111
1113
  Int8Array: TypedArray('%Int8ArrayPrototype%'),
1112
1114
  Uint16Array: TypedArray('%Uint16ArrayPrototype%'),
1113
1115
  Uint32Array: TypedArray('%Uint32ArrayPrototype%'),
1114
- Uint8Array: TypedArray('%Uint8ArrayPrototype%'),
1115
1116
  Uint8ClampedArray: TypedArray('%Uint8ClampedArrayPrototype%'),
1117
+ Uint8Array: {
1118
+ ...TypedArray('%Uint8ArrayPrototype%'),
1119
+ // https://github.com/tc39/proposal-arraybuffer-base64
1120
+ fromBase64: fn,
1121
+ // https://github.com/tc39/proposal-arraybuffer-base64
1122
+ fromHex: fn,
1123
+ },
1116
1124
 
1117
1125
  '%BigInt64ArrayPrototype%': TypedArrayPrototype('BigInt64Array'),
1118
1126
  '%BigUint64ArrayPrototype%': TypedArrayPrototype('BigUint64Array'),
@@ -1125,8 +1133,18 @@ export const permitted = {
1125
1133
  '%Int8ArrayPrototype%': TypedArrayPrototype('Int8Array'),
1126
1134
  '%Uint16ArrayPrototype%': TypedArrayPrototype('Uint16Array'),
1127
1135
  '%Uint32ArrayPrototype%': TypedArrayPrototype('Uint32Array'),
1128
- '%Uint8ArrayPrototype%': TypedArrayPrototype('Uint8Array'),
1129
1136
  '%Uint8ClampedArrayPrototype%': TypedArrayPrototype('Uint8ClampedArray'),
1137
+ '%Uint8ArrayPrototype%': {
1138
+ ...TypedArrayPrototype('Uint8Array'),
1139
+ // https://github.com/tc39/proposal-arraybuffer-base64
1140
+ setFromBase64: fn,
1141
+ // https://github.com/tc39/proposal-arraybuffer-base64
1142
+ setFromHex: fn,
1143
+ // https://github.com/tc39/proposal-arraybuffer-base64
1144
+ toBase64: fn,
1145
+ // https://github.com/tc39/proposal-arraybuffer-base64
1146
+ toHex: fn,
1147
+ },
1130
1148
 
1131
1149
  // *** Keyed Collections
1132
1150
 
@@ -5,6 +5,7 @@ import {
5
5
  getOwnPropertyDescriptors,
6
6
  defineProperties,
7
7
  arrayMap,
8
+ functionBind,
8
9
  } from './commons.js';
9
10
 
10
11
  /**
@@ -37,11 +38,9 @@ export const tameSymbolConstructor = () => {
37
38
  const OriginalSymbol = Symbol;
38
39
  const SymbolPrototype = OriginalSymbol.prototype;
39
40
 
40
- const SharedSymbol = {
41
- Symbol(description) {
42
- return OriginalSymbol(description);
43
- },
44
- }.Symbol;
41
+ // Bypass Hermes bug, fixed in: https://github.com/facebook/hermes/commit/00f18c89c720e1c34592bb85a1a8d311e6e99599
42
+ // Make a "copy" of the primordial [Symbol "constructor"](https://tc39.es/ecma262/#sec-symbol-description) which maintains all observable behavior. The primordial explicitly throws on `[[Construct]]` and has a `[[Call]]` which ignores the receiver. Binding also maintains the `toString` source as a native function. The `name` is restored below when copying own properties.
43
+ const SharedSymbol = functionBind(Symbol, undefined);
45
44
 
46
45
  defineProperties(SymbolPrototype, {
47
46
  constructor: {
package/types.d.ts CHANGED
@@ -25,7 +25,7 @@ export interface RepairOptions {
25
25
  consoleTaming?: 'safe' | 'unsafe';
26
26
  errorTrapping?: 'platform' | 'exit' | 'abort' | 'report' | 'none';
27
27
  unhandledRejectionTrapping?: 'report' | 'none';
28
- errorTaming?: 'safe' | 'unsafe';
28
+ errorTaming?: 'safe' | 'unsafe' | 'unsafe-debug';
29
29
  dateTaming?: 'safe' | 'unsafe'; // deprecated
30
30
  mathTaming?: 'safe' | 'unsafe'; // deprecated
31
31
  evalTaming?: 'safeEval' | 'unsafeEval' | 'noEval';
@@ -43,19 +43,23 @@ export type RepairIntrinsics = (options?: LockdownOptions) => void;
43
43
  export type HardenIntrinsics = () => void;
44
44
  export type Lockdown = (options?: LockdownOptions) => void;
45
45
 
46
+ export type ModuleExportsNamespace = Record<string, any>;
47
+
46
48
  export type __LiveExportMap__ = Record<string, [string, boolean]>;
47
49
  export type __FixedExportMap__ = Record<string, [string]>;
50
+ export type __ReexportMap__ = Record<string, Array<[string, string]>>;
48
51
 
49
- export interface PrecompiledStaticModuleInterface {
52
+ export interface PrecompiledModuleSource {
50
53
  imports: Array<string>;
51
54
  exports: Array<string>;
52
55
  reexports: Array<string>;
53
56
  __syncModuleProgram__: string;
54
57
  __liveExportMap__: __LiveExportMap__;
55
58
  __fixedExportMap__: __FixedExportMap__;
59
+ __reexportMap__: __ReexportMap__;
56
60
  }
57
61
 
58
- export interface ThirdPartyStaticModuleInterface {
62
+ export interface VirtualModuleSource {
59
63
  imports: Array<string>;
60
64
  exports: Array<string>;
61
65
  /**
@@ -68,41 +72,74 @@ export interface ThirdPartyStaticModuleInterface {
68
72
  ): void;
69
73
  }
70
74
 
71
- export type FinalStaticModuleType =
72
- | PrecompiledStaticModuleInterface
73
- | ThirdPartyStaticModuleInterface;
75
+ export type ModuleSource = PrecompiledModuleSource | VirtualModuleSource;
74
76
 
75
- export interface RedirectStaticModuleInterface {
76
- specifier: string;
77
- record?: FinalStaticModuleType;
77
+ export interface SourceModuleDescriptor {
78
+ source: string | ModuleSource;
79
+ specifier?: string;
78
80
  importMeta?: any;
81
+ compartment?: Compartment; // defaults to parent
82
+ }
83
+
84
+ export interface NamespaceModuleDescriptor {
85
+ namespace: string | ModuleExportsNamespace;
79
86
  compartment?: Compartment;
80
87
  }
81
88
 
82
- export type StaticModuleType =
83
- | RedirectStaticModuleInterface
84
- | FinalStaticModuleType;
89
+ // Deprecated in favor of SourceModuleDescriptor,
90
+ // but beware the change in default compartment.
91
+ export interface RecordModuleDescriptor {
92
+ specifier: string;
93
+ record?: ModuleSource;
94
+ importMeta?: any;
95
+ compartment?: Compartment; // defaults to self
96
+ }
85
97
 
86
- export type ModuleExportsNamespace = Record<string, any>;
98
+ export type ModuleDescriptor =
99
+ | SourceModuleDescriptor
100
+ | NamespaceModuleDescriptor
101
+ // To be deprecated:
102
+ | RecordModuleDescriptor
103
+ | ModuleExportsNamespace
104
+ | VirtualModuleSource
105
+ | PrecompiledModuleSource
106
+ | string;
107
+
108
+ // Deprecated type aliases:
109
+ export type PrecompiledStaticModuleInterface = PrecompiledModuleSource;
110
+ export type ThirdPartyStaticModuleInterface = VirtualModuleSource;
111
+ export type RedirectStaticModuleInterface = RecordModuleDescriptor;
112
+ export type FinalStaticModuleType = ModuleSource;
113
+ export type StaticModuleType = RedirectStaticModuleInterface | ModuleSource;
87
114
 
88
115
  export type Transform = (source: string) => string;
89
116
  export type ResolveHook = (
90
117
  importSpecifier: string,
91
118
  referrerSpecifier: string,
92
119
  ) => string;
93
- export type ModuleMap = Record<string, string | ModuleExportsNamespace>;
120
+ export type ModuleMap = Record<string, string | ModuleDescriptor>;
94
121
  export type ModuleMapHook = (
95
122
  moduleSpecifier: string,
96
- ) => string | ModuleExportsNamespace | void;
97
- export type ImportHook = (moduleSpecifier: string) => Promise<StaticModuleType>;
123
+ ) => ModuleDescriptor | undefined;
124
+ export type ImportHook = (moduleSpecifier: string) => Promise<ModuleDescriptor>;
125
+ export type ImportNowHook = (moduleSpecifier: string) => ModuleDescriptor;
126
+ export type ImportMetaHook = (
127
+ moduleSpecifier: string,
128
+ importMeta: Object,
129
+ ) => void;
98
130
 
99
131
  export interface CompartmentOptions {
100
132
  name?: string;
101
133
  transforms?: Array<Transform>;
102
134
  moduleMapHook?: ModuleMapHook;
103
135
  importHook?: ImportHook;
136
+ importNowHook?: ImportNowHook;
137
+ importMetaHook?: ImportMetaHook;
104
138
  resolveHook?: ResolveHook;
139
+ globals?: Map<string, any>;
140
+ modules?: Map<string, ModuleDescriptor>;
105
141
  __shimTransforms__?: Array<Transform>;
142
+ __noNamespaceBox__?: boolean;
106
143
  }
107
144
 
108
145
  export interface EvaluateOptions {
@@ -113,16 +150,49 @@ export interface EvaluateOptions {
113
150
  __rejectSomeDirectEvalExpressions__?: boolean;
114
151
  }
115
152
 
116
- // The DetailsToken is an empty object literal.
153
+ /**
154
+ * A call to the `details` template literal makes and returns a fresh details
155
+ * token, which is a frozen empty object associated with the arguments of that
156
+ * `details` template literal expression.
157
+ */
117
158
  export type DetailsToken = Record<any, never>;
159
+ /** Either a plain string, or made by the `details` template literal tag. */
118
160
  export type Details = string | DetailsToken;
119
161
 
120
162
  export interface AssertMakeErrorOptions {
163
+ /**
164
+ * Does not affect the error.name property. That remains determined by
165
+ * the constructor. Rather, the `errorName` determines how this error is
166
+ * identified in the causal console log's output.
167
+ */
121
168
  errorName?: string;
169
+
170
+ /**
171
+ * Discloses the error that caused this one, typically from a lower
172
+ * layer of abstraction. This is represented by a public `cause` data property
173
+ * on the error, not a hidden annotation.
174
+ */
122
175
  cause?: Error;
176
+
177
+ /**
178
+ * Normally only used when the ErrorConstuctor is `AggregateError`, to
179
+ * represent the set of prior errors aggregated together in this error,
180
+ * typically by `Promise.any`. But `makeError` allows it on any error.
181
+ * This is represented by a public `errors` data property on the error,
182
+ * not a hidden annotation.
183
+ */
123
184
  errors?: Error[];
185
+
186
+ /**
187
+ * Defaults to true. If true, `makeError` will apply `sanitizeError`
188
+ * to the error before returning it. See the comments on
189
+ * {@link sanitizeError}.
190
+ */
191
+ sanitize?: boolean;
124
192
  }
125
193
 
194
+ // TODO inline overloading
195
+
126
196
  type AssertTypeofBigint = (
127
197
  specimen: any,
128
198
  typeName: 'bigint',
@@ -173,62 +243,278 @@ export type AssertTypeof = AssertTypeofBigint &
173
243
  AssertTypeofSymbol &
174
244
  AssertTypeofUndefined;
175
245
 
176
- interface ToStringable {
246
+ interface StringablePayload {
177
247
  toString(): string;
178
248
  }
179
249
 
250
+ /**
251
+ * TypeScript does not treat `AggregateErrorConstructor` as a subtype of
252
+ * `ErrorConstructor`, which makes sense because their constructors
253
+ * have incompatible signatures. However, we want to parameterize some
254
+ * operations by any error constructor, including possible `AggregateError`.
255
+ * So we introduce `GenericErrorConstructor` as a common supertype. Any call
256
+ * to it to make an instance must therefore first case split on whether the
257
+ * constructor is an AggregateErrorConstructor or a normal ErrorConstructor.
258
+ */
180
259
  export type GenericErrorConstructor =
181
260
  | ErrorConstructor
182
261
  | AggregateErrorConstructor;
183
262
 
263
+ /**
264
+ * To make an `assert` which terminates some larger unit of computation
265
+ * like a transaction, vat, or process, call `makeAssert` with a `Raise`
266
+ * callback, where that callback actually performs that larger termination.
267
+ * If possible, the callback should also report its `reason` parameter as
268
+ * the alleged reason for the termination.
269
+ */
184
270
  export type Raise = (reason: Error) => void;
271
+
272
+ /**
273
+ * Makes and returns an `assert` function object that shares the bookkeeping
274
+ * state defined by this module with other `assert` function objects made by
275
+ * `makeAssert`. This state is per-module-instance and is exposed by the
276
+ * `loggedErrorHandler` above. We refer to `assert` as a "function object"
277
+ * because it can be called directly as a function, but also has methods that
278
+ * can be called.
279
+ *
280
+ * If `optRaise` is provided, the returned `assert` function object will call
281
+ * `optRaise(reason)` before throwing the error. This enables `optRaise` to
282
+ * engage in even more violent termination behavior, like terminating the vat,
283
+ * that prevents execution from reaching the following throw. However, if
284
+ * `optRaise` returns normally, which would be unusual, the throw following
285
+ * `optRaise(reason)` would still happen.
286
+ */
185
287
  // Behold: recursion.
186
288
  // eslint-disable-next-line no-use-before-define
187
289
  export type MakeAssert = (raise?: Raise, unredacted?: boolean) => Assert;
188
290
 
189
- export interface AssertionFunctions {
190
- (
191
- value: any,
192
- details?: Details,
193
- errConstructor?: GenericErrorConstructor,
194
- options?: AssertMakeErrorOptions,
195
- ): asserts value;
291
+ export type BaseAssert = (
292
+ /** The truthy/falsy value we're testing */
293
+ flag: any,
294
+ /** The details of what was asserted */
295
+ details?: Details,
296
+ /** An optional alternate error constructor to use */
297
+ errConstructor?: GenericErrorConstructor,
298
+ options?: AssertMakeErrorOptions,
299
+ ) => asserts flag;
300
+
301
+ export interface AssertionFunctions extends BaseAssert {
196
302
  typeof: AssertTypeof;
197
- equal(
198
- left: any,
199
- right: any,
303
+
304
+ /**
305
+ * The `assert.equal` method
306
+ *
307
+ * Assert that two values must be `Object.is`.
308
+ */
309
+ equal<T>(
310
+ /** What we received */
311
+ actual: unknown,
312
+ /** What we wanted */
313
+ expected: T,
314
+ /** The details of what was asserted */
200
315
  details?: Details,
316
+ /** An optional alternate error constructor to use */
201
317
  errConstructor?: GenericErrorConstructor,
202
318
  options?: AssertMakeErrorOptions,
203
- ): void;
204
- string(specimen: any, details?: Details): asserts specimen is string;
319
+ ): asserts actual is T;
320
+
321
+ /**
322
+ * The `assert.string` method.
323
+ *
324
+ * `assert.string(v)` is equivalent to `assert.typeof(v, 'string')`. We
325
+ * special case this one because it is the most frequently used.
326
+ *
327
+ * Assert an expected typeof result.
328
+ */
329
+ string(
330
+ specimen: any,
331
+ /** The details of what was asserted */
332
+ details?: Details,
333
+ ): asserts specimen is string;
334
+
335
+ /**
336
+ * The `assert.fail` method.
337
+ *
338
+ * Fail an assertion, recording full details to the console and
339
+ * raising an exception with a message in which `details` substitution values
340
+ * have been redacted.
341
+ *
342
+ * The optional `optDetails` can be a string for backwards compatibility
343
+ * with the nodejs assertion library.
344
+ */
205
345
  fail(
346
+ /** The details of what was asserted */
206
347
  details?: Details,
348
+ /** An optional alternate error constructor to use */
207
349
  errConstructor?: GenericErrorConstructor,
208
350
  options?: AssertMakeErrorOptions,
209
351
  ): never;
210
352
  }
211
353
 
212
354
  export interface AssertionUtilities {
355
+ /**
356
+ * Aka the `makeError` function as imported from `@endo/errors`
357
+ *
358
+ * Recording unredacted details for the console.
359
+ */
213
360
  error(
361
+ /** The details of what was asserted */
214
362
  details?: Details,
363
+ /** An optional alternate error constructor to use */
215
364
  errConstructor?: GenericErrorConstructor,
216
365
  options?: AssertMakeErrorOptions,
217
366
  ): Error;
367
+
368
+ /**
369
+ * Aka the `annotateError` function as imported from `@endo/errors`
370
+ *
371
+ * Annotate an error with details, potentially to be used by an
372
+ * augmented console such as the causal console of `console.js`, to
373
+ * provide extra information associated with logged errors.
374
+ */
218
375
  note(error: Error, details: Details): void;
376
+
377
+ /**
378
+ * Use the `details` function as a template literal tag to create
379
+ * informative error messages. The assertion functions take such messages
380
+ * as optional arguments:
381
+ * ```js
382
+ * assert(sky.isBlue(), details`${sky.color} should be "blue"`);
383
+ * ```
384
+ * or following the normal convention to locally rename `details` to `X`
385
+ * and `quote` to `q` like `const { details: X, quote: q } = assert;`:
386
+ * ```js
387
+ * assert(sky.isBlue(), X`${sky.color} should be "blue"`);
388
+ * ```
389
+ * However, note that in most cases it is preferable to instead use the `Fail`
390
+ * template literal tag (which has the same input signature as `details`
391
+ * but automatically creates and throws an error):
392
+ * ```js
393
+ * sky.isBlue() || Fail`${sky.color} should be "blue"`;
394
+ * ```
395
+ *
396
+ * The details template tag returns a `DetailsToken` object that can print
397
+ * itself with the formatted message in two ways.
398
+ * It will report full details to the console, but
399
+ * mask embedded substitution values with their typeof information in the thrown error
400
+ * to prevent revealing secrets up the exceptional path. In the example
401
+ * above, the thrown error may reveal only that `sky.color` is a string,
402
+ * whereas the same diagnostic printed to the console reveals that the
403
+ * sky was green. This masking can be disabled for an individual substitution value
404
+ * using `quote`.
405
+ *
406
+ * The `raw` property of an input template array is ignored, so a simple
407
+ * array of strings may be provided directly.
408
+ */
219
409
  details(
220
410
  template: TemplateStringsArray | string[],
221
411
  ...args: any
222
412
  ): DetailsToken;
413
+
414
+ /**
415
+ * Use the `Fail` function as a template literal tag to efficiently
416
+ * create and throw a `details`-style error only when a condition is not satisfied.
417
+ * ```js
418
+ * condition || Fail`...complaint...`;
419
+ * ```
420
+ * This avoids the overhead of creating usually-unnecessary errors like
421
+ * ```js
422
+ * assert(condition, details`...complaint...`);
423
+ * ```
424
+ * while improving readability over alternatives like
425
+ * ```js
426
+ * condition || assert.fail(details`...complaint...`);
427
+ * ```
428
+ *
429
+ * However, due to current weakness in TypeScript, static reasoning
430
+ * is less powerful with the `||` patterns than with an `assert` call.
431
+ * Until/unless https://github.com/microsoft/TypeScript/issues/51426 is fixed,
432
+ * for `||`-style assertions where this loss of static reasoning is a problem,
433
+ * instead express the assertion as
434
+ * ```js
435
+ * if (!condition) {
436
+ * Fail`...complaint...`;
437
+ * }
438
+ * ```
439
+ * or, if needed,
440
+ * ```js
441
+ * if (!condition) {
442
+ * // `throw` is noop since `Fail` throws, but it improves static analysis
443
+ * throw Fail`...complaint...`;
444
+ * }
445
+ * ```
446
+ */
223
447
  Fail(template: TemplateStringsArray | string[], ...args: any): never;
224
- quote(payload: any, spaces?: string | number): ToStringable;
225
- bare(payload: any, spaces?: string | number): ToStringable;
448
+
449
+ /**
450
+ * To "declassify" and quote a substitution value used in a
451
+ * ``` details`...` ``` template literal, enclose that substitution expression
452
+ * in a call to `quote`. This makes the value appear quoted
453
+ * (as if with `JSON.stringify`) in the message of the thrown error. The
454
+ * payload itself is still passed unquoted to the console as it would be
455
+ * without `quote`.
456
+ *
457
+ * For example, the following will reveal the expected sky color, but not the
458
+ * actual incorrect sky color, in the thrown error's message:
459
+ * ```js
460
+ * sky.color === expectedColor || Fail`${sky.color} should be ${quote(expectedColor)}`;
461
+ * ```
462
+ *
463
+ * The normal convention is to locally rename `details` to `X` and `quote` to `q`
464
+ * like `const { details: X, quote: q } = assert;`, so the above example would then be
465
+ * ```js
466
+ * sky.color === expectedColor || Fail`${sky.color} should be ${q(expectedColor)}`;
467
+ * ```
468
+ */
469
+ quote(
470
+ /** What to declassify */
471
+ payload: any,
472
+ spaces?: string | number,
473
+ ): /** The declassified and quoted payload */ StringablePayload;
474
+
475
+ /**
476
+ * Embed a string directly into error details without wrapping punctuation.
477
+ * To avoid injection attacks that exploit quoting confusion, this must NEVER
478
+ * be used with data that is possibly attacker-controlled.
479
+ * As a further safeguard, we fall back to quoting any input that is not a
480
+ * string of sufficiently word-like parts separated by isolated spaces (rather
481
+ * than throwing an exception, which could hide the original problem for which
482
+ * explanatory details are being constructed---i.e., ``` assert.details`...` ```
483
+ * should never be the source of a new exception, nor should an attempt to
484
+ * render its output, although we _could_ instead decide to handle the latter
485
+ * by inline replacement similar to that of `bestEffortStringify` for producing
486
+ * rendered messages like `(an object) was tagged "[Unsafe bare string]"`).
487
+ */
488
+ bare(
489
+ /** What to declassify */
490
+ payload: any,
491
+ spaces?: string | number,
492
+ ): /** The declassified payload without quotes (beware confusion hazard) */
493
+ StringablePayload;
226
494
  }
227
495
 
228
496
  export interface DeprecatedAssertionUtilities {
229
497
  makeAssert: MakeAssert;
230
498
  }
231
499
 
500
+ /**
501
+ * assert that expr is truthy, with an optional details to describe
502
+ * the assertion. It is a tagged template literal like
503
+ * ```js
504
+ * assert(expr, details`....`);`
505
+ * ```
506
+ *
507
+ * The literal portions of the template are assumed non-sensitive, as
508
+ * are the `typeof` types of the substitution values. These are
509
+ * assembled into the thrown error message. The actual contents of the
510
+ * substitution values are assumed sensitive, to be revealed to
511
+ * the console only. We assume only the virtual platform's owner can read
512
+ * what is written to the console, where the owner is in a privileged
513
+ * position over computation running on that platform.
514
+ *
515
+ * The optional `optDetails` can be a string for backwards compatibility
516
+ * with the nodejs assertion library.
517
+ */
232
518
  export type Assert = AssertionFunctions &
233
519
  AssertionUtilities &
234
520
  DeprecatedAssertionUtilities;
@@ -255,9 +541,12 @@ declare global {
255
541
  * code in a context bound to a new global creates a new compartment.
256
542
  */
257
543
  export class Compartment {
544
+ constructor(options?: CompartmentOptions & { __options__: true });
545
+
546
+ // Deprecated:
258
547
  constructor(
259
- globals?: Object,
260
- moduleMap?: ModuleMap,
548
+ globals?: Record<string, any> | undefined,
549
+ modules?: Record<string, ModuleDescriptor>,
261
550
  options?: CompartmentOptions,
262
551
  );
263
552