@metamask/snaps-execution-environments 0.27.1 → 0.29.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.
Files changed (66) hide show
  1. package/dist/common/BaseSnapExecutor.d.ts +1 -1
  2. package/dist/common/BaseSnapExecutor.js +18 -5
  3. package/dist/common/BaseSnapExecutor.js.map +1 -1
  4. package/dist/common/endowments/commonEndowmentFactory.d.ts +19 -0
  5. package/dist/common/endowments/commonEndowmentFactory.js +69 -0
  6. package/dist/common/endowments/commonEndowmentFactory.js.map +1 -0
  7. package/dist/common/endowments/crypto.js +4 -1
  8. package/dist/common/endowments/crypto.js.map +1 -1
  9. package/dist/common/endowments/date.d.ts +15 -0
  10. package/dist/common/endowments/date.js +39 -0
  11. package/dist/common/endowments/date.js.map +1 -0
  12. package/dist/common/endowments/index.d.ts +1 -1
  13. package/dist/common/endowments/index.js +6 -6
  14. package/dist/common/endowments/index.js.map +1 -1
  15. package/dist/common/endowments/interval.js +7 -4
  16. package/dist/common/endowments/interval.js.map +1 -1
  17. package/dist/common/endowments/math.js +2 -2
  18. package/dist/common/endowments/math.js.map +1 -1
  19. package/dist/common/endowments/network.d.ts +1 -41
  20. package/dist/common/endowments/network.js +9 -207
  21. package/dist/common/endowments/network.js.map +1 -1
  22. package/dist/common/endowments/textDecoder.d.ts +10 -0
  23. package/dist/common/endowments/textDecoder.js +18 -0
  24. package/dist/common/endowments/textDecoder.js.map +1 -0
  25. package/dist/common/endowments/textEncoder.d.ts +10 -0
  26. package/dist/common/endowments/textEncoder.js +18 -0
  27. package/dist/common/endowments/textEncoder.js.map +1 -0
  28. package/dist/common/endowments/timeout.js +6 -4
  29. package/dist/common/endowments/timeout.js.map +1 -1
  30. package/dist/common/lockdown/lockdown-more.js +2 -1
  31. package/dist/common/lockdown/lockdown-more.js.map +1 -1
  32. package/dist/common/lockdown/lockdown.js +2 -1
  33. package/dist/common/lockdown/lockdown.js.map +1 -1
  34. package/dist/common/utils.d.ts +0 -16
  35. package/dist/common/utils.js +4 -43
  36. package/dist/common/utils.js.map +1 -1
  37. package/dist/common/validation.d.ts +8 -8
  38. package/dist/iframe/IFrameSnapExecutor.js +3 -2
  39. package/dist/iframe/IFrameSnapExecutor.js.map +1 -1
  40. package/dist/logging.d.ts +8 -0
  41. package/dist/logging.js +13 -0
  42. package/dist/logging.js.map +1 -0
  43. package/dist/node-process/ChildProcessSnapExecutor.js +3 -2
  44. package/dist/node-process/ChildProcessSnapExecutor.js.map +1 -1
  45. package/dist/node-thread/ThreadSnapExecutor.js +3 -2
  46. package/dist/node-thread/ThreadSnapExecutor.js.map +1 -1
  47. package/dist/offscreen/OffscreenSnapExecutor.d.ts +34 -0
  48. package/dist/offscreen/OffscreenSnapExecutor.js +104 -0
  49. package/dist/offscreen/OffscreenSnapExecutor.js.map +1 -0
  50. package/dist/offscreen/index.d.ts +1 -0
  51. package/dist/offscreen/index.js +15 -0
  52. package/dist/offscreen/index.js.map +1 -0
  53. package/dist/webpack/iframe/bundle.js +1750 -1
  54. package/dist/webpack/iframe/bundle.js.LICENSE.txt +0 -2
  55. package/dist/webpack/iframe/lockdown.umd.min.js +1 -1
  56. package/dist/webpack/node-process/bundle.js +23 -10
  57. package/dist/webpack/node-process/bundle.js.LICENSE.txt +0 -2
  58. package/dist/webpack/node-process/lockdown.umd.min.js +1 -1
  59. package/dist/webpack/node-thread/bundle.js +23 -10
  60. package/dist/webpack/node-thread/bundle.js.LICENSE.txt +0 -2
  61. package/dist/webpack/node-thread/lockdown.umd.min.js +1 -1
  62. package/dist/webpack/offscreen/bundle.js +1751 -0
  63. package/dist/webpack/offscreen/bundle.js.LICENSE.txt +25 -0
  64. package/dist/webpack/offscreen/index.html +11 -0
  65. package/dist/webpack/offscreen/lockdown.umd.min.js +1 -0
  66. package/package.json +19 -13
@@ -73,21 +73,20 @@ class ResponseWrapper {
73
73
  }
74
74
  _ResponseWrapper_teardownRef = new WeakMap(), _ResponseWrapper_ogResponse = new WeakMap();
75
75
  /**
76
- * Create a network endowment, consisting of a `WebSocket` object and `fetch`
77
- * function. This allows us to provide a teardown function, so that we can cancel
76
+ * Create a network endowment, consisting of a `fetch` function.
77
+ * This allows us to provide a teardown function, so that we can cancel
78
78
  * any pending requests, connections, streams, etc. that may be open when a snap
79
79
  * is terminated.
80
80
  *
81
- * This wraps the original implementations of `WebSocket` and `fetch`,
82
- * to ensure that a bad actor cannot get access to the original objects, thus
81
+ * This wraps the original implementation of `fetch`,
82
+ * to ensure that a bad actor cannot get access to the original function, thus
83
83
  * potentially preventing the network requests from being torn down.
84
84
  *
85
- * @returns An object containing a wrapped `WebSocket` class and `fetch`
85
+ * @returns An object containing a wrapped `fetch`
86
86
  * function, as well as a teardown function.
87
87
  */
88
88
  const createNetwork = () => {
89
- var _instances, _teardownClose, _createWrapped, _socket, _isTornDown, _events, _onopenOriginal, _onmessageOriginal, _onerrorOriginal, _oncloseOriginal, _a;
90
- // Open fetch calls or open body streams or open websockets
89
+ // Open fetch calls or open body streams
91
90
  const openConnections = new Set();
92
91
  // Track last teardown count
93
92
  const teardownRef = { lastTeardown: 0 };
@@ -147,204 +146,8 @@ const createNetwork = () => {
147
146
  /* istanbul ignore next: can't test garbage collection without modifying node parameters */
148
147
  () => openConnections.delete(openBodyConnection));
149
148
  }
150
- return res;
149
+ return harden(res);
151
150
  };
