@metamask/snaps-execution-environments 8.1.0 → 9.0.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 (35) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/dist/common/BaseSnapExecutor.cjs +79 -61
  3. package/dist/common/BaseSnapExecutor.cjs.map +1 -1
  4. package/dist/common/BaseSnapExecutor.mjs +79 -61
  5. package/dist/common/BaseSnapExecutor.mjs.map +1 -1
  6. package/dist/common/endowments/crypto.cjs +5 -15
  7. package/dist/common/endowments/crypto.cjs.map +1 -1
  8. package/dist/common/endowments/crypto.d.cts +10 -4
  9. package/dist/common/endowments/crypto.d.cts.map +1 -1
  10. package/dist/common/endowments/crypto.d.mts +10 -4
  11. package/dist/common/endowments/crypto.d.mts.map +1 -1
  12. package/dist/common/endowments/crypto.mjs +5 -17
  13. package/dist/common/endowments/crypto.mjs.map +1 -1
  14. package/dist/common/endowments/network.cjs +39 -52
  15. package/dist/common/endowments/network.cjs.map +1 -1
  16. package/dist/common/endowments/network.mjs +39 -52
  17. package/dist/common/endowments/network.mjs.map +1 -1
  18. package/dist/common/validation.d.cts +12 -0
  19. package/dist/common/validation.d.cts.map +1 -1
  20. package/dist/common/validation.d.mts +12 -0
  21. package/dist/common/validation.d.mts.map +1 -1
  22. package/dist/proxy/ProxySnapExecutor.cjs +72 -69
  23. package/dist/proxy/ProxySnapExecutor.cjs.map +1 -1
  24. package/dist/proxy/ProxySnapExecutor.mjs +71 -68
  25. package/dist/proxy/ProxySnapExecutor.mjs.map +1 -1
  26. package/dist/webpack/iframe/bundle.js +1 -1
  27. package/dist/webpack/iframe/index.html +854 -406
  28. package/dist/webpack/node-process/bundle.js +1 -1
  29. package/dist/webpack/node-thread/bundle.js +1 -1
  30. package/dist/webpack/webview/index.html +855 -407
  31. package/dist/webview/WebViewExecutorStream.cjs +9 -22
  32. package/dist/webview/WebViewExecutorStream.cjs.map +1 -1
  33. package/dist/webview/WebViewExecutorStream.mjs +9 -22
  34. package/dist/webview/WebViewExecutorStream.mjs.map +1 -1
  35. package/package.json +7 -7
