@metamask/snaps-execution-environments 3.0.0 → 3.2.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 (45) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/dist/browserify/iframe/bundle.js +5 -5
  3. package/dist/browserify/node-process/bundle.js +4 -4
  4. package/dist/browserify/node-thread/bundle.js +4 -4
  5. package/dist/browserify/offscreen/bundle.js +4 -4
  6. package/dist/browserify/worker-executor/bundle.js +5 -5
  7. package/dist/browserify/worker-pool/bundle.js +4 -4
  8. package/dist/cjs/common/BaseSnapExecutor.js +123 -74
  9. package/dist/cjs/common/BaseSnapExecutor.js.map +1 -1
  10. package/dist/cjs/common/commands.js +2 -0
  11. package/dist/cjs/common/commands.js.map +1 -1
  12. package/dist/cjs/common/endowments/index.js +2 -1
  13. package/dist/cjs/common/endowments/index.js.map +1 -1
  14. package/dist/cjs/common/endowments/interval.js +2 -1
  15. package/dist/cjs/common/endowments/interval.js.map +1 -1
  16. package/dist/cjs/common/endowments/timeout.js +2 -1
  17. package/dist/cjs/common/endowments/timeout.js.map +1 -1
  18. package/dist/cjs/common/globalEvents.js +2 -1
  19. package/dist/cjs/common/globalEvents.js.map +1 -1
  20. package/dist/cjs/common/globalObject.js.map +1 -1
  21. package/dist/cjs/common/utils.js +7 -21
  22. package/dist/cjs/common/utils.js.map +1 -1
  23. package/dist/cjs/common/validation.js +3 -2
  24. package/dist/cjs/common/validation.js.map +1 -1
  25. package/dist/esm/common/BaseSnapExecutor.js +123 -74
  26. package/dist/esm/common/BaseSnapExecutor.js.map +1 -1
  27. package/dist/esm/common/commands.js +2 -0
  28. package/dist/esm/common/commands.js.map +1 -1
  29. package/dist/esm/common/endowments/index.js +2 -1
  30. package/dist/esm/common/endowments/index.js.map +1 -1
  31. package/dist/esm/common/endowments/interval.js +2 -1
  32. package/dist/esm/common/endowments/interval.js.map +1 -1
  33. package/dist/esm/common/endowments/timeout.js +2 -1
  34. package/dist/esm/common/endowments/timeout.js.map +1 -1
  35. package/dist/esm/common/globalEvents.js +2 -1
  36. package/dist/esm/common/globalEvents.js.map +1 -1
  37. package/dist/esm/common/globalObject.js.map +1 -1
  38. package/dist/esm/common/utils.js +7 -25
  39. package/dist/esm/common/utils.js.map +1 -1
  40. package/dist/esm/common/validation.js +3 -2
  41. package/dist/esm/common/validation.js.map +1 -1
  42. package/dist/types/common/BaseSnapExecutor.d.ts +2 -3
  43. package/dist/types/common/endowments/index.d.ts +1 -1
  44. package/dist/types/common/utils.d.ts +0 -9
  45. package/package.json +18 -19
@@ -10,11 +10,11 @@ Object.defineProperty(exports, "BaseSnapExecutor", {
10
10
  return BaseSnapExecutor;
11
11
  }
12
12
  });
13
+ const _jsonrpcengine = require("@metamask/json-rpc-engine");
13
14
  const _providers = require("@metamask/providers");
15
+ const _rpcerrors = require("@metamask/rpc-errors");
14
16
  const _snapsutils = require("@metamask/snaps-utils");
15
17
  const _utils = require("@metamask/utils");
16
- const _ethrpcerrors = require("eth-rpc-errors");
17
- const _jsonrpcengine = require("json-rpc-engine");
18
18
  const _superstruct = require("superstruct");
19
19
  const _logging = require("../logging");
20
20
  const _commands = require("./commands");
@@ -23,6 +23,21 @@ const _globalEvents = require("./globalEvents");
23
23
  const _sortParams = require("./sortParams");
24
24
  const _utils1 = require("./utils");
25
25
  const _validation = require("./validation");