152
- /**
153
- * This class wraps a WebSocket object instead of extending it.
154
- * That way, a bad actor can't get access to original methods using
155
- * `socket.prototype`.
156
- *
157
- * When modifying this class, ensure that no method calls any other method
158
- * from the same class (#socket calls are fine). Otherwise, a bad actor could
159
- * replace one of the implementations
160
- */
161
- const _WebSocket = (_a = class {
162
- constructor(url, protocols) {
163
- _instances.add(this);
164
- _socket.set(this, void 0);
165
- /**
166
- * After this is set to true, no new event listeners can be added
167
- */
168
- _isTornDown.set(this, false);
169
- _events.set(this, {});
170
- _onopenOriginal.set(this, null);
171
- _onmessageOriginal.set(this, null);
172
- _onerrorOriginal.set(this, null);
173
- _oncloseOriginal.set(this, null);
174
- __classPrivateFieldSet(this, _socket, new WebSocket(url, protocols), "f");
175
- // You can't call ref.deref()?.#teardownClose()
176
- // But you can capture the close itself
177
- const ref = new WeakRef(__classPrivateFieldGet(this, _instances, "m", _teardownClose).bind(this));
178
- const openConnection = {
179
- cancel: async () => {
180
- var _a;
181
- try {
182
- await ((_a = ref.deref()) === null || _a === void 0 ? void 0 : _a());
183
- }
184
- catch (_b) {
185
- /* do nothing */
186
- }
187
- },
188
- };
189
- openConnections.add(openConnection);
190
- cleanup.register(this,
191
- /* istanbul ignore next: can't test garbage collection without modifying node parameters */
192
- () => openConnections.delete(openConnection));
193
- }
194
- get onclose() {
195
- return __classPrivateFieldGet(this, _oncloseOriginal, "f");
196
- }
197
- set onclose(callback) {
198
- if (!__classPrivateFieldGet(this, _isTornDown, "f")) {
199
- __classPrivateFieldSet(this, _oncloseOriginal, callback, "f");
200
- __classPrivateFieldGet(this, _socket, "f").onclose = __classPrivateFieldGet(this, _instances, "m", _createWrapped).call(this, callback);
201
- }
202
- }
203
- get onerror() {
204
- return __classPrivateFieldGet(this, _onerrorOriginal, "f");
205
- }
206
- set onerror(callback) {
207
- __classPrivateFieldSet(this, _onerrorOriginal, callback, "f");
208
- __classPrivateFieldGet(this, _socket, "f").onerror = __classPrivateFieldGet(this, _instances, "m", _createWrapped).call(this, callback);
209
- }
210
- get onmessage() {
211
- return __classPrivateFieldGet(this, _onmessageOriginal, "f");
212
- }
213
- set onmessage(callback) {
214
- __classPrivateFieldSet(this, _onmessageOriginal, callback, "f");
215
- __classPrivateFieldGet(this, _socket, "f").onmessage = __classPrivateFieldGet(this, _instances, "m", _createWrapped).call(this, callback);
216
- }
217
- get onopen() {
218
- return __classPrivateFieldGet(this, _onopenOriginal, "f");
219
- }
220
- set onopen(callback) {
221
- __classPrivateFieldSet(this, _onopenOriginal, callback, "f");
222
- __classPrivateFieldGet(this, _socket, "f").onopen = __classPrivateFieldGet(this, _instances, "m", _createWrapped).call(this, callback);
223
- }
224
- close(code, reason) {
225
- __classPrivateFieldGet(this, _socket, "f").close(code, reason);
226
- }
227
- send(data) {
228
- __classPrivateFieldGet(this, _socket, "f").send(data);
229
- }
230
- // The WebSocket interface don't respect the camelCase format
231
- /* eslint-disable @typescript-eslint/naming-convention */
232
- get CLOSED() {
233
- return __classPrivateFieldGet(this, _socket, "f").CLOSED;
234
- }
235
- get CLOSING() {
236
- return __classPrivateFieldGet(this, _socket, "f").CLOSING;
237
- }
238
- get CONNECTING() {
239
- return __classPrivateFieldGet(this, _socket, "f").CONNECTING;
240
- }
241
- get OPEN() {
242
- return __classPrivateFieldGet(this, _socket, "f").OPEN;
243
- }
244
- /* eslint-enable @typescript-eslint/naming-convention */
245
- get binaryType() {
246
- return __classPrivateFieldGet(this, _socket, "f").binaryType;
247
- }
248
- set binaryType(value) {
249
- __classPrivateFieldGet(this, _socket, "f").binaryType = value;
250
- }
251
- get bufferedAmount() {
252
- var _a;
253
- return (_a = __classPrivateFieldGet(this, _socket, "f").bufferedAmount) !== null && _a !== void 0 ? _a : 0;
254
- }
255
- get extensions() {
256
- var _a;
257
- return (_a = __classPrivateFieldGet(this, _socket, "f").extensions) !== null && _a !== void 0 ? _a : '';
258
- }
259
- get protocol() {
260
- return __classPrivateFieldGet(this, _socket, "f").protocol;
261
- }
262
- get readyState() {
263
- return __classPrivateFieldGet(this, _socket, "f").readyState;
264
- }
265
- get url() {
266
- return __classPrivateFieldGet(this, _socket, "f").url;
267
- }
268
- addEventListener(type, listener, options) {
269
- if (!__classPrivateFieldGet(this, _isTornDown, "f")) {
270
- if (__classPrivateFieldGet(this, _events, "f")[type] === undefined) {
271
- __classPrivateFieldGet(this, _events, "f")[type] = new Map();
272
- }
273
- const wrapped = __classPrivateFieldGet(this, _instances, "m", _createWrapped).call(this, listener);
274
- if (wrapped !== null) {
275
- __classPrivateFieldGet(this, _events, "f")[type].set(listener, wrapped);
276
- __classPrivateFieldGet(this, _socket, "f").addEventListener(type, wrapped, options);
277
- }
278
- }
279
- }
280
- removeEventListener(type, listener, options) {
281
- if (__classPrivateFieldGet(this, _events, "f")[type] !== undefined) {
282
- const wrapped = __classPrivateFieldGet(this, _events, "f")[type].get(listener);
283
- if (wrapped !== undefined) {
284
- __classPrivateFieldGet(this, _events, "f")[type].delete(listener);
285
- __classPrivateFieldGet(this, _socket, "f").removeEventListener(type, wrapped, options);
286
- }
287
- }
288
- }
289
- dispatchEvent(event) {
290
- // Can't call close prematurely before the teardown finishes
291
- if (event.type !== 'close' || !__classPrivateFieldGet(this, _isTornDown, "f")) {
292
- return __classPrivateFieldGet(this, _socket, "f").dispatchEvent(event);
293
- }
294
- return false;
295
- }
296
- },
297
- _socket = new WeakMap(),
298
- _isTornDown = new WeakMap(),
299
- _events = new WeakMap(),
300
- _onopenOriginal = new WeakMap(),
301
- _onmessageOriginal = new WeakMap(),
302
- _onerrorOriginal = new WeakMap(),
303
- _oncloseOriginal = new WeakMap(),
304
- _instances = new WeakSet(),
305
- _teardownClose = async function _teardownClose() {
306
- var _a, _b, _c;
307
- // We clear all close listeners
308
- __classPrivateFieldGet(this, _socket, "f").onclose = null;
309
- for (const wrapped of (_b = (_a = __classPrivateFieldGet(this, _events, "f").close) === null || _a === void 0 ? void 0 : _a.values()) !== null && _b !== void 0 ? _b : []) {
310
- __classPrivateFieldGet(this, _socket, "f").removeEventListener('close', wrapped);
311
- }
312
- (_c = __classPrivateFieldGet(this, _events, "f").close) === null || _c === void 0 ? void 0 : _c.clear();
313
- // We add our own listener
314
- let onClosedResolve;
315
- const onClosed = new Promise((resolve) => (onClosedResolve = resolve));
316
- __classPrivateFieldGet(this, _socket, "f").onclose = () => {
317
- onClosedResolve();
318
- };
319
- // No new listeners can be added after this point
320
- __classPrivateFieldSet(this, _isTornDown, true, "f");
321
- __classPrivateFieldGet(this, _socket, "f").close();
322
- return onClosed;
323
- },
324
- _createWrapped = function _createWrapped(listener) {
325
- if (listener === null) {
326
- return null;
327
- }
328
- return (event) => {
329
- // TODO: Should we migrate this to use a wrapper class?
330
- const properties = [...(0, utils_1.allProperties)(event)]
331
- .filter(([_, key]) => key !== 'constructor')
332
- .reduce((acc, [obj, key]) => {
333
- const stringKey = key.toString();
334
- const descriptor = Reflect.getOwnPropertyDescriptor(obj, key);
335
- if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.value) === 'function') {
336
- acc[stringKey] = event[stringKey].bind(this);
337
- }
338
- else {
339
- acc[stringKey] = event[stringKey];
340
- }
341
- return acc;
342
- }, {});
343
- const wrappedEvent = Object.assign(Object.assign({}, properties), { target: this, currentTarget: this, srcElement: this, ports: [this], source: null, composedPath: () => [this] });
344
- listener.apply(this, [wrappedEvent]);
345
- };
346
- },
347
- _a);
348
151
  const teardownFunction = async () => {
349
152
  teardownRef.lastTeardown += 1;
350
153
  const promises = [];
@@ -353,13 +156,12 @@ const createNetwork = () => {
353
156
  await Promise.all(promises);
354
157
  };
355
158
  return {
356
- fetch: _fetch,
357
- WebSocket: _WebSocket,
159
+ fetch: harden(_fetch),
358
160
  teardownFunction,
359
161
  };
360
162
  };
