ses 0.15.13 → 0.15.16

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/index.d.ts CHANGED
@@ -24,6 +24,7 @@ export interface LockdownOptions {
24
24
  localeTaming?: 'safe' | 'unsafe';
25
25
  consoleTaming?: 'safe' | 'unsafe';
26
26
  errorTrapping?: 'platform' | 'exit' | 'abort' | 'report' | 'none';
27
+ unhandledRejectionTrapping?: 'report' | 'none';
27
28
  errorTaming?: 'safe' | 'unsafe';
28
29
  dateTaming?: 'safe' | 'unsafe'; // deprecated
29
30
  mathTaming?: 'safe' | 'unsafe'; // deprecated
@@ -37,16 +38,16 @@ export interface LockdownOptions {
37
38
 
38
39
  export type Lockdown = (options?: LockdownOptions) => void;
39
40
 
40
- export type __LiveExportsMap__ = Record<string, [string, boolean]>;
41
- export type __FixedExportsMap__ = Record<string, [string]>;
41
+ export type __LiveExportMap__ = Record<string, [string, boolean]>;
42
+ export type __FixedExportMap__ = Record<string, [string]>;
42
43
 
43
44
  export interface PrecompiledStaticModuleInterface {
44
45
  imports: Array<string>;
45
46
  exports: Array<string>;
46
47
  reexports: Array<string>;
47
48
  __syncModuleProgram__: string;
48
- __liveExportsMap__: __LiveExportsMap__;
49
- __fixedExportsMap__: __FixedExportsMap__;
49
+ __liveExportMap__: __LiveExportMap__;
50
+ __fixedExportMap__: __FixedExportMap__;
50
51
  }
51
52
 
52
53
  export interface ThirdPartyStaticModuleInterface {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ses",
3
- "version": "0.15.13",
3
+ "version": "0.15.16",
4
4
  "description": "Hardened JavaScript for Fearless Cooperation",
5
5
  "keywords": [
6
6
  "lockdown",
@@ -59,19 +59,19 @@
59
59
  "test:platform-compatability": "node test/package/test.cjs"
60
60
  },
61
61
  "devDependencies": {
62
- "@endo/compartment-mapper": "^0.7.3",
63
- "@endo/eslint-config": "^0.4.8",
64
- "@endo/static-module-record": "^0.7.2",
65
- "@endo/test262-runner": "^0.1.24",
62
+ "@endo/compartment-mapper": "^0.7.6",
63
+ "@endo/eslint-config": "^0.5.0",
64
+ "@endo/static-module-record": "^0.7.5",
65
+ "@endo/test262-runner": "^0.1.27",
66
66
  "ava": "^3.12.1",
67
67
  "babel-eslint": "^10.0.3",
68
68
  "c8": "^7.7.3",
69
- "eslint": "^7.23.0",
69
+ "eslint": "^7.32.0",
70
70
  "eslint-config-airbnb-base": "^14.0.0",
71
71
  "eslint-config-prettier": "^6.9.0",
72
72
  "eslint-plugin-eslint-comments": "^3.1.2",
73
- "eslint-plugin-import": "^2.19.1",
74
- "eslint-plugin-prettier": "^3.1.2",
73
+ "eslint-plugin-import": "^2.26.0",
74
+ "eslint-plugin-prettier": "^3.4.1",
75
75
  "prettier": "^1.19.1",
76
76
  "sinon": "8.0.4",
77
77
  "terser": "^4.8.0",
@@ -179,5 +179,5 @@
179
179
  ],
180
180
  "timeout": "2m"
181
181
  },
182
- "gitHead": "ada5203fd64e6828dca74895fd74588e08925d97"
182
+ "gitHead": "7be9306df5e5eae280134cbbaf0d3886b4e51536"
183
183
  }
package/src/commons.js CHANGED
@@ -20,6 +20,7 @@ export { universalThis as globalThis };
20
20
  export const {
21
21
  Array,
22
22
  Date,
23
+ FinalizationRegistry,
23
24
  Float32Array,
24
25
  JSON,
25
26
  Map,
@@ -157,7 +158,9 @@ export const typedArrayPrototype = getPrototypeOf(Uint8Array.prototype);
157
158
  * which only lives at
158
159
  * http://web.archive.org/web/20160805225710/http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
159
160
  *
160
- * @param {(thisArg: Object, ...args: any[]) => any} fn
161
+ * @template {Function} F
162
+ * @param {F} fn
163
+ * returns {(thisArg: ThisParameterType<F>, ...args: Parameters<F>) => ReturnType<F>}
161
164
  */
162
165
  export const uncurryThis = fn => (thisArg, ...args) => apply(fn, thisArg, args);
163
166
 
@@ -178,6 +181,8 @@ export const iterateArray = uncurryThis(arrayPrototype[iteratorSymbol]);
178
181
  export const mapSet = uncurryThis(mapPrototype.set);
179
182
  export const mapGet = uncurryThis(mapPrototype.get);
180
183
  export const mapHas = uncurryThis(mapPrototype.has);
184
+ export const mapDelete = uncurryThis(mapPrototype.delete);
185
+ export const mapEntries = uncurryThis(mapPrototype.entries);
181
186
  export const iterateMap = uncurryThis(mapPrototype[iteratorSymbol]);
182
187
  //
183
188
  export const setAdd = uncurryThis(setPrototype.add);
@@ -202,6 +207,7 @@ export const stringStartsWith = uncurryThis(stringPrototype.startsWith);
202
207
  export const iterateString = uncurryThis(stringPrototype[iteratorSymbol]);
203
208
  //
204
209
  export const weakmapDelete = uncurryThis(weakmapPrototype.delete);
210
+ /** @type {<K, V>(thisArg: WeakMap<K, V>, ...args: Parameters<WeakMap<K,V>['get']>) => ReturnType<WeakMap<K,V>['get']>} */
205
211
  export const weakmapGet = uncurryThis(weakmapPrototype.get);
206
212
  export const weakmapHas = uncurryThis(weakmapPrototype.has);
207
213
  export const weakmapSet = uncurryThis(weakmapPrototype.set);
@@ -216,6 +222,12 @@ const { all } = Promise;
216
222
  export const promiseAll = promises => apply(all, Promise, [promises]);
217
223
  export const promiseCatch = uncurryThis(promisePrototype.catch);
218
224
  export const promiseThen = uncurryThis(promisePrototype.then);
225
+ //
226
+ export const finalizationRegistryRegister =
227
+ FinalizationRegistry && uncurryThis(FinalizationRegistry.prototype.register);
228
+ export const finalizationRegistryUnregister =
229
+ FinalizationRegistry &&
230
+ uncurryThis(FinalizationRegistry.prototype.unregister);
219
231
 
220
232
  /**
221
233
  * getConstructorOf()
@@ -306,7 +306,7 @@ export const makeCompartmentConstructor = (
306
306
  assign(globalObject, endowments);
307
307
 
308
308
  weakmapSet(privateFields, this, {
309
- name,
309
+ name: `${name}`,
310
310
  globalTransforms,
311
311
  globalObject,
312
312
  knownScopeProxies,
@@ -172,15 +172,6 @@ const ErrorInfo = {
172
172
  };
173
173
  freeze(ErrorInfo);
174
174
 
175
- /**
176
- * The error annotations are sent to the baseConsole by calling some level
177
- * method. The 'debug' level seems best, because the Chrome console classifies
178
- * `debug` as verbose and does not show it by default. But we keep it symbolic
179
- * so we can change our mind. (On Node, `debug`, `log`, and `info` are aliases
180
- * for the same function and so will behave the same there.)
181
- */
182
- export const BASE_CONSOLE_LEVEL = 'debug';
183
-
184
175
  /** @type {MakeCausalConsole} */
185
176
  const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
186
177
  const {
@@ -207,34 +198,36 @@ const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
207
198
  };
208
199
 
209
200
  /**
201
+ * @param {LogSeverity} severity
210
202
  * @param {Error} error
211
203
  * @param {ErrorInfoKind} kind
212
204
  * @param {readonly any[]} logArgs
213
205
  * @param {Array<Error>} subErrorsSink
214
206
  */
215
- const logErrorInfo = (error, kind, logArgs, subErrorsSink) => {
207
+ const logErrorInfo = (severity, error, kind, logArgs, subErrorsSink) => {
216
208
  const errorTag = tagError(error);
217
209
  const errorName =
218
210
  kind === ErrorInfo.MESSAGE ? `${errorTag}:` : `${errorTag} ${kind}`;
219
211
  const argTags = extractErrorArgs(logArgs, subErrorsSink);
220
212
  // eslint-disable-next-line @endo/no-polymorphic-call
221
- baseConsole[BASE_CONSOLE_LEVEL](errorName, ...argTags);
213
+ baseConsole[severity](errorName, ...argTags);
222
214
  };
223
215
 
224
216
  /**
225
217
  * Logs the `subErrors` within a group name mentioning `optTag`.
226
218
  *
219
+ * @param {LogSeverity} severity
227
220
  * @param {Error[]} subErrors
228
221
  * @param {string | undefined} optTag
229
222
  * @returns {void}
230
223
  */
231
- const logSubErrors = (subErrors, optTag = undefined) => {
224
+ const logSubErrors = (severity, subErrors, optTag = undefined) => {
232
225
  if (subErrors.length === 0) {
233
226
  return;
234
227
  }
235
228
  if (subErrors.length === 1 && optTag === undefined) {
236
229
  // eslint-disable-next-line no-use-before-define
237
- logError(subErrors[0]);
230
+ logError(severity, subErrors[0]);
238
231
  return;
239
232
  }
240
233
  let label;
@@ -251,7 +244,7 @@ const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
251
244
  try {
252
245
  for (const subError of subErrors) {
253
246
  // eslint-disable-next-line no-use-before-define
254
- logError(subError);
247
+ logError(severity, subError);
255
248
  }
256
249
  } finally {
257
250
  // eslint-disable-next-line @endo/no-polymorphic-call
@@ -261,19 +254,20 @@ const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
261
254
 
262
255
  const errorsLogged = new WeakSet();
263
256
 
264
- /** @type {NoteCallback} */
265
- const noteCallback = (error, noteLogArgs) => {
257
+ /** @type {(severity: LogSeverity) => NoteCallback} */
258
+ const makeNoteCallback = severity => (error, noteLogArgs) => {
266
259
  const subErrors = [];
267
260
  // Annotation arrived after the error has already been logged,
268
261
  // so just log the annotation immediately, rather than remembering it.
269
- logErrorInfo(error, ErrorInfo.NOTE, noteLogArgs, subErrors);
270
- logSubErrors(subErrors, tagError(error));
262
+ logErrorInfo(severity, error, ErrorInfo.NOTE, noteLogArgs, subErrors);
263
+ logSubErrors(severity, subErrors, tagError(error));
271
264
  };
272
265
 
273
266
  /**
267
+ * @param {LogSeverity} severity
274
268
  * @param {Error} error
275
269
  */
276
- const logError = error => {
270
+ const logError = (severity, error) => {
277
271
  if (weaksetHas(errorsLogged, error)) {
278
272
  return;
279
273
  }
@@ -281,17 +275,26 @@ const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
281
275
  weaksetAdd(errorsLogged, error);
282
276
  const subErrors = [];
283
277
  const messageLogArgs = takeMessageLogArgs(error);
284
- const noteLogArgsArray = takeNoteLogArgsArray(error, noteCallback);
278
+ const noteLogArgsArray = takeNoteLogArgsArray(
279
+ error,
280
+ makeNoteCallback(severity),
281
+ );
285
282
  // Show the error's most informative error message
286
283
  if (messageLogArgs === undefined) {
287
284
  // If there is no message log args, then just show the message that
288
285
  // the error itself carries.
289
286
  // eslint-disable-next-line @endo/no-polymorphic-call
290
- baseConsole[BASE_CONSOLE_LEVEL](`${errorTag}:`, error.message);
287
+ baseConsole[severity](`${errorTag}:`, error.message);
291
288
  } else {
292
289
  // If there is one, we take it to be strictly more informative than the
293
290
  // message string carried by the error, so show it *instead*.
294
- logErrorInfo(error, ErrorInfo.MESSAGE, messageLogArgs, subErrors);
291
+ logErrorInfo(
292
+ severity,
293
+ error,
294
+ ErrorInfo.MESSAGE,
295
+ messageLogArgs,
296
+ subErrors,
297
+ );
295
298
  }
296
299
  // After the message but before any other annotations, show the stack.
297
300
  let stackString = getStackString(error);
@@ -303,13 +306,13 @@ const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
303
306
  stackString += '\n';
304
307
  }
305
308
  // eslint-disable-next-line @endo/no-polymorphic-call
306
- baseConsole[BASE_CONSOLE_LEVEL](stackString);
309
+ baseConsole[severity](stackString);
307
310
  // Show the other annotations on error
308
311
  for (const noteLogArgs of noteLogArgsArray) {
309
- logErrorInfo(error, ErrorInfo.NOTE, noteLogArgs, subErrors);
312
+ logErrorInfo(severity, error, ErrorInfo.NOTE, noteLogArgs, subErrors);
310
313
  }
311
314
  // explain all the errors seen in the messages already emitted.
312
- logSubErrors(subErrors, errorTag);
315
+ logSubErrors(severity, subErrors, errorTag);
313
316
  };
314
317
 
315
318
  const levelMethods = arrayMap(consoleLevelMethods, ([level, _]) => {
@@ -322,7 +325,7 @@ const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
322
325
  // @ts-ignore
323
326
  // eslint-disable-next-line @endo/no-polymorphic-call
324
327
  baseConsole[level](...argTags);
325
- logSubErrors(subErrors);
328
+ logSubErrors(level, subErrors);
326
329
  };
327
330
  defineProperty(levelMethod, 'name', { value: level });
328
331
  return [level, freeze(levelMethod)];
@@ -3,6 +3,7 @@
3
3
  import { TypeError, globalThis } from '../commons.js';
4
4
  import { loggedErrorHandler as defaultHandler } from './assert.js';
5
5
  import { makeCausalConsole } from './console.js';
6
+ import { makeRejectionHandlers } from './unhandled-rejection.js';
6
7
  import './types.js';
7
8
  import './internal-types.js';
8
9
 
@@ -17,20 +18,19 @@ const originalConsole = console;
17
18
  *
18
19
  * @param {"safe" | "unsafe"} consoleTaming
19
20
  * @param {"platform" | "exit" | "abort" | "report" | "none"} [errorTrapping]
21
+ * @param {"report" | "none"} [unhandledRejectionTrapping]
20
22
  * @param {GetStackString=} optGetStackString
21
23
  */
22
24
  export const tameConsole = (
23
25
  consoleTaming = 'safe',
24
26
  errorTrapping = 'platform',
27
+ unhandledRejectionTrapping = 'report',
25
28
  optGetStackString = undefined,
26
29
  ) => {
27
30
  if (consoleTaming !== 'safe' && consoleTaming !== 'unsafe') {
28
31
  throw new TypeError(`unrecognized consoleTaming ${consoleTaming}`);
29
32
  }
30
33
 
31
- if (consoleTaming === 'unsafe') {
32
- return { console: originalConsole };
33
- }
34
34
  let loggedErrorHandler;
35
35
  if (optGetStackString === undefined) {
36
36
  loggedErrorHandler = defaultHandler;
@@ -40,7 +40,10 @@ export const tameConsole = (
40
40
  getStackString: optGetStackString,
41
41
  };
42
42
  }
43
- const causalConsole = makeCausalConsole(originalConsole, loggedErrorHandler);
43
+ const ourConsole =
44
+ consoleTaming === 'unsafe'
45
+ ? originalConsole
46
+ : makeCausalConsole(originalConsole, loggedErrorHandler);
44
47
 
45
48
  // Attach platform-specific error traps such that any error that gets thrown
46
49
  // at top-of-turn (the bottom of stack) will get logged by our causal
@@ -53,40 +56,85 @@ export const tameConsole = (
53
56
  // utter that. That unnecessary shim forces the whole bundle into sloppy mode,
54
57
  // which in turn breaks SES's strict mode invariant.
55
58
 
59
+ // Disable the polymorphic check for the rest of this file. It's too noisy
60
+ // when dealing with platform APIs.
61
+ /* eslint-disable @endo/no-polymorphic-call */
62
+
56
63
  // Node.js
57
64
  if (errorTrapping !== 'none' && globalThis.process !== undefined) {
58
- // eslint-disable-next-line @endo/no-polymorphic-call
59
65
  globalThis.process.on('uncaughtException', error => {
60
66
  // causalConsole is born frozen so not vulnerable to method tampering.
61
- // eslint-disable-next-line @endo/no-polymorphic-call
62
- causalConsole.error(error);
67
+ ourConsole.error(error);
63
68
  if (errorTrapping === 'platform' || errorTrapping === 'exit') {
64
- // eslint-disable-next-line @endo/no-polymorphic-call
65
69
  globalThis.process.exit(globalThis.process.exitCode || -1);
66
70
  } else if (errorTrapping === 'abort') {
67
- // eslint-disable-next-line @endo/no-polymorphic-call
68
71
  globalThis.process.abort();
69
72
  }
70
73
  });
71
74
  }
72
75
 
76
+ if (
77
+ unhandledRejectionTrapping !== 'none' &&
78
+ globalThis.process !== undefined
79
+ ) {
80
+ const handleRejection = reason => {
81
+ // 'platform' and 'report' just log the reason.
82
+ ourConsole.error('SES_UNHANDLED_REJECTION:', reason);
83
+ };
84
+ // Maybe track unhandled promise rejections.
85
+ const h = makeRejectionHandlers(handleRejection);
86
+ if (h) {
87
+ // Rejection handlers are supported.
88
+ globalThis.process.on('unhandledRejection', h.unhandledRejectionHandler);
89
+ globalThis.process.on('rejectionHandled', h.rejectionHandledHandler);
90
+ globalThis.process.on('exit', h.processTerminationHandler);
91
+ }
92
+ }
93
+
73
94
  // Browser
74
95
  if (
75
96
  errorTrapping !== 'none' &&
76
97
  globalThis.window !== undefined &&
77
98
  globalThis.window.addEventListener !== undefined
78
99
  ) {
79
- // eslint-disable-next-line @endo/no-polymorphic-call
80
100
  globalThis.window.addEventListener('error', event => {
81
- // eslint-disable-next-line @endo/no-polymorphic-call
82
101
  event.preventDefault();
83
- // eslint-disable-next-line @endo/no-polymorphic-call
84
- causalConsole.error(event.error);
102
+ // 'platform' and 'report' just log the reason.
103
+ ourConsole.error(event.error);
85
104
  if (errorTrapping === 'exit' || errorTrapping === 'abort') {
86
105
  globalThis.window.location.href = `about:blank`;
87
106
  }
88
107
  });
89
108
  }
90
109
 
91
- return { console: causalConsole };
110
+ if (
111
+ unhandledRejectionTrapping !== 'none' &&
112
+ globalThis.window !== undefined &&
113
+ globalThis.window.addEventListener !== undefined
114
+ ) {
115
+ const handleRejection = reason => {
116
+ ourConsole.error('SES_UNHANDLED_REJECTION:', reason);
117
+ };
118
+
119
+ const h = makeRejectionHandlers(handleRejection);
120
+ if (h) {
121
+ // Rejection handlers are supported.
122
+ globalThis.window.addEventListener('unhandledrejection', event => {
123
+ event.preventDefault();
124
+ h.unhandledRejectionHandler(event.reason, event.promise);
125
+ });
126
+
127
+ globalThis.window.addEventListener('rejectionhandled', event => {
128
+ event.preventDefault();
129
+ h.rejectionHandledHandler(event.promise);
130
+ });
131
+
132
+ globalThis.window.addEventListener('beforeunload', _event => {
133
+ h.processTerminationHandler();
134
+ });
135
+ }
136
+ }
137
+ /* eslint-enable @endo/no-polymorphic-call */
138
+
139
+ return { console: ourConsole };
92
140
  };
@@ -10,8 +10,9 @@ import {
10
10
  import { NativeErrors } from '../whitelist.js';
11
11
  import { tameV8ErrorConstructor } from './tame-v8-error-constructor.js';
12
12
 
13
- // Present on at least FF. Proposed by Error-proposal. Not on SES whitelist
14
- // so grab it before it is removed.
13
+ // Present on at least FF and XS. Proposed by Error-proposal. The original
14
+ // is dangerous, so tameErrorConstructor replaces it with a safe one.
15
+ // We grab the original here before it gets replaced.
15
16
  const stackDesc = getOwnPropertyDescriptor(FERAL_ERROR.prototype, 'stack');
16
17
  const stackGetter = stackDesc && stackDesc.get;
17
18
 
@@ -74,16 +75,6 @@ export default function tameErrorConstructor(
74
75
  const SharedError = makeErrorConstructor({ powers: 'none' });
75
76
  defineProperties(ErrorPrototype, {
76
77
  constructor: { value: SharedError },
77
- /* TODO
78
- stack: {
79
- get() {
80
- return '';
81
- },
82
- set(_) {
83
- // ignore
84
- },
85
- },
86
- */
87
78
  });
88
79
 
89
80
  for (const NativeError of NativeErrors) {
@@ -154,7 +145,70 @@ export default function tameErrorConstructor(
154
145
  errorTaming,
155
146
  stackFiltering,
156
147
  );
148
+ } else if (errorTaming === 'unsafe') {
149
+ // v8 has too much magic around their 'stack' own property for it to
150
+ // coexist cleanly with this accessor. So only install it on non-v8
151
+
152
+ // Error.prototype.stack property as proposed at
153
+ // https://tc39.es/proposal-error-stacks/
154
+ // with the fix proposed at
155
+ // https://github.com/tc39/proposal-error-stacks/issues/46
156
+ // On others, this still protects from the override mistake,
157
+ // essentially like enable-property-overrides.js would
158
+ // once this accessor property itself is frozen, as will happen
159
+ // later during lockdown.
160
+ //
161
+ // However, there is here a change from the intent in the current
162
+ // state of the proposal. If experience tells us whether this change
163
+ // is a good idea, we should modify the proposal accordingly. There is
164
+ // much code in the world that assumes `error.stack` is a string. So
165
+ // where the proposal accommodates secure operation by making the
166
+ // property optional, we instead accommodate secure operation by
167
+ // having the secure form always return only the stable part, the
168
+ // stringified error instance, and omitting all the frame information
169
+ // rather than omitting the property.
170
+ defineProperties(ErrorPrototype, {
171
+ stack: {
172
+ get() {
173
+ return initialGetStackString(this);
174
+ },
175
+ set(newValue) {
176
+ defineProperties(this, {
177
+ stack: {
178
+ value: newValue,
179
+ writable: true,
180
+ enumerable: true,
181
+ configurable: true,
182
+ },
183
+ });
184
+ },
185
+ },
186
+ });
187
+ } else {
188
+ // v8 has too much magic around their 'stack' own property for it to
189
+ // coexist cleanly with this accessor. So only install it on non-v8
190
+ defineProperties(ErrorPrototype, {
191
+ stack: {
192
+ get() {
193
+ // https://github.com/tc39/proposal-error-stacks/issues/46
194
+ // allows this to not add an unpleasant newline. Otherwise
195
+ // we should fix this.
196
+ return `${this}`;
197
+ },
198
+ set(newValue) {
199
+ defineProperties(this, {
200
+ stack: {
201
+ value: newValue,
202
+ writable: true,
203
+ enumerable: true,
204
+ configurable: true,
205
+ },
206
+ });
207
+ },
208
+ },
209
+ });
157
210
  }
211
+
158
212
  return {
159
213
  '%InitialGetStackString%': initialGetStackString,
160
214
  '%InitialError%': InitialError,
@@ -0,0 +1,122 @@
1
+ // @ts-check
2
+ import {
3
+ FinalizationRegistry,
4
+ Map,
5
+ mapGet,
6
+ mapDelete,
7
+ WeakMap,
8
+ mapSet,
9
+ finalizationRegistryRegister,
10
+ weakmapSet,
11
+ weakmapGet,
12
+ mapEntries,
13
+ mapHas,
14
+ } from '../commons.js';
15
+
16
+ /**
17
+ * Create rejection-tracking machinery compatible with Node.js and browsers.
18
+ *
19
+ * Note that modern browsers *prevent* access to the 'unhandledrejection' and
20
+ * 'rejectionhandled' events needed:
21
+ * - in cross-origin mode, like when served from file://
22
+ * - in the browser console (interactively typed-in code)
23
+ * - in the debugger
24
+ *
25
+ * Then, they just look like: `Uncaught (in promise) Error: ...` and don't
26
+ * implement the machinery.
27
+ *
28
+ * The solution is to serve your web page from an http:// or https:// web server
29
+ * and execute actual code.
30
+ *
31
+ * @param {(reason: unknown) => void} reportReason report the reason for an
32
+ * unhandled rejection.
33
+ */
34
+ export const makeRejectionHandlers = reportReason => {
35
+ if (FinalizationRegistry === undefined) {
36
+ return undefined;
37
+ }
38
+
39
+ /** @typedef {number} ReasonId */
40
+ let lastReasonId = 0;
41
+
42
+ /** @type {Map<ReasonId, unknown>} */
43
+ const idToReason = new Map();
44
+
45
+ /** @type {(() => void) | undefined} */
46
+ let cancelChecking;
47
+
48
+ const removeReasonId = reasonId => {
49
+ mapDelete(idToReason, reasonId);
50
+ if (cancelChecking && idToReason.size === 0) {
51
+ // No more unhandled rejections to check, just cancel the check.
52
+ cancelChecking();
53
+ cancelChecking = undefined;
54
+ }
55
+ };
56
+
57
+ /** @type {WeakMap<Promise, ReasonId>} */
58
+ const promiseToReasonId = new WeakMap();
59
+
60
+ /**
61
+ * Clean up and report the reason for a GCed unhandled rejection.
62
+ *
63
+ * @param {ReasonId} heldReasonId
64
+ */
65
+ const finalizeDroppedPromise = heldReasonId => {
66
+ if (mapHas(idToReason)) {
67
+ const reason = mapGet(idToReason, heldReasonId);
68
+ removeReasonId(heldReasonId);
69
+ reportReason(reason);
70
+ }
71
+ };
72
+
73
+ /** @type {FinalizationRegistry<ReasonId>} */
74
+ const promiseToReason = new FinalizationRegistry(finalizeDroppedPromise);
75
+
76
+ /**
77
+ * Track a rejected promise and its corresponding reason if there is no
78
+ * rejection handler synchronously attached.
79
+ *
80
+ * @param {unknown} reason
81
+ * @param {Promise} pr
82
+ */
83
+ const unhandledRejectionHandler = (reason, pr) => {
84
+ lastReasonId += 1;
85
+ const reasonId = lastReasonId;
86
+
87
+ // Update bookkeeping.
88
+ mapSet(idToReason, reasonId, reason);
89
+ weakmapSet(promiseToReasonId, pr, reasonId);
90
+ finalizationRegistryRegister(promiseToReason, pr, reasonId, pr);
91
+ };
92
+
93
+ /**
94
+ * Deal with the addition of a handler to a previously rejected promise.
95
+ *
96
+ * Just remove it from our list. Let the FinalizationRegistry or
97
+ * processTermination report any GCed unhandled rejected promises.
98
+ *
99
+ * @param {Promise} pr
100
+ */
101
+ const rejectionHandledHandler = pr => {
102
+ const reasonId = weakmapGet(promiseToReasonId, pr);
103
+ removeReasonId(reasonId);
104
+ };
105
+
106
+ /**
107
+ * Report all the unhandled rejections, now that we are abruptly terminating
108
+ * the agent cluster.
109
+ */
110
+ const processTerminationHandler = () => {
111
+ for (const [reasonId, reason] of mapEntries(idToReason)) {
112
+ removeReasonId(reasonId);
113
+ reportReason(reason);
114
+ }
115
+ };
116
+
117
+ return {
118
+ rejectionHandledHandler,
119
+ unhandledRejectionHandler,
120
+ processTerminationHandler,
121
+ };
122
+ };
@@ -160,6 +160,10 @@ export const repairIntrinsics = (options = {}) => {
160
160
  const {
161
161
  errorTaming = getenv('LOCKDOWN_ERROR_TAMING', 'safe'),
162
162
  errorTrapping = getenv('LOCKDOWN_ERROR_TRAPPING', 'platform'),
163
+ unhandledRejectionTrapping = getenv(
164
+ 'LOCKDOWN_UNHANDLED_REJECTION_TRAPPING',
165
+ 'report',
166
+ ),
163
167
  regExpTaming = getenv('LOCKDOWN_REGEXP_TAMING', 'safe'),
164
168
  localeTaming = getenv('LOCKDOWN_LOCALE_TAMING', 'safe'),
165
169
  consoleTaming = getenv('LOCKDOWN_CONSOLE_TAMING', 'safe'),
@@ -286,18 +290,23 @@ export const repairIntrinsics = (options = {}) => {
286
290
 
287
291
  const intrinsics = finalIntrinsics();
288
292
 
289
- // Wrap console unless suppressed.
290
- // At the moment, the console is considered a host power in the start
291
- // compartment, and not a primordial. Hence it is absent from the whilelist
292
- // and bypasses the intrinsicsCollector.
293
+ /**
294
+ * Wrap console unless suppressed.
295
+ * At the moment, the console is considered a host power in the start
296
+ * compartment, and not a primordial. Hence it is absent from the whilelist
297
+ * and bypasses the intrinsicsCollector.
298
+ *
299
+ * @type {((error: any) => string | undefined) | undefined}
300
+ */
293
301
  let optGetStackString;
294
302
  if (errorTaming !== 'unsafe') {
295
303
  optGetStackString = intrinsics['%InitialGetStackString%'];
296
304
  }
297
305
  const consoleRecord = tameConsole(
298
- // @ts-ignore tameConsole does its own input validation
306
+ // @ts-expect-error tameConsole does its own input validation
299
307
  consoleTaming,
300
308
  errorTrapping,
309
+ unhandledRejectionTrapping,
301
310
  optGetStackString,
302
311
  );
303
312
  globalThis.console = /** @type {Console} */ (consoleRecord.console);