package/CHANGELOG.md CHANGED
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [9.0.0]
11
+
12
+ ### Changed
13
+
14
+ - **BREAKING:** Drop support for Node.js 18 and 21 ([#3447](https://github.com/MetaMask/snaps/pull/3447))
15
+ - Bump `ses` from `1.12.0` to `1.13.0` ([#3438](https://github.com/MetaMask/snaps/pull/3438))
16
+
17
+ ## [8.2.0]
18
+
19
+ ### Added
20
+
21
+ - Add support for `AccountSelector` component ([#3088](https://github.com/MetaMask/snaps/pull/3088))
22
+
10
23
  ## [8.1.0]
11
24
 
12
25
  ### Added
@@ -503,7 +516,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
503
516
  - The version of the package no longer needs to match the version of all other
504
517
  MetaMask Snaps packages.
505
518
 
506
- [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@8.1.0...HEAD
519
+ [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@9.0.0...HEAD
520
+ [9.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@8.2.0...@metamask/snaps-execution-environments@9.0.0
521
+ [8.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@8.1.0...@metamask/snaps-execution-environments@8.2.0
507
522
  [8.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@8.0.1...@metamask/snaps-execution-environments@8.1.0
508
523
  [8.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@8.0.0...@metamask/snaps-execution-environments@8.0.1
509
524
  [8.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@7.2.2...@metamask/snaps-execution-environments@8.0.0
@@ -1,13 +1,7 @@
1
1
  "use strict";
2
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
- };
7
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
8
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
9
4
  };
10
- var _BaseSnapExecutor_instances, _BaseSnapExecutor_write, _BaseSnapExecutor_notify, _BaseSnapExecutor_respond;
11
5
  Object.defineProperty(exports, "__esModule", { value: true });
12
6
  exports.BaseSnapExecutor = void 0;
13
7
  // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
@@ -61,12 +55,35 @@ const EXECUTION_ENVIRONMENT_METHODS = {
61
55
  },
62
56
  };
63
57
  class BaseSnapExecutor {
58
+ // TODO: Either fix this lint violation or explain why it's necessary to
59
+ // ignore.
60
+ // eslint-disable-next-line no-restricted-syntax
61
+ snapData;
62
+ // TODO: Either fix this lint violation or explain why it's necessary to
63
+ // ignore.
64
+ // eslint-disable-next-line no-restricted-syntax
65
+ commandStream;
66
+ // TODO: Either fix this lint violation or explain why it's necessary to
67
+ // ignore.
68
+ // eslint-disable-next-line no-restricted-syntax
69
+ rpcStream;
70
+ // TODO: Either fix this lint violation or explain why it's necessary to
71
+ // ignore.
72
+ // eslint-disable-next-line no-restricted-syntax
73
+ methods;
74
+ // TODO: Either fix this lint violation or explain why it's necessary to
75
+ // ignore.
76
+ // eslint-disable-next-line no-restricted-syntax
77
+ snapErrorHandler;
78
+ // TODO: Either fix this lint violation or explain why it's necessary to
79
+ // ignore.
80
+ // eslint-disable-next-line no-restricted-syntax
81
+ snapPromiseErrorHandler;
82
+ // TODO: Either fix this lint violation or explain why it's necessary to
83
+ // ignore.
84
+ // eslint-disable-next-line no-restricted-syntax
85
+ lastTeardown = 0;
64
86
  constructor(commandStream, rpcStream) {
65
- _BaseSnapExecutor_instances.add(this);
66
- // TODO: Either fix this lint violation or explain why it's necessary to
67
- // ignore.
68
- // eslint-disable-next-line no-restricted-syntax
69
- this.lastTeardown = 0;
70
87
  this.snapData = new Map();
71
88
  this.commandStream = commandStream;
72
89
  this.commandStream.on('data', (data) => {
@@ -117,7 +134,7 @@ class BaseSnapExecutor {
117
134
  // TODO: Either fix this lint violation or explain why it's necessary to
118
135
  // ignore.
119
136
  // eslint-disable-next-line promise/no-promise-in-callback
120
- __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_notify).call(this, {
137
+ this.#notify({
121
138
  method: 'UnhandledError',
122
139
  params: {
123
140
  error: {
@@ -141,7 +158,7 @@ class BaseSnapExecutor {
141
158
  (0, superstruct_1.is)(message.id, utils_1.JsonRpcIdStruct)) {
142
159
  // Instead of throwing, we directly respond with an error.
143
160
  // We can only do this if the message ID is still valid.
144
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_write).call(this, {
161
+ await this.#write({
145
162
  error: (0, rpc_errors_1.serializeError)(rpc_errors_1.rpcErrors.internal('JSON-RPC requests must be JSON serializable objects.')),
146
163
  id: message.id,
147
164
  jsonrpc: '2.0',
@@ -154,7 +171,7 @@ class BaseSnapExecutor {
154
171
  }
155
172
  const { id, method, params } = message;
156
173
  if (!(0, utils_1.hasProperty)(EXECUTION_ENVIRONMENT_METHODS, method)) {
157
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_respond).call(this, id, {
174
+ await this.#respond(id, {
158
175
  error: rpc_errors_1.rpcErrors
159
176
  .methodNotFound({
160
177
  data: {
@@ -170,7 +187,7 @@ class BaseSnapExecutor {
170
187
  const paramsAsArray = (0, sortParams_1.sortParamKeys)(methodObject.params, params);
171
188
  const [error] = (0, superstruct_1.validate)(paramsAsArray, methodObject.struct);
172
189
  if (error) {
173
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_respond).call(this, id, {
190
+ await this.#respond(id, {
174
191
  error: rpc_errors_1.rpcErrors
175
192
  .invalidParams({
176
193
  message: `Invalid parameters for method "${method}": ${error.message}.`,
@@ -185,10 +202,10 @@ class BaseSnapExecutor {
185
202
  }
186
203
  try {
187
204
  const result = await this.methods[method](...paramsAsArray);
188
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_respond).call(this, id, { result });
205
+ await this.#respond(id, { result });
189
206
  }
190
207
  catch (rpcError) {
191
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_respond).call(this, id, {
208
+ await this.#respond(id, {
192
209
  error: (0, rpc_errors_1.serializeError)(rpcError, {
193
210
  fallbackError,
194
211
  shouldPreserveMessage: false,
@@ -196,6 +213,46 @@ class BaseSnapExecutor {
196
213
  });
197
214
  }
198
215
  }
216
+ // Awaitable function that writes back to the command stream
217
+ // To prevent snap execution from blocking writing we wrap in a promise
218
+ // and await it before continuing execution
219
+ async #write(chunk) {
220
+ return new Promise((resolve, reject) => {
221
+ this.commandStream.write(chunk, (error) => {
222
+ if (error) {
223
+ reject(error);
224
+ return;
225
+ }
226
+ resolve();
227
+ });
228
+ });
229
+ }
230
+ async #notify(notification) {
231
+ if (!(0, utils_2.isValidResponse)(notification)) {
232
+ throw rpc_errors_1.rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.');
233
+ }
234
+ await this.#write({
235
+ ...notification,
236
+ jsonrpc: '2.0',
237
+ });
238
+ }
239
+ async #respond(id, response) {
240
+ if (!(0, utils_2.isValidResponse)(response)) {
241
+ // Instead of throwing, we directly respond with an error.
242
+ // This prevents an issue where we wouldn't respond when errors were non-serializable
243
+ await this.#write({
244
+ error: (0, rpc_errors_1.serializeError)(rpc_errors_1.rpcErrors.internal('JSON-RPC responses must be JSON serializable objects smaller than 64 MB.')),
245
+ id,
246
+ jsonrpc: '2.0',
247
+ });
248
+ return;
249
+ }
250
+ await this.#write({
251
+ ...response,
252
+ id,
253
+ jsonrpc: '2.0',
254
+ });
255
+ }
199
256
  /**
200
257
  * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw
201
258
  * on errors.
@@ -240,7 +297,7 @@ class BaseSnapExecutor {
240
297
  ethereum,
241
298
  snapId,
242
299
  endowments: _endowments,
243
- notify: __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_notify).bind(this),
300
+ notify: this.#notify.bind(this),
244
301
  });
245
302
  // !!! Ensure that this is the only place the data is being set.
246
303
  // Other methods access the object value and mutate its properties.
@@ -331,14 +388,14 @@ class BaseSnapExecutor {
331
388
  return await (0, utils_2.withTeardown)((async () => {
332
389
  try {
333
390
  const promise = originalRequest(sanitizedArgs);
334
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_notify).call(this, {
391
+ await this.#notify({
335
392
  method: 'OutboundRequest',
336
393
  params: { source: 'snap.request' },
337
394
  });
338
395
  return await promise;
339
396
  }
340
397
  finally {
341
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_notify).call(this, {
398
+ await this.#notify({
342
399
  method: 'OutboundResponse',
343
400
  params: { source: 'snap.request' },
344
401
  });
@@ -366,14 +423,14 @@ class BaseSnapExecutor {
366
423
  return await (0, utils_2.withTeardown)((async () => {
367
424
  try {
368
425
  const promise = originalRequest(sanitizedArgs);
369
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_notify).call(this, {
426
+ await this.#notify({
370
427
  method: 'OutboundRequest',
371
428
  params: { source: 'ethereum.request' },
372
429
  });
373
430
  return await promise;
374
431
  }
375
432
  finally {
376
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_notify).call(this, {
433
+ await this.#notify({
377
434
  method: 'OutboundResponse',
378
435
  params: { source: 'ethereum.request' },
379
436
  });
@@ -439,43 +496,4 @@ class BaseSnapExecutor {
439
496
  }
440
497
  }
441
498
  exports.BaseSnapExecutor = BaseSnapExecutor;
442
- _BaseSnapExecutor_instances = new WeakSet(), _BaseSnapExecutor_write =
443
- // Awaitable function that writes back to the command stream
444
- // To prevent snap execution from blocking writing we wrap in a promise
445
- // and await it before continuing execution
446
- async function _BaseSnapExecutor_write(chunk) {
447
- return new Promise((resolve, reject) => {
448
- this.commandStream.write(chunk, (error) => {
449
- if (error) {
450
- reject(error);
451
- return;
452
- }
453
- resolve();
454
- });
455
- });
456
- }, _BaseSnapExecutor_notify = async function _BaseSnapExecutor_notify(notification) {
457
- if (!(0, utils_2.isValidResponse)(notification)) {
458
- throw rpc_errors_1.rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.');
459
- }
460
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_write).call(this, {
461
- ...notification,
462
- jsonrpc: '2.0',
463
- });
464
- }, _BaseSnapExecutor_respond = async function _BaseSnapExecutor_respond(id, response) {
465
- if (!(0, utils_2.isValidResponse)(response)) {
466
- // Instead of throwing, we directly respond with an error.
467
- // This prevents an issue where we wouldn't respond when errors were non-serializable
468
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_write).call(this, {
469
- error: (0, rpc_errors_1.serializeError)(rpc_errors_1.rpcErrors.internal('JSON-RPC responses must be JSON serializable objects smaller than 64 MB.')),
470
- id,
471
- jsonrpc: '2.0',
472
- });
473
- return;
474
- }
475
- await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_write).call(this, {
476
- ...response,
477
- id,
478
- jsonrpc: '2.0',
479
- });
480
- };
481
499
  //# sourceMappingURL=BaseSnapExecutor.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"BaseSnapExecutor.cjs","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;;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mCAAS,YAAkD;IAC9D,IAAI,CAAC,IAAA,uBAAe,EAAC,YAAY,CAAC,EAAE,CAAC;QACnC,MAAM,sBAAS,CAAC,QAAQ,CACtB,8EAA8E,CAC/E,CAAC;IACJ,CAAC;IAED,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;QAChB,GAAG,YAAY;QACf,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;AACL,CAAC,8BAED,KAAK,oCAAU,EAAa,EAAE,QAA8B;IAC1D,IAAI,CAAC,IAAA,uBAAe,EAAC,QAAQ,CAAC,EAAE,CAAC;QAC/B,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;YAChB,KAAK,EAAE,IAAA,2BAAc,EACnB,sBAAS,CAAC,QAAQ,CAChB,0EAA0E,CAC3E,CACF;YACD,EAAE;YACF,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;QAChB,GAAG,QAAQ;QACX,EAAE;QACF,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;AACL,CAAC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport ObjectMultiplex from '@metamask/object-multiplex';\nimport type { RequestArguments, StreamProvider } from '@metamask/providers';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsEthereumProvider, SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport { validate, is } from '@metamask/superstruct';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\n\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { SnapProvider } from './SnapProvider';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\nimport { log } from '../logging';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private readonly snapData: Map<string, SnapData>;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private readonly commandStream: Duplex;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private readonly rpcStream: Duplex;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private readonly methods: CommandMethodsMapping;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n const result = await this.executeInSnapContext(target, async () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined || result === null) {\n return null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n shouldPreserveMessage: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line promise/no-promise-in-callback\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n shouldPreserveMessage: false,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, Json>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const multiplex = new ObjectMultiplex();\n pipeline(this.rpcStream, multiplex, this.rpcStream, (error) => {\n if (error) {\n logError(`Provider stream failure.`, error);\n }\n });\n\n const provider = new SnapProvider(\n multiplex.createStream('metamask-provider'),\n {\n rpcMiddleware: [createIdRemapMiddleware()],\n },\n );\n\n provider.initializeSync();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments({\n snap,\n ethereum,\n snapId,\n endowments: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, async () => {\n compartment.evaluate(sourceCode);\n await this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private async registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n // If the module is async, we must await the exports.\n const snapExports = await snapModule.exports;\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapExports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n\n // If the Snap has no valid exports after this, fail.\n assert(Object.keys(data.exports).length > 0, 'Snap has no valid exports.');\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n // As part of the sanitization, we validate that the args are valid JSON.\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n try {\n const promise = originalRequest(sanitizedArgs);\n\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n\n return await promise;\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapsProvider = { request } as SnapsProvider;\n\n return harden(snapsProvider);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private createEIP1193Provider(\n provider: StreamProvider,\n ): SnapsEthereumProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n // As part of the sanitization, we validate that the args are valid JSON.\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n try {\n const promise = originalRequest(sanitizedArgs);\n\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n\n return await promise;\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const ethereumProvider = { request };\n\n return harden(ethereumProvider);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_resolve, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"BaseSnapExecutor.cjs","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,+DAAoE;AACpE,kFAAyD;AAEzD,qDAA6E;AAE7E,mDAAmD;AAMnD,uDAO+B;AAC/B,uDAAqD;AAOrD,2CAMyB;AAEzB,qDAA2C;AAG3C,6CAA6D;AAC7D,uDAAgD;AAChD,qDAAuE;AACvE,qDAA8C;AAC9C,iDAA6C;AAC7C,uCAMiB;AACjB,iDAKsB;AACtB,4CAAiC;AAYjC,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,uBAAU,CAAC,GAAG,CAAC,QAAQ;IAC7B,OAAO,EAAE,6BAA6B;CACvC,CAAC;AAEF,MAAM,cAAc,GAAG,sB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;YAC9C,oEAAoE;YACpE,uCAAuC;YACvC,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC;QACvD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,8BAAgB,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;gBACvC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC;gBACvB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;YAC5B,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA1iBD,4CA0iBC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport ObjectMultiplex from '@metamask/object-multiplex';\nimport type { RequestArguments, StreamProvider } from '@metamask/providers';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsEthereumProvider, SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport { validate, is } from '@metamask/superstruct';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\n\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { SnapProvider } from './SnapProvider';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\nimport { log } from '../logging';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private readonly snapData: Map<string, SnapData>;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private readonly commandStream: Duplex;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private readonly rpcStream: Duplex;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private readonly methods: CommandMethodsMapping;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n const result = await this.executeInSnapContext(target, async () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined || result === null) {\n return null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n shouldPreserveMessage: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line promise/no-promise-in-callback\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n shouldPreserveMessage: false,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, Json>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const multiplex = new ObjectMultiplex();\n pipeline(this.rpcStream, multiplex, this.rpcStream, (error) => {\n if (error) {\n logError(`Provider stream failure.`, error);\n }\n });\n\n const provider = new SnapProvider(\n multiplex.createStream('metamask-provider'),\n {\n rpcMiddleware: [createIdRemapMiddleware()],\n },\n );\n\n provider.initializeSync();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments({\n snap,\n ethereum,\n snapId,\n endowments: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, async () => {\n compartment.evaluate(sourceCode);\n await this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private async registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n // If the module is async, we must await the exports.\n const snapExports = await snapModule.exports;\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapExports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n\n // If the Snap has no valid exports after this, fail.\n assert(Object.keys(data.exports).length > 0, 'Snap has no valid exports.');\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n // As part of the sanitization, we validate that the args are valid JSON.\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n try {\n const promise = originalRequest(sanitizedArgs);\n\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n\n return await promise;\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapsProvider = { request } as SnapsProvider;\n\n return harden(snapsProvider);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private createEIP1193Provider(\n provider: StreamProvider,\n ): SnapsEthereumProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n // As part of the sanitization, we validate that the args are valid JSON.\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n try {\n const promise = originalRequest(sanitizedArgs);\n\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n\n return await promise;\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const ethereumProvider = { request };\n\n return harden(ethereumProvider);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_resolve, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}