26
+ function _check_private_redeclaration(obj, privateCollection) {
27
+ if (privateCollection.has(obj)) {
28
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
29
+ }
30
+ }
31
+ function _class_private_method_get(receiver, privateSet, fn) {
32
+ if (!privateSet.has(receiver)) {
33
+ throw new TypeError("attempted to get private field on non-instance");
34
+ }
35
+ return fn;
36
+ }
37
+ function _class_private_method_init(obj, privateSet) {
38
+ _check_private_redeclaration(obj, privateSet);
39
+ privateSet.add(obj);
40
+ }
26
41
  function _define_property(obj, key, value) {
27
42
  if (key in obj) {
28
43
  Object.defineProperty(obj, key, {
@@ -37,9 +52,12 @@ function _define_property(obj, key, value) {
37
52
  return obj;
38
53
  }
39
54
  const fallbackError = {
40
- code: _ethrpcerrors.errorCodes.rpc.internal,
55
+ code: _rpcerrors.errorCodes.rpc.internal,
41
56
  message: 'Execution Environment Error'
42
57
  };
58
+ const unhandledError = _rpcerrors.rpcErrors.internal({
59
+ message: 'Unhandled Snap Error'
60
+ }).serialize();
43
61
  /**
44
62
  * The supported methods in the execution environment. The validator checks the
45
63
  * incoming JSON-RPC request, and the `params` property is used for sorting the
@@ -71,36 +89,40 @@ const fallbackError = {
71
89
  ]
72
90
  }
73
91
  };
92
+ var _write = /*#__PURE__*/ new WeakSet(), _notify = /*#__PURE__*/ new WeakSet(), _respond = /*#__PURE__*/ new WeakSet();
74
93
  class BaseSnapExecutor {
75
94
  errorHandler(error, data) {
76
- const constructedError = (0, _utils1.constructError)(error);
77
- const serializedError = (0, _ethrpcerrors.serializeError)(constructedError, {
78
- fallbackError,
95
+ const serializedError = (0, _rpcerrors.serializeError)(error, {
96
+ fallbackError: unhandledError,
79
97
  shouldIncludeStack: false
80
98
  });
81
- // We're setting it this way to avoid sentData.stack = undefined
82
- const sentData = {
83
- ...data,
84
- stack: constructedError?.stack ?? null
85
- };
86
- this.notify({
99
+ const errorData = (0, _snapsutils.getErrorData)(serializedError);
100
+ _class_private_method_get(this, _notify, notify).call(this, {
87
101
  method: 'UnhandledError',
88
102
  params: {
89
103
  error: {
90
104
  ...serializedError,
91
- data: sentData
105
+ data: {
106
+ ...errorData,
107
+ ...data
108
+ }
92
109
  }
93
110
  }
111
+ }).catch((notifyError)=>{
112
+ (0, _snapsutils.logError)(notifyError);
94
113
  });
95
114
  }
96
115
  async onCommandRequest(message) {
97
116
  if (!(0, _utils.isJsonRpcRequest)(message)) {
98
- throw new Error('Command stream received a non-JSON-RPC request.');
117
+ throw _rpcerrors.rpcErrors.invalidRequest({
118
+ message: 'Command stream received a non-JSON-RPC request.',
119
+ data: message
120
+ });
99
121
  }
100
122
  const { id, method, params } = message;
101
123
  if (!(0, _utils.hasProperty)(EXECUTION_ENVIRONMENT_METHODS, method)) {
102
- this.respond(id, {
103
- error: _ethrpcerrors.ethErrors.rpc.methodNotFound({
124
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
125
+ error: _rpcerrors.rpcErrors.methodNotFound({
104
126
  data: {
105
127
  method
106
128
  }
@@ -113,8 +135,8 @@ class BaseSnapExecutor {
113
135
  const paramsAsArray = (0, _sortParams.sortParamKeys)(methodObject.params, params);
114
136
  const [error] = (0, _superstruct.validate)(paramsAsArray, methodObject.struct);
115
137
  if (error) {
116
- this.respond(id, {
117
- error: _ethrpcerrors.ethErrors.rpc.invalidParams({
138
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
139
+ error: _rpcerrors.rpcErrors.invalidParams({
118
140
  message: `Invalid parameters for method "${method}": ${error.message}.`,
119
141
  data: {
120
142
  method,
@@ -126,45 +148,17 @@ class BaseSnapExecutor {
126
148
  }
127
149
  try {
128
150
  const result = await this.methods[method](...paramsAsArray);
129
- this.respond(id, {
151
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
130
152
  result
131
153
  });
132
154
  } catch (rpcError) {
133
- this.respond(id, {
134
- error: (0, _ethrpcerrors.serializeError)(rpcError, {
155
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
156
+ error: (0, _rpcerrors.serializeError)(rpcError, {
135
157
  fallbackError
136
158
  })
137
159
  });
138
160
  }
139
161
  }
140
- notify(requestObject) {
141
- if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
142
- throw new Error('JSON-RPC notifications must be JSON serializable objects');
143
- }
144
- this.commandStream.write({
145
- ...requestObject,
146
- jsonrpc: '2.0'
147
- });
148
- }
149
- respond(id, requestObject) {
150
- if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
151
- // Instead of throwing, we directly respond with an error.
152
- // This prevents an issue where we wouldn't respond when errors were non-serializable
153
- this.commandStream.write({
154
- error: (0, _ethrpcerrors.serializeError)(new Error('JSON-RPC responses must be JSON serializable objects.'), {
155
- fallbackError
156
- }),
157
- id,
158
- jsonrpc: '2.0'
159
- });
160
- return;
161
- }
162
- this.commandStream.write({
163
- ...requestObject,
164
- id,
165
- jsonrpc: '2.0'
166
- });
167
- }
168
162
  /**
169
163
  * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw
170
164
  * on errors.
@@ -233,7 +227,13 @@ class BaseSnapExecutor {
233
227
  });
234
228
  } catch (error) {
235
229
  this.removeSnap(snapId);
236
- throw new Error(`Error while running snap '${snapId}': ${error.message}`);
230
+ const [cause] = (0, _snapsutils.unwrapError)(error);
231
+ throw _rpcerrors.rpcErrors.internal({
232
+ message: `Error while running snap '${snapId}': ${cause.message}`,
233
+ data: {
234
+ cause: cause.serialize()
235
+ }
236
+ });
237
237
  }
238
238
  }
239
239
  /**
@@ -274,16 +274,18 @@ class BaseSnapExecutor {
274
274
  const request = async (args)=>{
275
275
  const sanitizedArgs = (0, _utils1.sanitizeRequestArguments)(args);
276
276
  (0, _utils1.assertSnapOutboundRequest)(sanitizedArgs);
277
- this.notify({
278
- method: 'OutboundRequest'
279
- });
280
- try {
281
- return await (0, _utils1.withTeardown)(originalRequest(sanitizedArgs), this);
282
- } finally{
283
- this.notify({
284
- method: 'OutboundResponse'
277
+ return await (0, _utils1.withTeardown)((async ()=>{
278
+ await _class_private_method_get(this, _notify, notify).call(this, {
279
+ method: 'OutboundRequest'
285
280
  });
286
- }
281
+ try {
282
+ return await originalRequest(sanitizedArgs);
283
+ } finally{
284
+ await _class_private_method_get(this, _notify, notify).call(this, {
285
+ method: 'OutboundResponse'
286
+ });
287
+ }
288
+ })(), this);
287
289
  };
288
290
  // Proxy target is intentionally set to be an empty object, to ensure
289
291
  // that access to the prototype chain is not possible.
@@ -312,16 +314,18 @@ class BaseSnapExecutor {
312
314
  const request = async (args)=>{
313
315
  const sanitizedArgs = (0, _utils1.sanitizeRequestArguments)(args);
314
316
  (0, _utils1.assertEthereumOutboundRequest)(sanitizedArgs);
315
- this.notify({
316
- method: 'OutboundRequest'
317
- });
318
- try {
319
- return await (0, _utils1.withTeardown)(originalRequest(sanitizedArgs), this);
320
- } finally{
321
- this.notify({
322
- method: 'OutboundResponse'
317
+ return await (0, _utils1.withTeardown)((async ()=>{
318
+ await _class_private_method_get(this, _notify, notify).call(this, {
319
+ method: 'OutboundRequest'
323
320
  });
324
- }
321
+ try {
322
+ return await originalRequest(sanitizedArgs);
323
+ } finally{
324
+ await _class_private_method_get(this, _notify, notify).call(this, {
325
+ method: 'OutboundResponse'
326
+ });
327
+ }
328
+ })(), this);
325
329
  };
326
330
  const streamProviderProxy = (0, _utils1.proxyStreamProvider)(provider, request);
327
331
  return harden(streamProviderProxy);
@@ -346,11 +350,11 @@ class BaseSnapExecutor {
346
350
  */ async executeInSnapContext(snapId, executor) {
347
351
  const data = this.snapData.get(snapId);
348
352
  if (data === undefined) {
349
- throw new Error(`Tried to execute in context of unknown snap: "${snapId}".`);
353
+ throw _rpcerrors.rpcErrors.internal(`Tried to execute in context of unknown snap: "${snapId}".`);
350
354
  }
351
355
  let stop;
352
356
  const stopPromise = new Promise((_, reject)=>stop = ()=>reject(// TODO(rekmarks): Specify / standardize error code for this case.
353
- _ethrpcerrors.ethErrors.rpc.internal(`The snap "${snapId}" has been terminated during execution.`)));
357
+ _rpcerrors.rpcErrors.internal(`The snap "${snapId}" has been terminated during execution.`)));
354
358
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
355
359
  const evaluationData = {
356
360
  stop: stop
@@ -364,6 +368,8 @@ class BaseSnapExecutor {
364
368
  executor(),
365
369
  stopPromise
366
370
  ]);
371
+ } catch (error) {
372
+ throw new _snapsutils.WrappedSnapError(error);
367
373
  } finally{
368
374
  data.runningEvaluations.delete(evaluationData);
369
375
  if (data.runningEvaluations.size === 0) {
@@ -373,6 +379,12 @@ class BaseSnapExecutor {
373
379
  }
374
380
  }
375
381
  constructor(commandStream, rpcStream){
382
+ // Awaitable function that writes back to the command stream
383
+ // To prevent snap execution from blocking writing we wrap in a promise
384
+ // and await it before continuing execution
385
+ _class_private_method_init(this, _write);
386
+ _class_private_method_init(this, _notify);
387
+ _class_private_method_init(this, _respond);
376
388
  _define_property(this, "snapData", void 0);
377
389
  _define_property(this, "commandStream", void 0);
378
390
  _define_property(this, "rpcStream", void 0);
@@ -395,14 +407,14 @@ class BaseSnapExecutor {
395
407
  // before the call.
396
408
  const handler = data?.exports[handlerType];
397
409
  const { required } = _snapsutils.SNAP_EXPORTS[handlerType];
398
- (0, _utils.assert)(!required || handler !== undefined, `No ${handlerType} handler exported for snap "${target}`);
410
+ (0, _utils.assert)(!required || handler !== undefined, `No ${handlerType} handler exported for snap "${target}`, _rpcerrors.rpcErrors.methodNotSupported);
399
411
  // Certain handlers are not required. If they are not exported, we
400
412
  // return null.
401
413
  if (!handler) {
402
414
  return null;
403
415
  }
404
- // TODO: fix handler args type cast
405
- let result = await this.executeInSnapContext(target, ()=>handler(args));
416
+ let result = await this.executeInSnapContext(target, ()=>// TODO: fix handler args type cast
417
+ handler(args));
406
418
  // The handler might not return anything, but undefined is not valid JSON.
407
419
  if (result === undefined) {
408
420
  result = null;
@@ -411,10 +423,47 @@ class BaseSnapExecutor {
411
423
  try {
412
424
  return (0, _utils.getSafeJson)(result);
413
425
  } catch (error) {
414
- throw new TypeError(`Received non-JSON-serializable value: ${error.message.replace(/^Assertion failed: /u, '')}`);
426
+ throw _rpcerrors.rpcErrors.internal(`Received non-JSON-serializable value: ${error.message.replace(/^Assertion failed: /u, '')}`);
415
427
  }
416
428
  }, this.onTerminate.bind(this));
417
429
  }
418
430
  }
431
+ async function write(chunk) {
432
+ return new Promise((resolve, reject)=>{
433
+ this.commandStream.write(chunk, (error)=>{
434
+ if (error) {
435
+ reject(error);
436
+ return;
437
+ }
438
+ resolve();
439
+ });
440
+ });
441
+ }
442
+ async function notify(requestObject) {
443
+ if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
444
+ throw _rpcerrors.rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects');
445
+ }
446
+ await _class_private_method_get(this, _write, write).call(this, {
447
+ ...requestObject,
448
+ jsonrpc: '2.0'
449
+ });
450
+ }
451
+ async function respond(id, requestObject) {
452
+ if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
453
+ // Instead of throwing, we directly respond with an error.
454
+ // This prevents an issue where we wouldn't respond when errors were non-serializable
455
+ await _class_private_method_get(this, _write, write).call(this, {
456
+ error: (0, _rpcerrors.serializeError)(_rpcerrors.rpcErrors.internal('JSON-RPC responses must be JSON serializable objects.')),
457
+ id,
458
+ jsonrpc: '2.0'
459
+ });
460
+ return;
461
+ }
462
+ await _class_private_method_get(this, _write, write).call(this, {
463
+ ...requestObject,
464
+ id,
465
+ jsonrpc: '2.0'
466
+ });
467
+ }
419
468
 
420
469
  //# sourceMappingURL=BaseSnapExecutor.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport type { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n constructError,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\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\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 class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\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 );\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 // TODO: fix handler args type cast\n let result = await this.executeInSnapContext(target, () =>\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw new TypeError(\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 private errorHandler(error: unknown, data: Record<string, Json>) {\n const constructedError = constructError(error);\n const serializedError = serializeError(constructedError, {\n fallbackError,\n shouldIncludeStack: false,\n });\n\n // We're setting it this way to avoid sentData.stack = undefined\n const sentData: Json = { ...data, stack: constructedError?.stack ?? null };\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: sentData,\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw new Error('Command stream received a non-JSON-RPC request.');\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\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 this.respond(id, {\n error: ethErrors.rpc\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 this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\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 this.commandStream.write({\n error: serializeError(\n new Error('JSON-RPC responses must be JSON serializable objects.'),\n {\n fallbackError,\n },\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n this.commandStream.write({\n ...requestObject,\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 provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\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,\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 // 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, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n throw new Error(\n `Error while running snap '${snapId}': ${(error as Error).message}`,\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 private 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 data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\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 private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(sanitizedArgs), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\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 private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(sanitizedArgs), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\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 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 new Error(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n ethErrors.rpc.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 } 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"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","constructedError","constructError","serializedError","serializeError","shouldIncludeStack","sentData","stack","notify","method","onCommandRequest","isJsonRpcRequest","Error","id","hasProperty","respond","ethErrors","methodNotFound","serialize","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","result","methods","rpcError","requestObject","isValidJson","isObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validator","SNAP_EXPORTS","originalRequest","request","bind","args","sanitizedArgs","sanitizeRequestArguments","assertSnapOutboundRequest","withTeardown","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","logError","getCommandMethodImplementations","target","handlerType","handler","required","assert","getSafeJson","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BAuGnDA;;;eAAAA;;;2BAtGkB;4BAYxB;uBAcA;8BAC+C;+BACd;6BAEf;yBAEL;0BAE4B;4BACf;8BACqB;4BACxB;wBAQvB;4BAMA;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;IACpBC,MAAMC,wBAAU,CAACC,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAUA;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQC,sCAA0B;QAClCC,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXH,QAAQI,6CAAiC;QACzCF,QAAQ;YAAC;YAAU;YAAc;SAAa;IAChD;IACAG,WAAW;QACTL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 {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"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 { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';\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 getErrorData,\n unwrapError,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\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 class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\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 let result = await this.executeInSnapContext(target, () =>\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) {\n result = 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 private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\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 private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw rpcErrors.invalidRequest({\n message: 'Command stream received a non-JSON-RPC request.',\n data: message,\n });\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 }),\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(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n await this.#write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\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.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...requestObject,\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 provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\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,\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, () => {\n compartment.evaluate(sourceCode);\n 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 private 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 data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\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 private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({ method: 'OutboundRequest' });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({ method: 'OutboundResponse' });\n }\n })(),\n this as any,\n );\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\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 private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({ method: 'OutboundRequest' });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({ method: 'OutboundResponse' });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\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 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 (_, 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"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","unhandledError","rpcErrors","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","serializedError","serializeError","shouldIncludeStack","errorData","getErrorData","notify","method","catch","notifyError","logError","onCommandRequest","isJsonRpcRequest","invalidRequest","id","hasProperty","respond","methodNotFound","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","result","methods","rpcError","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","Error","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","unwrapError","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validator","SNAP_EXPORTS","originalRequest","request","bind","args","sanitizedArgs","sanitizeRequestArguments","assertSnapOutboundRequest","withTeardown","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","WrappedSnapError","size","lastTeardown","commandStream","Map","on","getCommandMethodImplementations","target","handlerType","handler","required","assert","methodNotSupported","getSafeJson","replace","chunk","resolve","write","requestObject","isValidJson","isObject","jsonrpc"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BA+GnDA;;;eAAAA;;;+BA9G2B;2BACT;2BAEuB;4BAc/C;uBAcA;6BAEkB;yBAEL;0BAE4B;4BACf;8BACqB;4BACxB;wBAOvB;4BAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;IACpBC,MAAMC,qBAAU,CAACC,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAEA,MAAMC,iBAAiBC,oBAAS,CAC7BH,QAAQ,CAAO;IACdC,SAAS;AACX,GACCG,SAAS;AAUZ;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQC,sCAA0B;QAClCC,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXH,QAAQI,6CAAiC;QACzCF,QAAQ;YAAC;YAAU;YAAc;SAAa;IAChD;IAC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CAACgJ,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAACvD,WAAW,CAACe,IAAI,CAAC,IAAI;IAE9B;AA8YF;AAzTE,eAAA,MAAayC,KAAW;IACtB,OAAO,IAAIrB,QAAc,CAACsB,SAASpB;QACjC,IAAI,CAACO,aAAa,CAACc,KAAK,CAACF,OAAO,CAACjI;YAC/B,IAAIA,OAAO;gBACT8G,OAAO9G;gBACP;YACF;YACAkI;QACF;IACF;AACF;AAEA,eAAA,OAAcE,aAAmD;IAC/D,IAAI,CAACC,IAAAA,kBAAW,EAACD,kBAAkB,CAACE,IAAAA,eAAQ,EAACF,gBAAgB;QAC3D,MAAMlJ,oBAAS,CAACH,QAAQ,CACtB;IAEJ;IAEA,MAAM,0BAAA,IAAI,EAAEoJ,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBG,SAAS;IACX;AACF;AAEA,eAAA,QAAexH,EAAa,EAAEqH,aAAsC;IAClE,IAAI,CAACC,IAAAA,kBAAW,EAACD,kBAAkB,CAACE,IAAAA,eAAQ,EAACF,gBAAgB;QAC3D,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,0BAAA,IAAI,EAAED,QAAAA,YAAN,IAAI,EAAQ;YAChBnI,OAAOG,IAAAA,yBAAc,EACnBjB,oBAAS,CAACH,QAAQ,CAChB;YAGJgC;YACAwH,SAAS;QACX;QACA;IACF;IAEA,MAAM,0BAAA,IAAI,EAAEJ,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBrH;QACAwH,SAAS;IACX;AACF"}
@@ -58,6 +58,8 @@ function getHandlerArguments(origin, handler, request) {
58
58
  return {
59
59
  request
60
60
  };
61
+ case _snapsutils.HandlerType.OnHomePage:
62
+ return {};
61
63
  default:
62
64
  return (0, _utils.assertExhaustive)(handler);
63
65
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnNameLookup","assertIsOnNameLookupRequestArguments","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IAgCgBA,mBAAmB;eAAnBA;;IA6DAC,+BAA+B;eAA/BA;;;4BA7FY;uBACK;4BAc1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKN,uBAAW,CAACO,YAAY;YAAE;gBAC7BC,IAAAA,gDAAoC,EAACT,QAAQI,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEI,MAAM,EAAEC,OAAO,EAAE,GAChCX,QAAQI,MAAM;gBAEhB,OAAOM,SACH;oBACEJ;oBACAI;gBACF,IACA;oBACEJ;oBACAK;gBACF;YACN;QACA,KAAKV,uBAAW,CAACW,YAAY;QAC7B,KAAKX,uBAAW,CAACY,gBAAgB;YAC/B,OAAO;gBAAEf;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACa,SAAS;QAC1B,KAAKb,uBAAW,CAACc,SAAS;QAC1B,KAAKd,uBAAW,CAACe,QAAQ;YACvB,OAAO;gBAAEhB;YAAQ;QAEnB;YACE,OAAOiB,IAAAA,uBAAgB,EAAClB;IAC5B;AACF;AAaO,SAASF,gCACdqB,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQ/B,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMmB,WACLW,QACA/B,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n case HandlerType.OnHomePage:\n return {};\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnNameLookup","assertIsOnNameLookupRequestArguments","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","OnHomePage","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IAgCgBA,mBAAmB;eAAnBA;;IAgEAC,+BAA+B;eAA/BA;;;4BAhGY;uBACK;4BAc1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKN,uBAAW,CAACO,YAAY;YAAE;gBAC7BC,IAAAA,gDAAoC,EAACT,QAAQI,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEI,MAAM,EAAEC,OAAO,EAAE,GAChCX,QAAQI,MAAM;gBAEhB,OAAOM,SACH;oBACEJ;oBACAI;gBACF,IACA;oBACEJ;oBACAK;gBACF;YACN;QACA,KAAKV,uBAAW,CAACW,YAAY;QAC7B,KAAKX,uBAAW,CAACY,gBAAgB;YAC/B,OAAO;gBAAEf;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACa,SAAS;QAC1B,KAAKb,uBAAW,CAACc,SAAS;QAC1B,KAAKd,uBAAW,CAACe,QAAQ;YACvB,OAAO;gBAAEhB;YAAQ;QAEnB,KAAKC,uBAAW,CAACgB,UAAU;YACzB,OAAO,CAAC;QAEV;YACE,OAAOC,IAAAA,uBAAgB,EAACnB;IAC5B;AACF;AAaO,SAASF,gCACdsB,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQhC,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMoB,WACLW,QACAhC,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
@@ -8,6 +8,7 @@ Object.defineProperty(exports, "createEndowments", {
8
8
  return createEndowments;
9
9
  }
10
10
  });
11
+ const _rpcerrors = require("@metamask/rpc-errors");
11
12
  const _snapsutils = require("@metamask/snaps-utils");
12
13
  const _utils = require("@metamask/utils");
13
14
  const _globalObject = require("../globalObject");
@@ -67,7 +68,7 @@ function createEndowments(snap, ethereum, snapId, endowments = []) {
67
68
  } else {
68
69
  // If we get to this point, we've been passed an endowment that doesn't
69
70
  // exist in our current environment.
70
- throw new Error(`Unknown endowment: "${endowmentName}".`);
71
+ throw _rpcerrors.rpcErrors.internal(`Unknown endowment: "${endowmentName}".`);
71
72
  }
72
73
  return {
73
74
  allEndowments,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport type { SnapId } from '@metamask/snaps-utils';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n snapId: SnapId,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw new Error(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"],"names":["createEndowments","registeredEndowments","buildCommonEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","snap","ethereum","snapId","endowments","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","hasProperty","teardownFunction","endowment","get","Object","assign","push","rootRealmGlobal","logWarning","globalValue","Error","teardown","Promise","all","map"],"mappings":";;;;+BAqDgBA;;;eAAAA;;;4BAlDW;uBACC;8BAEI;+EAEE;;;;;;AAelC;;CAEC,GACD,MAAMC,uBAAuBC,IAAAA,+BAAqB;AAElD;;;;CAIC,GACD,MAAMC,qBAAqBF,qBAAqBG,MAAM,CAAC,CAACC,WAAWC;IACjEA,QAAQC,KAAK,CAACC,OAAO,CAAC,CAACC;QACrBJ,UAAUK,GAAG,CAACD,MAAMH,QAAQK,OAAO;IACrC;IACA,OAAON;AACT,GAAG,IAAIO;AAeA,SAASZ,iBACda,I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,MAAMC,QAAQC,GAAG,CACflB,OAAOE,SAAS,CAACiB,GAAG,CAAC,CAACb,mBAAqBA;IAE/C;IACA,OAAO;QAAER,YAAYE,OAAOC,aAAa;QAAEe;IAAS;AACtD"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';\nimport type { SnapId } from '@metamask/snaps-utils';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n snapId: SnapId,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw rpcErrors.internal(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"],"names":["createEndowments","registeredEndowments","buildCommonEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","snap","ethereum","snapId","endowments","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","hasProperty","teardownFunction","endowment","get","Object","assign","push","rootRealmGlobal","logWarning","globalValue","rpcErrors","internal","teardown","Promise","all","map"],"mappings":";;;;+BAsDgBA;;;eAAAA;;;2BArDU;4BAGC;uBACC;8BAEI;+EAEE;;;;;;AAelC;;CAEC,GACD,MAAMC,uBAAuBC,IAAAA,+BAAqB;AAElD;;;;CAIC,GACD,MAAMC,qBAAqBF,qBAAqBG,MAAM,CAAC,CAACC,WAAWC;IACjEA,QAAQC,KAAK,CAACC,OAAO,CAAC,CAACC;QACrBJ,UAAUK,GAAG,CAACD,MAAMH,QAAQK,OAAO;IACrC;IACA,OAAON;AACT,GAAG,IAAIO;AAeA,SAASZ,iBACda,IAAuB,EACvBC,QAAwB,EACxBC,MAAc,EACdC,aAAuB,EAAE;IAEzB,MAAMC,uBAAgD,CAAC;IAEvD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAMC,SAASF,WAAWZ,MAAM,CAI9B,CAAC,EAAEe,aAAa,EAAEC,SAAS,EAAE,EAAEC;QAC7B,oEAAoE;QACpE,IAAIlB,mBAAmBmB,GAAG,CAACD,gBAAgB;YACzC,IAAI,CAACE,IAAAA,kBAAW,EAACN,sBAAsBI,gBAAgB;gBACrD,uEAAuE;gBACvE,gEAAgE;gBAChE,wEAAwE;gBACxE,4CAA4C;gBAC5C,2DAA2D;gBAE3D,mEAAmE;gBACnE,oEAAoE;gBACpE,MAAM,EAAEG,gBAAgB,EAAE,GAAGC,WAAW,GAAGtB,mBAAmBuB,GAAG,CAC/DL,eACC;oBAAEN;gBAAO;gBACZY,OAAOC,MAAM,CAACX,sBAAsBQ;gBACpC,IAAID,kBAAkB;oBACpBJ,UAAUS,IAAI,CAACL;gBACjB;YACF;YACAL,aAAa,CAACE,cAAc,GAAGJ,oBAAoB,CAACI,cAAc;QACpE,OAAO,IAAIA,kBAAkB,YAAY;YACvC,iDAAiD;YACjDF,aAAa,CAACE,cAAc,GAAGP;QACjC,OAAO,IAAIO,iBAAiBS,6BAAe,EAAE;YAC3CC,IAAAA,sBAAU,EAAC,CAAC,4BAA4B,EAAEV,cAAc,CAAC,CAAC;YAC1D,uEAAuE;YACvE,iBAAiB;YACjB,MAAMW,cAAc,AAACF,6BAAe,AAA4B,CAC9DT,cACD;YACDF,aAAa,CAACE,cAAc,GAAGW;QACjC,OAAO;YACL,uEAAuE;YACvE,oCAAoC;YACpC,MAAMC,oBAAS,CAACC,QAAQ,CAAC,CAAC,oBAAoB,EAAEb,cAAc,EAAE,CAAC;QACnE;QACA,OAAO;YAAEF;YAAeC;QAAU;IACpC,GACA;QACED,eAAe;YAAEN;QAAK;QACtBO,WAAW,EAAE;IACf;IAGF,MAAMe,WAAW;QACf,MAAMC,QAAQC,GAAG,CACfnB,OAAOE,SAAS,CAACkB,GAAG,CAAC,CAACd,mBAAqBA;IAE/C;IACA,OAAO;QAAER,YAAYE,OAAOC,aAAa;QAAEgB;IAAS;AACtD"}
@@ -8,6 +8,7 @@ Object.defineProperty(exports, "default", {
8
8
  return _default;
9
9
  }
10
10
  });
11
+ const _rpcerrors = require("@metamask/rpc-errors");
11
12
  const MINIMUM_INTERVAL = 10;
12
13
  /**
13
14
  * Creates a pair of `setInterval` and `clearInterval` functions attenuated such
@@ -22,7 +23,7 @@ const MINIMUM_INTERVAL = 10;
22
23
  const registeredHandles = new Map();
23
24
  const _setInterval = (handler, timeout)=>{
24
25
  if (typeof handler !== 'function') {
25
- throw new Error(`The interval handler must be a function. Received: ${typeof handler}`);
26
+ throw _rpcerrors.rpcErrors.invalidInput(`The interval handler must be a function. Received: ${typeof handler}.`);
26
27
  }
27
28
  harden(handler);
28
29
  const handle = Object.freeze(Object.create(null));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/interval.ts"],"sourcesContent":["const MINIMUM_INTERVAL = 10;\n\n/**\n * Creates a pair of `setInterval` and `clearInterval` functions attenuated such\n * that:\n * - `setInterval` throws if its \"handler\" parameter is not a function.\n * - `clearInterval` only clears timeouts created by its sibling `setInterval`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setInterval` and `clearInterval`\n * functions.\n */\nconst createInterval = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setInterval = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The interval handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setInterval(\n handler,\n Math.max(MINIMUM_INTERVAL, timeout ?? 0),\n );\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearInterval = (handle: unknown): void => {\n harden(handle);\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearInterval(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearInterval(handle);\n }\n };\n\n return {\n setInterval: harden(_setInterval),\n clearInterval: harden(_clearInterval),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setInterval', 'clearInterval'] as const,\n factory: createInterval,\n};\nexport default endowmentModule;\n"],"names":["MINIMUM_INTERVAL","createInterval","registeredHandles","Map","_setInterval","handler","timeout","Error","harden","handle","Object","freeze","create","platformHandle","setInterval","Math","max","set","_clearInterval","get","undefined","clearInterval","delete","teardownFunction","keys","endowmentModule","names","factory"],"mappings":";;;;+BAyDA;;;eAAA;;;AAzDA,MAAMA,mBAAmB;AAEzB;;;;;;;;;CASC,GACD,MAAMC,iBAAiB;IACrB,MAAMC,oBAAoB,IAAIC;IAE9B,MAAMC,eAAe,CAACC,SAAuBC;QAC3C,IAAI,OAAOD,YAAY,YAAY;YACjC,MAAM,IAAIE,MACR,CAAC,mDAAmD,EAAE,OAAOF,QAAQ,CAAC;QAE1E;QACAG,OAAOH;QACP,MAAMI,SAASC,OAAOC,MAAM,CAACD,OAAOE,MAAM,CAAC;QAC3C,MAAMC,iBAAiBC,YACrBT,SACAU,KAAKC,GAAG,CAAChB,kBAAkBM,WAAW;QAExCJ,kBAAkBe,GAAG,CAACR,QAAQI;QAC9B,OAAOJ;IACT;IAEA,MAAMS,iBAAiB,CAACT;QACtBD,OAAOC;QACP,MAAMI,iBAAiBX,kBAAkBiB,GAAG,CAACV;QAC7C,IAAII,mBAAmBO,WAAW;YAChCC,cAAcR;YACdX,kBAAkBoB,MAAM,CAACb;QAC3B;IACF;IAEA,MAAMc,mBAAmB;QACvB,KAAK,MAAMd,UAAUP,kBAAkBsB,IAAI,GAAI;YAC7CN,eAAeT;QACjB;IACF;IAEA,OAAO;QACLK,aAAaN,OAAOJ;QACpBiB,eAAeb,OAAOU;QACtBK;IACF;AACF;AAEA,MAAME,kBAAkB;IACtBC,OAAO;QAAC;QAAe;KAAgB;IACvCC,SAAS1B;AACX;MACA,WAAewB"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/interval.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\n\nconst MINIMUM_INTERVAL = 10;\n\n/**\n * Creates a pair of `setInterval` and `clearInterval` functions attenuated such\n * that:\n * - `setInterval` throws if its \"handler\" parameter is not a function.\n * - `clearInterval` only clears timeouts created by its sibling `setInterval`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setInterval` and `clearInterval`\n * functions.\n */\nconst createInterval = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setInterval = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw rpcErrors.invalidInput(\n `The interval handler must be a function. Received: ${typeof handler}.`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setInterval(\n handler,\n Math.max(MINIMUM_INTERVAL, timeout ?? 0),\n );\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearInterval = (handle: unknown): void => {\n harden(handle);\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearInterval(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearInterval(handle);\n }\n };\n\n return {\n setInterval: harden(_setInterval),\n clearInterval: harden(_clearInterval),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setInterval', 'clearInterval'] as const,\n factory: createInterval,\n};\nexport default endowmentModule;\n"],"names":["MINIMUM_INTERVAL","createInterval","registeredHandles","Map","_setInterval","handler","timeout","rpcErrors","invalidInput","harden","handle","Object","freeze","create","platformHandle","setInterval","Math","max","set","_clearInterval","get","undefined","clearInterval","delete","teardownFunction","keys","endowmentModule","names","factory"],"mappings":";;;;+BA2DA;;;eAAA;;;2BA3D0B;AAE1B,MAAMA,mBAAmB;AAEzB;;;;;;;;;CASC,GACD,MAAMC,iBAAiB;IACrB,MAAMC,oBAAoB,IAAIC;IAE9B,MAAMC,eAAe,CAACC,SAAuBC;QAC3C,IAAI,OAAOD,YAAY,YAAY;YACjC,MAAME,oBAAS,CAACC,YAAY,CAC1B,CAAC,mDAAmD,EAAE,OAAOH,QAAQ,CAAC,CAAC;QAE3E;QACAI,OAAOJ;QACP,MAAMK,SAASC,OAAOC,MAAM,CAACD,OAAOE,MAAM,CAAC;QAC3C,MAAMC,iBAAiBC,YACrBV,SACAW,KAAKC,GAAG,CAACjB,kBAAkBM,WAAW;QAExCJ,kBAAkBgB,GAAG,CAACR,QAAQI;QAC9B,OAAOJ;IACT;IAEA,MAAMS,iBAAiB,CAACT;QACtBD,OAAOC;QACP,MAAMI,iBAAiBZ,kBAAkBkB,GAAG,CAACV;QAC7C,IAAII,mBAAmBO,WAAW;YAChCC,cAAcR;YACdZ,kBAAkBqB,MAAM,CAACb;QAC3B;IACF;IAEA,MAAMc,mBAAmB;QACvB,KAAK,MAAMd,UAAUR,kBAAkBuB,IAAI,GAAI;YAC7CN,eAAeT;QACjB;IACF;IAEA,OAAO;QACLK,aAAaN,OAAOL;QACpBkB,eAAeb,OAAOU;QACtBK;IACF;AACF;AAEA,MAAME,kBAAkB;IACtBC,OAAO;QAAC;QAAe;KAAgB;IACvCC,SAAS3B;AACX;MACA,WAAeyB"}
@@ -8,6 +8,7 @@ Object.defineProperty(exports, "default", {
8
8
  return _default;
9
9
  }
10
10
  });
11
+ const _rpcerrors = require("@metamask/rpc-errors");
11
12
  const MINIMUM_TIMEOUT = 10;
12
13
  /**
13
14
  * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such
@@ -22,7 +23,7 @@ const MINIMUM_TIMEOUT = 10;
22
23
  const registeredHandles = new Map();
23
24
  const _setTimeout = (handler, timeout)=>{
24
25
  if (typeof handler !== 'function') {
25
- throw new Error(`The timeout handler must be a function. Received: ${typeof handler}`);
26
+ throw _rpcerrors.rpcErrors.internal(`The timeout handler must be a function. Received: ${typeof handler}.`);
26
27
  }
27
28
  harden(handler);
28
29
  const handle = Object.freeze(Object.create(null));