361
163
  const endowmentModule = {
362
- names: ['fetch', 'WebSocket'],
164
+ names: ['fetch'],
363
165
  factory: createNetwork,
364
166
  };
365
167
  exports.default = endowmentModule;
@@ -1 +1 @@
1
- {"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/common/endowments/network.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,oCAAuD;AAIvD;;;GAGG;AACH,MAAM,eAAe;IAKnB,YAAY,UAAoB,EAAE,WAAqC;QAJvE,+CAAgD;QAEhD,8CAAsB;QAGpB,uBAAA,IAAI,+BAAe,UAAU,MAAA,CAAC;QAC9B,uBAAA,IAAI,gCAAgB,WAAW,MAAA,CAAC;IAClC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,uBAAA,IAAI,mCAAY,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,uBAAA,IAAI,mCAAY,CAAC,QAAQ,C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AQ,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC;YACvC,CAAC,CAAC;QACJ,CAAC;WAkBF,CAAC;IAEF,MAAM,gBAAgB,GAAG,KAAK,IAAI,EAAE;QAClC,WAAW,CAAC,YAAY,IAAI,CAAC,CAAC;QAC9B,MAAM,QAAQ,GAAoB,EAAE,CAAC;QACrC,eAAe,CAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QACjE,eAAe,CAAC,KAAK,EAAE,CAAC;QACxB,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC,CAAC;IAEF,OAAO;QACL,KAAK,EAAE,MAAM;QACb,SAAS,EAAE,UAAU;QACrB,gBAAgB;KACjB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,OAAO,EAAE,WAAW,CAAU;IACtC,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { allProperties, withTeardown } from '../utils';\n\ntype WebSocketCallback = (this: WebSocket, ev: any) => any;\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n constructor(ogResponse: Response, teardownRef: { lastTeardown: number }) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return withTeardown<string>(this.#ogResponse.text(), this as any);\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return withTeardown<ArrayBuffer>(\n this.#ogResponse.arrayBuffer(),\n this as any,\n );\n }\n\n async blob(): Promise<Blob> {\n return withTeardown<Blob>(this.#ogResponse.blob(), this as any);\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(newResponse, this.#teardownRef);\n }\n\n async formData(): Promise<FormData> {\n return withTeardown<FormData>(this.#ogResponse.formData(), this as any);\n }\n\n async json(): Promise<any> {\n return withTeardown(this.#ogResponse.json(), this as any);\n }\n}\n\n/**\n * Create a network endowment, consisting of a `WebSocket` object and `fetch`\n * function. This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementations of `WebSocket` and `fetch`,\n * to ensure that a bad actor cannot get access to the original objects, thus\n * potentially preventing the network requests from being torn down.\n *\n * @returns An object containing a wrapped `WebSocket` class and `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = () => {\n // Open fetch calls or open body streams or open websockets\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n try {\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await withTeardown(fetchPromise, teardownRef),\n teardownRef,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return res;\n };\n\n /**\n * This class wraps a WebSocket object instead of extending it.\n * That way, a bad actor can't get access to original methods using\n * `socket.prototype`.\n *\n * When modifying this class, ensure that no method calls any other method\n * from the same class (#socket calls are fine). Otherwise, a bad actor could\n * replace one of the implementations\n */\n const _WebSocket = class implements WebSocket {\n constructor(url: string | URL, protocols?: string | string[]) {\n this.#socket = new WebSocket(url, protocols);\n\n // You can't call ref.deref()?.#teardownClose()\n // But you can capture the close itself\n const ref = new WeakRef(this.#teardownClose.bind(this));\n const openConnection = {\n cancel: async () => {\n try {\n await ref.deref()?.();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openConnection);\n cleanup.register(\n this,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openConnection),\n );\n }\n\n get onclose(): WebSocketCallback | null {\n return this.#oncloseOriginal;\n }\n\n set onclose(callback: WebSocketCallback | null) {\n if (!this.#isTornDown) {\n this.#oncloseOriginal = callback;\n this.#socket.onclose = this.#createWrapped(callback);\n }\n }\n\n get onerror(): ((this: WebSocket, ev: Event) => any) | null {\n return this.#onerrorOriginal;\n }\n\n set onerror(callback: ((this: WebSocket, ev: Event) => any) | null) {\n this.#onerrorOriginal = callback;\n this.#socket.onerror = this.#createWrapped(callback);\n }\n\n get onmessage(): ((this: WebSocket, ev: MessageEvent) => any) | null {\n return this.#onmessageOriginal;\n }\n\n set onmessage(\n callback: ((this: WebSocket, ev: MessageEvent) => any) | null,\n ) {\n this.#onmessageOriginal = callback;\n this.#socket.onmessage = this.#createWrapped(callback);\n }\n\n get onopen(): ((this: WebSocket, ev: Event) => any) | null {\n return this.#onopenOriginal;\n }\n\n set onopen(callback: ((this: WebSocket, ev: Event) => any) | null) {\n this.#onopenOriginal = callback;\n this.#socket.onopen = this.#createWrapped(callback);\n }\n\n close(code?: number, reason?: string): void {\n this.#socket.close(code, reason);\n }\n\n send(data: string | Blob | ArrayBufferView | ArrayBufferLike): void {\n this.#socket.send(data);\n }\n\n // The WebSocket interface don't respect the camelCase format\n /* eslint-disable @typescript-eslint/naming-convention */\n get CLOSED(): number {\n return this.#socket.CLOSED;\n }\n\n get CLOSING(): number {\n return this.#socket.CLOSING;\n }\n\n get CONNECTING(): number {\n return this.#socket.CONNECTING;\n }\n\n get OPEN(): number {\n return this.#socket.OPEN;\n }\n /* eslint-enable @typescript-eslint/naming-convention */\n\n get binaryType(): BinaryType {\n return this.#socket.binaryType;\n }\n\n set binaryType(value: BinaryType) {\n this.#socket.binaryType = value;\n }\n\n get bufferedAmount(): number {\n return this.#socket.bufferedAmount ?? 0;\n }\n\n get extensions(): string {\n return this.#socket.extensions ?? '';\n }\n\n get protocol(): string {\n return this.#socket.protocol;\n }\n\n get readyState(): number {\n return this.#socket.readyState;\n }\n\n get url(): string {\n return this.#socket.url;\n }\n\n addEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions,\n ): void;\n\n addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): void;\n\n addEventListener(type: any, listener: any, options?: any): void {\n if (!this.#isTornDown) {\n if (this.#events[type] === undefined) {\n this.#events[type] = new Map();\n }\n const wrapped = this.#createWrapped(listener);\n if (wrapped !== null) {\n this.#events[type].set(listener, wrapped);\n this.#socket.addEventListener(type, wrapped, options);\n }\n }\n }\n\n removeEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,\n options?: boolean | EventListenerOptions,\n ): void;\n\n removeEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): void;\n\n removeEventListener(type: any, listener: any, options?: any): void {\n if (this.#events[type] !== undefined) {\n const wrapped = this.#events[type].get(listener);\n if (wrapped !== undefined) {\n this.#events[type].delete(listener);\n this.#socket.removeEventListener(type, wrapped, options);\n }\n }\n }\n\n dispatchEvent(event: Event): boolean {\n // Can't call close prematurely before the teardown finishes\n if (event.type !== 'close' || !this.#isTornDown) {\n return this.#socket.dispatchEvent(event);\n }\n return false;\n }\n\n async #teardownClose() {\n // We clear all close listeners\n this.#socket.onclose = null;\n for (const wrapped of this.#events.close?.values() ?? []) {\n this.#socket.removeEventListener('close', wrapped);\n }\n this.#events.close?.clear();\n\n // We add our own listener\n let onClosedResolve: any;\n const onClosed = new Promise<void>(\n (resolve) => (onClosedResolve = resolve),\n );\n this.#socket.onclose = () => {\n onClosedResolve();\n };\n\n // No new listeners can be added after this point\n this.#isTornDown = true;\n\n this.#socket.close();\n\n return onClosed;\n }\n\n #createWrapped(listener: WebSocketCallback): WebSocketCallback;\n\n #createWrapped(listener: null): null;\n\n #createWrapped(\n listener: WebSocketCallback | null,\n ): WebSocketCallback | null;\n\n #createWrapped(\n listener: WebSocketCallback | null,\n ): WebSocketCallback | null {\n if (listener === null) {\n return null;\n }\n\n return (event) => {\n // TODO: Should we migrate this to use a wrapper class?\n const properties = [...allProperties(event)]\n .filter(([_, key]) => key !== 'constructor')\n .reduce<Record<string, any>>((acc, [obj, key]) => {\n const stringKey = key.toString();\n const descriptor = Reflect.getOwnPropertyDescriptor(obj, key);\n if (typeof descriptor?.value === 'function') {\n acc[stringKey] = event[stringKey].bind(this);\n } else {\n acc[stringKey] = event[stringKey];\n }\n return acc;\n }, {});\n const wrappedEvent = {\n ...properties,\n target: this,\n currentTarget: this,\n srcElement: this,\n ports: [this],\n source: null,\n composedPath: () => [this],\n };\n listener.apply(this, [wrappedEvent]);\n };\n }\n\n #socket: WebSocket;\n\n /**\n * After this is set to true, no new event listeners can be added\n */\n #isTornDown = false;\n\n #events: Record<string, Map<WebSocketCallback, WebSocketCallback>> = {};\n\n #onopenOriginal: WebSocketCallback | null = null;\n\n #onmessageOriginal: WebSocketCallback | null = null;\n\n #onerrorOriginal: WebSocketCallback | null = null;\n\n #oncloseOriginal: WebSocketCallback | null = null;\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: _fetch,\n WebSocket: _WebSocket,\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch', 'WebSocket'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"]}
1
+ {"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/common/endowments/network.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,oCAAwC;AAExC;;;GAGG;AACH,MAAM,eAAe;IAKnB,YAAY,UAAoB,EAAE,WAAqC;QAJvE,+CAAgD;QAEhD,8CAAsB;QAGpB,uBAAA,IAAI,+BAAe,UAAU,MAAA,CAAC;QAC9B,uBAAA,IAAI,gCAAgB,WAAW,MAAA,CAAC;IAClC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,uBAAA,IAAI,mCAAY,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,uBAAA,IAAI,mCAAY,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,IAAI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,CAAC,CAAC;QACjE,eAAe,CAAC,KAAK,EAAE,CAAC;QACxB,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC,CAAC;IAEF,OAAO;QACL,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QACrB,gBAAgB;KACjB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,OAAO,CAAU;IACzB,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { withTeardown } from '../utils';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n constructor(ogResponse: Response, teardownRef: { lastTeardown: number }) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return withTeardown<string>(this.#ogResponse.text(), this as any);\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return withTeardown<ArrayBuffer>(\n this.#ogResponse.arrayBuffer(),\n this as any,\n );\n }\n\n async blob(): Promise<Blob> {\n return withTeardown<Blob>(this.#ogResponse.blob(), this as any);\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(newResponse, this.#teardownRef);\n }\n\n async formData(): Promise<FormData> {\n return withTeardown<FormData>(this.#ogResponse.formData(), this as any);\n }\n\n async json(): Promise<any> {\n return withTeardown(this.#ogResponse.json(), this as any);\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = () => {\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n try {\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await withTeardown(fetchPromise, teardownRef),\n teardownRef,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"]}
@@ -0,0 +1,10 @@
1
+ declare const endowmentModule: {
2
+ names: readonly ["TextDecoder"];
3
+ factory: () => {
4
+ readonly TextDecoder: {
5
+ new (label?: string | undefined, options?: TextDecoderOptions | undefined): TextDecoder;
6
+ prototype: TextDecoder;
7
+ };
8
+ };
9
+ };
10
+ export default endowmentModule;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Creates TextDecoder function hardened by SES.
5
+ *
6
+ * @returns An object with the attenuated `TextDecoder` function.
7
+ */
8
+ const createTextDecoder = () => {
9
+ return {
10
+ TextDecoder: harden(TextDecoder),
11
+ };
12
+ };
13
+ const endowmentModule = {
14
+ names: ['TextDecoder'],
15
+ factory: createTextDecoder,
16
+ };
17
+ exports.default = endowmentModule;
18
+ //# sourceMappingURL=textDecoder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"textDecoder.js","sourceRoot":"","sources":["../../../src/common/endowments/textDecoder.ts"],"names":[],"mappings":";;AAAA;;;;GAIG;AACH,MAAM,iBAAiB,GAAG,GAAG,EAAE;IAC7B,OAAO;QACL,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC;KACxB,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,aAAa,CAAU;IAC/B,OAAO,EAAE,iBAAiB;CAC3B,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["/**\n * Creates TextDecoder function hardened by SES.\n *\n * @returns An object with the attenuated `TextDecoder` function.\n */\nconst createTextDecoder = () => {\n return {\n TextDecoder: harden(TextDecoder),\n } as const;\n};\n\nconst endowmentModule = {\n names: ['TextDecoder'] as const,\n factory: createTextDecoder,\n};\nexport default endowmentModule;\n"]}
@@ -0,0 +1,10 @@
1
+ declare const endowmentModule: {
2
+ names: readonly ["TextEncoder"];
3
+ factory: () => {
4
+ readonly TextEncoder: {
5
+ new (): TextEncoder;
6
+ prototype: TextEncoder;
7
+ };
8
+ };
9
+ };
10
+ export default endowmentModule;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Creates TextEncoder function hardened by SES.
5
+ *
6
+ * @returns An object with the attenuated `TextEncoder` function.
7
+ */
8
+ const createTextEncoder = () => {
9
+ return {
10
+ TextEncoder: harden(TextEncoder),
11
+ };
12
+ };
13
+ const endowmentModule = {
14
+ names: ['TextEncoder'],
15
+ factory: createTextEncoder,
16
+ };
17
+ exports.default = endowmentModule;
18
+ //# sourceMappingURL=textEncoder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"textEncoder.js","sourceRoot":"","sources":["../../../src/common/endowments/textEncoder.ts"],"names":[],"mappings":";;AAAA;;;;GAIG;AACH,MAAM,iBAAiB,GAAG,GAAG,EAAE;IAC7B,OAAO;QACL,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC;KACxB,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,aAAa,CAAU;IAC/B,OAAO,EAAE,iBAAiB;CAC3B,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["/**\n * Creates TextEncoder function hardened by SES.\n *\n * @returns An object with the attenuated `TextEncoder` function.\n */\nconst createTextEncoder = () => {\n return {\n TextEncoder: harden(TextEncoder),\n } as const;\n};\n\nconst endowmentModule = {\n names: ['TextEncoder'] as const,\n factory: createTextEncoder,\n};\nexport default endowmentModule;\n"]}
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const MINIMUM_TIMEOUT = 10;
3
4
  /**
4
5
  * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such
5
6
  * that:
@@ -16,11 +17,12 @@ const createTimeout = () => {
16
17
  if (typeof handler !== 'function') {
17
18
  throw new Error(`The timeout handler must be a function. Received: ${typeof handler}`);
18
19
  }
19
- const handle = Object.freeze({});
20
+ harden(handler);
21
+ const handle = Object.freeze(Object.create(null));
20
22
  const platformHandle = setTimeout(() => {
21
23
  registeredHandles.delete(handle);
22
24
  handler();
23
- }, timeout);
25
+ }, Math.max(MINIMUM_TIMEOUT, timeout !== null && timeout !== void 0 ? timeout : 0));
24
26
  registeredHandles.set(handle, platformHandle);
25
27
  return handle;
26
28
  };
@@ -37,8 +39,8 @@ const createTimeout = () => {
37
39
  }
38
40
  };
39
41
  return {
40
- setTimeout: _setTimeout,
41
- clearTimeout: _clearTimeout,
42
+ setTimeout: harden(_setTimeout),
43
+ clearTimeout: harden(_clearTimeout),
42
44
  teardownFunction,
43
45
  };
44
46
  };
@@ -1 +1 @@
1
- {"version":3,"file":"timeout.js","sourceRoot":"","sources":["../../../src/common/endowments/timeout.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;GASG;AACH,MAAM,aAAa,GAAG,GAAG,EAAE;IACzB,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAoB,CAAC;IAEtD,MAAM,WAAW,GAAG,CAAC,OAAqB,EAAE,OAAgB,EAAW,EAAE;QACvE,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,qDAAqD,OAAO,OAAO,EAAE,CACtE,CAAC;SACH;QAED,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACjC,MAAM,cAAc,GAAG,UAAU,CAAC,GAAG,EAAE;YACrC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACjC,OAAO,EAAE,CAAC;QACZ,CAAC,EAAE,OAAO,CAAC,CAAC;QAEZ,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;QAC9C,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,CAAC,MAAe,EAAQ,EAAE;QAC9C,MAAM,cAAc,GAAG,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrD,IAAI,cAAc,KAAK,SAAS,EAAE;YAChC,YAAY,CAAC,cAAqB,CAAC,CAAC;YACpC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;SAClC;IACH,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,GAAS,EAAE;QAClC,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,IAAI,EAAE,EAAE;YAC7C,aAAa,CAAC,MAAM,CAAC,CAAC;SACvB;IACH,CAAC,CAAC;IAEF,OAAO;QACL,UAAU,EAAE,WAAW;QACvB,YAAY,EAAE,aAAa;QAC3B,gBAAgB;KACR,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,YAAY,EAAE,cAAc,CAAU;IAC9C,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["/**\n * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such\n * that:\n * - `setTimeout` throws if its \"handler\" parameter is not a function.\n * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setTimeout` and `clearTimeout`\n * functions.\n */\nconst createTimeout = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setTimeout = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The timeout handler must be a function. Received: ${typeof handler}`,\n );\n }\n\n const handle = Object.freeze({});\n const platformHandle = setTimeout(() => {\n registeredHandles.delete(handle);\n handler();\n }, timeout);\n\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearTimeout = (handle: unknown): void => {\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearTimeout(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearTimeout(handle);\n }\n };\n\n return {\n setTimeout: _setTimeout,\n clearTimeout: _clearTimeout,\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setTimeout', 'clearTimeout'] as const,\n factory: createTimeout,\n};\nexport default endowmentModule;\n"]}
1
+ {"version":3,"file":"timeout.js","sourceRoot":"","sources":["../../../src/common/endowments/timeout.ts"],"names":[],"mappings":";;AAAA,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B;;;;;;;;;GASG;AACH,MAAM,aAAa,GAAG,GAAG,EAAE;IACzB,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAoB,CAAC;IAEtD,MAAM,WAAW,GAAG,CAAC,OAAqB,EAAE,OAAgB,EAAW,EAAE;QACvE,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,qDAAqD,OAAO,OAAO,EAAE,CACtE,CAAC;SACH;QACD,MAAM,CAAC,OAAO,CAAC,CAAC;QAChB,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAClD,MAAM,cAAc,GAAG,UAAU,CAAC,GAAG,EAAE;YACrC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACjC,OAAO,EAAE,CAAC;QACZ,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,CAAC,CAAC,CAAC,CAAC;QAE5C,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;QAC9C,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,CAAC,MAAe,EAAQ,EAAE;QAC9C,MAAM,cAAc,GAAG,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrD,IAAI,cAAc,KAAK,SAAS,EAAE;YAChC,YAAY,CAAC,cAAqB,CAAC,CAAC;YACpC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;SAClC;IACH,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,GAAS,EAAE;QAClC,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,IAAI,EAAE,EAAE;YAC7C,aAAa,CAAC,MAAM,CAAC,CAAC;SACvB;IACH,CAAC,CAAC;IAEF,OAAO;QACL,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;QAC/B,YAAY,EAAE,MAAM,CAAC,aAAa,CAAC;QACnC,gBAAgB;KACR,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,YAAY,EAAE,cAAc,CAAU;IAC9C,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["const MINIMUM_TIMEOUT = 10;\n\n/**\n * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such\n * that:\n * - `setTimeout` throws if its \"handler\" parameter is not a function.\n * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setTimeout` and `clearTimeout`\n * functions.\n */\nconst createTimeout = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setTimeout = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The timeout handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setTimeout(() => {\n registeredHandles.delete(handle);\n handler();\n }, Math.max(MINIMUM_TIMEOUT, timeout ?? 0));\n\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearTimeout = (handle: unknown): void => {\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearTimeout(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearTimeout(handle);\n }\n };\n\n return {\n setTimeout: harden(_setTimeout),\n clearTimeout: harden(_clearTimeout),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setTimeout', 'clearTimeout'] as const,\n factory: createTimeout,\n};\nexport default endowmentModule;\n"]}
@@ -3,6 +3,7 @@
3
3
  /// <reference path="../../../../../node_modules/ses/index.d.ts" />
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.executeLockdownMore = void 0;
6
+ const snaps_utils_1 = require("@metamask/snaps-utils");
6
7
  /**
7
8
  * The SES `lockdown` function only hardens the properties enumerated by the
8
9
  * universalPropertyNames constant specified in 'ses/src/whitelist'. This
@@ -67,7 +68,7 @@ function executeLockdownMore() {
67
68
  });
68
69
  }
69
70
  catch (error) {
70
- console.error('Protecting intrinsics failed:', error);
71
+ (0, snaps_utils_1.logError)('Protecting intrinsics failed:', error);
71
72
  throw error;
72
73
  }
73
74
  }
@@ -1 +1 @@
1
- {"version":3,"file":"lockdown-more.js","sourceRoot":"","sources":["../../../src/common/lockdown/lockdown-more.ts"],"names":[],"mappings":";AAAA,qFAAqF;AACrF,mEAAmE;;;AAEnE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,mBAAmB;IACjC,gEAAgE;IAChE,oDAAoD;IACpD,gEAAgE;IAChE,oBAAoB;IACpB,IAAI;QACF,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,WAAW,EAAE,CAAC,UAAU,CAAC,CAAC;QAEtE,sEAAsE;QACtE,MAAM,oBAAoB,GAAG,IAAI,GAA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-comment\n/// <reference path=\"../../../../../node_modules/ses/index.d.ts\" />\n\n/**\n * The SES `lockdown` function only hardens the properties enumerated by the\n * universalPropertyNames constant specified in 'ses/src/whitelist'. This\n * function makes all function and object properties on the start compartment\n * global non-configurable and non-writable, unless they are already\n * non-configurable.\n *\n * It is critical that this function runs at the right time during\n * initialization, which should always be immediately after `lockdown` has been\n * called. At the time of writing, the modifications this function makes to the\n * runtime environment appear to be non-breaking, but that could change with\n * the addition of dependencies, or the order of our scripts in our HTML files.\n * Exercise caution.\n *\n * See inline comments for implementation details.\n *\n * We write this function in IIFE format to avoid polluting global scope.\n *\n * @throws If the lockdown failed.\n */\nexport function executeLockdownMore() {\n // Make all \"object\" and \"function\" own properties of globalThis\n // non-configurable and non-writable, when possible.\n // We call a property that is non-configurable and non-writable,\n // \"non-modifiable\".\n try {\n const namedIntrinsics = Reflect.ownKeys(new Compartment().globalThis);\n\n // These named intrinsics are not automatically hardened by `lockdown`\n const shouldHardenManually = new Set<symbol | string>(['eval', 'Function']);\n\n const globalProperties = new Set([\n // universalPropertyNames is a constant added by lockdown to global scope\n // at the time of writing, it is initialized in 'ses/src/whitelist'.\n // These properties tend to be non-enumerable.\n ...namedIntrinsics,\n\n // TODO: Also include the named platform globals\n // This grabs every enumerable property on globalThis.\n // ...Object.keys(globalThis),\n ]);\n\n globalProperties.forEach((propertyName) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(\n globalThis,\n propertyName,\n );\n\n if (descriptor) {\n if (descriptor.configurable) {\n // If the property on globalThis is configurable, make it\n // non-configurable. If it has no accessor properties, also make it\n // non-writable.\n if (hasAccessor(descriptor)) {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n });\n } else {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n writable: false,\n });\n }\n }\n\n if (shouldHardenManually.has(propertyName)) {\n harden((globalThis as any)[propertyName]);\n }\n }\n });\n } catch (error) {\n console.error('Protecting intrinsics failed:', error);\n throw error;\n }\n}\n\n/**\n * Checks whether the given propertyName descriptor has any accessors, i.e. the\n * properties `get` or `set`.\n *\n * We want to make globals non-writable, and we can't set the `writable`\n * property and accessor properties at the same time.\n *\n * @param descriptor - The propertyName descriptor to check.\n * @returns Whether the propertyName descriptor has any accessors.\n */\nfunction hasAccessor(descriptor: any): boolean {\n return 'set' in descriptor || 'get' in descriptor;\n}\n"]}
1
+ {"version":3,"file":"lockdown-more.js","sourceRoot":"","sources":["../../../src/common/lockdown/lockdown-more.ts"],"names":[],"mappings":";AAAA,qFAAqF;AACrF,mEAAmE;;;AAEnE,uDAAiD;AAEjD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,mBAAmB;IACjC,gEAAgE;IAChE,oDAAoD;IACpD,gEAAgE;IAChE,oBAAoB;IACpB,IAAI;QACF,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,WAAW,EAAE,CAAC,UAAU,CAAC,CAAC;QAEtE,sEAAsE;QACtE,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAkB,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC;QAE5E,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;YAC/B,yEAAyE;YACzE,oEAAoE;YACpE,8CAA8C;YAC9C,GAAG,eAAe;YAElB,gDAAgD;YAChD,sDAAsD;YACtD,8BAA8B;SAC/B,CAAC,CAAC;QAEH,gBAAgB,CAAC,OAAO,CAAC,CAAC,YAAY,EAAE,EAAE;YACxC,MAAM,UAAU,GAAG,OAAO,CAAC,wBAAwB,CACjD,UAAU,EACV,YAAY,CACb,CAAC;YAEF,IAAI,UAAU,EAAE;gBACd,IAAI,UAAU,CAAC,YAAY,EAAE;oBAC3B,yDAAyD;oBACzD,mEAAmE;oBACnE,gBAAgB;oBAChB,IAAI,WAAW,CAAC,UAAU,CAAC,EAAE;wBAC3B,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,YAAY,EAAE;4BAC9C,YAAY,EAAE,KAAK;yBACpB,CAAC,CAAC;qBACJ;yBAAM;wBACL,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,YAAY,EAAE;4BAC9C,YAAY,EAAE,KAAK;4BACnB,QAAQ,EAAE,KAAK;yBAChB,CAAC,CAAC;qBACJ;iBACF;gBAED,IAAI,oBAAoB,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE;oBAC1C,MAAM,CAAE,UAAkB,CAAC,YAAY,CAAC,CAAC,CAAC;iBAC3C;aACF;QACH,CAAC,CAAC,CAAC;KACJ;IAAC,OAAO,KAAK,EAAE;QACd,IAAA,sBAAQ,EAAC,+BAA+B,EAAE,KAAK,CAAC,CAAC;QACjD,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAtDD,kDAsDC;AAED;;;;;;;;;GASG;AACH,SAAS,WAAW,CAAC,UAAe;IAClC,OAAO,KAAK,IAAI,UAAU,IAAI,KAAK,IAAI,UAAU,CAAC;AACpD,CAAC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/index.d.ts\" />\n\nimport { logError } from '@metamask/snaps-utils';\n\n/**\n * The SES `lockdown` function only hardens the properties enumerated by the\n * universalPropertyNames constant specified in 'ses/src/whitelist'. This\n * function makes all function and object properties on the start compartment\n * global non-configurable and non-writable, unless they are already\n * non-configurable.\n *\n * It is critical that this function runs at the right time during\n * initialization, which should always be immediately after `lockdown` has been\n * called. At the time of writing, the modifications this function makes to the\n * runtime environment appear to be non-breaking, but that could change with\n * the addition of dependencies, or the order of our scripts in our HTML files.\n * Exercise caution.\n *\n * See inline comments for implementation details.\n *\n * We write this function in IIFE format to avoid polluting global scope.\n *\n * @throws If the lockdown failed.\n */\nexport function executeLockdownMore() {\n // Make all \"object\" and \"function\" own properties of globalThis\n // non-configurable and non-writable, when possible.\n // We call a property that is non-configurable and non-writable,\n // \"non-modifiable\".\n try {\n const namedIntrinsics = Reflect.ownKeys(new Compartment().globalThis);\n\n // These named intrinsics are not automatically hardened by `lockdown`\n const shouldHardenManually = new Set<symbol | string>(['eval', 'Function']);\n\n const globalProperties = new Set([\n // universalPropertyNames is a constant added by lockdown to global scope\n // at the time of writing, it is initialized in 'ses/src/whitelist'.\n // These properties tend to be non-enumerable.\n ...namedIntrinsics,\n\n // TODO: Also include the named platform globals\n // This grabs every enumerable property on globalThis.\n // ...Object.keys(globalThis),\n ]);\n\n globalProperties.forEach((propertyName) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(\n globalThis,\n propertyName,\n );\n\n if (descriptor) {\n if (descriptor.configurable) {\n // If the property on globalThis is configurable, make it\n // non-configurable. If it has no accessor properties, also make it\n // non-writable.\n if (hasAccessor(descriptor)) {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n });\n } else {\n Object.defineProperty(globalThis, propertyName, {\n configurable: false,\n writable: false,\n });\n }\n }\n\n if (shouldHardenManually.has(propertyName)) {\n harden((globalThis as any)[propertyName]);\n }\n }\n });\n } catch (error) {\n logError('Protecting intrinsics failed:', error);\n throw error;\n }\n}\n\n/**\n * Checks whether the given propertyName descriptor has any accessors, i.e. the\n * properties `get` or `set`.\n *\n * We want to make globals non-writable, and we can't set the `writable`\n * property and accessor properties at the same time.\n *\n * @param descriptor - The propertyName descriptor to check.\n * @returns Whether the propertyName descriptor has any accessors.\n */\nfunction hasAccessor(descriptor: any): boolean {\n return 'set' in descriptor || 'get' in descriptor;\n}\n"]}
@@ -3,6 +3,7 @@
3
3
  /// <reference path="../../../../../node_modules/ses/index.d.ts" />
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.executeLockdown = void 0;
6
+ const snaps_utils_1 = require("@metamask/snaps-utils");
6
7
  /**
7
8
  * Execute SES lockdown in the current context, i.e., the current iframe.
8
9
  *
@@ -20,7 +21,7 @@ function executeLockdown() {
20
21
  }
21
22
  catch (error) {
22
23
  // If the `lockdown` call throws an exception, it should not be able to continue
23
- console.error('Lockdown failed:', error);
24
+ (0, snaps_utils_1.logError)('Lockdown failed:', error);
24
25
  throw error;
25
26
  }
26
27
  }
@@ -1 +1 @@
1
- {"version":3,"file":"lockdown.js","sourceRoot":"","sources":["../../../src/common/lockdown/lockdown.ts"],"names":[],"mappings":";AAAA,qFAAqF;AACrF,mEAAmE;;;AAEnE;;;;GAIG;AACH,SAAgB,eAAe;IAC7B,IAAI;QACF,QAAQ,CAAC;YACP,aAAa,EAAE,QAAQ;YACvB,WAAW,EAAE,QAAQ;YACrB,UAAU,EAAE,QAAQ;YACpB,UAAU,EAAE,QAAQ;YACpB,cAAc,EAAE,QAAQ;SACzB,CAAC,CAAC;KACJ;IAAC,OAAO,KAAK,EAAE;QACd,gFAAgF;QAChF,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;QACzC,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAdD,0CAcC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/index.d.ts\" />\n\n/**\n * Execute SES lockdown in the current context, i.e., the current iframe.\n *\n * @throws If the SES lockdown failed.\n */\nexport function executeLockdown() {\n try {\n lockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n });\n } catch (error) {\n // If the `lockdown` call throws an exception, it should not be able to continue\n console.error('Lockdown failed:', error);\n throw error;\n }\n}\n"]}
1
+ {"version":3,"file":"lockdown.js","sourceRoot":"","sources":["../../../src/common/lockdown/lockdown.ts"],"names":[],"mappings":";AAAA,qFAAqF;AACrF,mEAAmE;;;AAEnE,uDAAiD;AAEjD;;;;GAIG;AACH,SAAgB,eAAe;IAC7B,IAAI;QACF,QAAQ,CAAC;YACP,aAAa,EAAE,QAAQ;YACvB,WAAW,EAAE,QAAQ;YACrB,UAAU,EAAE,QAAQ;YACpB,UAAU,EAAE,QAAQ;YACpB,cAAc,EAAE,QAAQ;SACzB,CAAC,CAAC;KACJ;IAAC,OAAO,KAAK,EAAE;QACd,gFAAgF;QAChF,IAAA,sBAAQ,EAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;QACpC,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAdD,0CAcC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../../node_modules/ses/index.d.ts\" />\n\nimport { logError } from '@metamask/snaps-utils';\n\n/**\n * Execute SES lockdown in the current context, i.e., the current iframe.\n *\n * @throws If the SES lockdown failed.\n */\nexport function executeLockdown() {\n try {\n lockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n });\n } catch (error) {\n // If the `lockdown` call throws an exception, it should not be able to continue\n logError('Lockdown failed:', error);\n throw error;\n }\n}\n"]}
@@ -7,22 +7,6 @@
7
7
  * @returns An error object.
8
8
  */
9
9
  export declare function constructError(originalError: unknown): Error | undefined;
10
- /**
11
- * Get all properties of an object, including its prototype chain.
12
- *
13
- * @param obj - The object to get all properties for.
14
- * @returns All properties of `obj` as a tuple set, containing the property name
15
- * and value.
16
- */
17
- export declare function allProperties(obj: any): Set<[object, string | symbol]>;
18
- /**
19
- * Get all functions of an object, including its prototype chain. This does not
20
- * include constructor functions.
21
- *
22
- * @param obj - The object to get all functions for.
23
- * @returns An array with all functions of `obj` as string or symbol.
24
- */
25
- export declare function allFunctions(obj: any): (string | symbol)[];
26
10
  /**
27
11
  * Make proxy for Promise and handle the teardown process properly.
28
12
  * If the teardown is called in the meanwhile, Promise result will not be
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.withTeardown = exports.allFunctions = exports.allProperties = exports.constructError = void 0;
3
+ exports.withTeardown = exports.constructError = void 0;
4
+ const logging_1 = require("../logging");
4
5
  /**
5
6
  * Takes an error that was thrown, determines if it is
6
7
  * an error object. If it is then it will return that. Otherwise,
@@ -22,46 +23,6 @@ function constructError(originalError) {
22
23
  return _originalError;
23
24
  }
24
25
  exports.constructError = constructError;
25
- /**
26
- * Get all properties of an object, including its prototype chain.
27
- *
28
- * @param obj - The object to get all properties for.
29
- * @returns All properties of `obj` as a tuple set, containing the property name
30
- * and value.
31
- */
32
- function allProperties(obj) {
33
- const properties = new Set();
34
- let current = obj;
35
- do {
36
- for (const key of Reflect.ownKeys(current)) {
37
- properties.add([current, key]);
38
- }
39
- } while ((current = Reflect.getPrototypeOf(current)) &&
40
- current !== Object.prototype);
41
- return properties;
42
- }
43
- exports.allProperties = allProperties;
44
- /**
45
- * Get all functions of an object, including its prototype chain. This does not
46
- * include constructor functions.
47
- *
48
- * @param obj - The object to get all functions for.
49
- * @returns An array with all functions of `obj` as string or symbol.
50
- */
51
- function allFunctions(obj) {
52
- const result = [];
53
- for (const [object, key] of allProperties(obj)) {
54
- if (key === 'constructor') {
55
- continue;
56
- }
57
- const descriptor = Reflect.getOwnPropertyDescriptor(object, key);
58
- if (descriptor !== undefined && typeof descriptor.value === 'function') {
59
- result.push(key);
60
- }
61
- }
62
- return result;
63
- }
64
- exports.allFunctions = allFunctions;
65
26
  /**
66
27
  * Make proxy for Promise and handle the teardown process properly.
67
28
  * If the teardown is called in the meanwhile, Promise result will not be
@@ -81,7 +42,7 @@ async function withTeardown(originalPromise, teardownRef) {
81
42
  resolve(value);
82
43
  }
83
44
  else {
84
- console.warn('Late promise received after Snap finished execution. Promise will be dropped.');
45
+ (0, logging_1.log)('Late promise received after Snap finished execution. Promise will be dropped.');
85
46
  }
86
47
  })
87
48
  .catch((reason) => {
@@ -89,7 +50,7 @@ async function withTeardown(originalPromise, teardownRef) {
89
50
  reject(reason);
90
51
  }
91
52
  else {
92
- console.warn('Late promise received after Snap finished execution. Promise will be dropped.');
53
+ (0, logging_1.log)('Late promise received after Snap finished execution. Promise will be dropped.');
93
54
  }
94
55
  });
95
56
  });