@metamask/snaps-execution-environments 0.24.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 (83) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +3 -0
  3. package/dist/common/BaseSnapExecutor.d.ts +68 -0
  4. package/dist/common/BaseSnapExecutor.js +324 -0
  5. package/dist/common/BaseSnapExecutor.js.map +1 -0
  6. package/dist/common/commands.d.ts +30 -0
  7. package/dist/common/commands.js +68 -0
  8. package/dist/common/commands.js.map +1 -0
  9. package/dist/common/endowments/crypto.d.ts +8 -0
  10. package/dist/common/endowments/crypto.js +25 -0
  11. package/dist/common/endowments/crypto.js.map +1 -0
  12. package/dist/common/endowments/index.d.ts +25 -0
  13. package/dist/common/endowments/index.js +122 -0
  14. package/dist/common/endowments/index.js.map +1 -0
  15. package/dist/common/endowments/interval.d.ts +9 -0
  16. package/dist/common/endowments/interval.js +47 -0
  17. package/dist/common/endowments/interval.js.map +1 -0
  18. package/dist/common/endowments/math.d.ts +60 -0
  19. package/dist/common/endowments/math.js +48 -0
  20. package/dist/common/endowments/math.js.map +1 -0
  21. package/dist/common/endowments/network.d.ts +48 -0
  22. package/dist/common/endowments/network.js +362 -0
  23. package/dist/common/endowments/network.js.map +1 -0
  24. package/dist/common/endowments/timeout.d.ts +9 -0
  25. package/dist/common/endowments/timeout.js +50 -0
  26. package/dist/common/endowments/timeout.js.map +1 -0
  27. package/dist/common/globalEvents.d.ts +19 -0
  28. package/dist/common/globalEvents.js +47 -0
  29. package/dist/common/globalEvents.js.map +1 -0
  30. package/dist/common/globalObject.d.ts +9 -0
  31. package/dist/common/globalObject.js +48 -0
  32. package/dist/common/globalObject.js.map +1 -0
  33. package/dist/common/keyring.d.ts +12 -0
  34. package/dist/common/keyring.js +42 -0
  35. package/dist/common/keyring.js.map +1 -0
  36. package/dist/common/lockdown/lockdown-more.d.ts +22 -0
  37. package/dist/common/lockdown/lockdown-more.js +88 -0
  38. package/dist/common/lockdown/lockdown-more.js.map +1 -0
  39. package/dist/common/lockdown/lockdown.d.ts +7 -0
  40. package/dist/common/lockdown/lockdown.js +28 -0
  41. package/dist/common/lockdown/lockdown.js.map +1 -0
  42. package/dist/common/sortParams.d.ts +16 -0
  43. package/dist/common/sortParams.js +32 -0
  44. package/dist/common/sortParams.js.map +1 -0
  45. package/dist/common/utils.d.ts +38 -0
  46. package/dist/common/utils.js +98 -0
  47. package/dist/common/utils.js.map +1 -0
  48. package/dist/common/validation.d.ts +100 -0
  49. package/dist/common/validation.js +110 -0
  50. package/dist/common/validation.js.map +1 -0
  51. package/dist/iframe/IFrameSnapExecutor.d.ts +11 -0
  52. package/dist/iframe/IFrameSnapExecutor.js +41 -0
  53. package/dist/iframe/IFrameSnapExecutor.js.map +1 -0
  54. package/dist/iframe/index.d.ts +1 -0
  55. package/dist/iframe/index.js +9 -0
  56. package/dist/iframe/index.js.map +1 -0
  57. package/dist/iframe-test/index.d.ts +1 -0
  58. package/dist/iframe-test/index.js +8 -0
  59. package/dist/iframe-test/index.js.map +1 -0
  60. package/dist/node-process/ChildProcessSnapExecutor.d.ts +4 -0
  61. package/dist/node-process/ChildProcessSnapExecutor.js +29 -0
  62. package/dist/node-process/ChildProcessSnapExecutor.js.map +1 -0
  63. package/dist/node-process/index.d.ts +1 -0
  64. package/dist/node-process/index.js +9 -0
  65. package/dist/node-process/index.js.map +1 -0
  66. package/dist/node-thread/ThreadSnapExecutor.d.ts +4 -0
  67. package/dist/node-thread/ThreadSnapExecutor.js +29 -0
  68. package/dist/node-thread/ThreadSnapExecutor.js.map +1 -0
  69. package/dist/node-thread/index.d.ts +1 -0
  70. package/dist/node-thread/index.js +9 -0
  71. package/dist/node-thread/index.js.map +1 -0
  72. package/dist/openrpc.json +210 -0
  73. package/dist/webpack/iframe/bundle.js +2 -0
  74. package/dist/webpack/iframe/bundle.js.LICENSE.txt +21 -0
  75. package/dist/webpack/iframe/index.html +10 -0
  76. package/dist/webpack/iframe/lockdown.umd.min.js +1 -0
  77. package/dist/webpack/node-process/bundle.js +1784 -0
  78. package/dist/webpack/node-process/bundle.js.LICENSE.txt +3 -0
  79. package/dist/webpack/node-process/lockdown.umd.min.js +1 -0
  80. package/dist/webpack/node-thread/bundle.js +1784 -0
  81. package/dist/webpack/node-thread/bundle.js.LICENSE.txt +3 -0
  82. package/dist/webpack/node-thread/lockdown.umd.min.js +1 -0
  83. package/package.json +88 -0
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright ConsenSys Software Inc. 2022. All rights reserved.
2
+
3
+ You acknowledge and agree that ConsenSys Software Inc. (“ConsenSys”) (or ConsenSys’s licensors) own all legal right, title and interest in and to the work, software, application, source code, documentation and any other documents in this repository (collectively, the “Program”), including any intellectual property rights which subsist in the Program (whether those rights happen to be registered or not, and wherever in the world those rights may exist), whether in source code or any other form.
4
+
5
+ Subject to the limited license below, you may not (and you may not permit anyone else to) distribute, publish, copy, modify, merge, combine with another program, create derivative works of, reverse engineer, decompile or otherwise attempt to extract the source code of, the Program or any part thereof, except that you may contribute to this repository.
6
+
7
+ You are granted a non-exclusive, non-transferable, non-sublicensable license to distribute, publish, copy, modify, merge, combine with another program or create derivative works of the Program (such resulting program, collectively, the “Resulting Program”) solely for Non-Commercial Use as long as you:
8
+
9
+ 1. give prominent notice (“Notice”) with each copy of the Resulting Program that the Program is used in the Resulting Program and that the Program is the copyright of ConsenSys; and
10
+ 2. subject the Resulting Program and any distribution, publication, copy, modification, merger therewith, combination with another program or derivative works thereof to the same Notice requirement and Non-Commercial Use restriction set forth herein.
11
+
12
+ “Non-Commercial Use” means each use as described in clauses (1)-(3) below, as reasonably determined by ConsenSys in its sole discretion:
13
+
14
+ 1. personal use for research, personal study, private entertainment, hobby projects or amateur pursuits, in each case without any anticipated commercial application;
15
+ 2. use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization or government institution; or
16
+ 3. the number of monthly active users of the Resulting Program across all versions thereof and platforms globally do not exceed 10,000 at any time.
17
+
18
+ You will not use any trade mark, service mark, trade name, logo of ConsenSys or any other company or organization in a way that is likely or intended to cause confusion about the owner or authorized user of such marks, names or logos.
19
+
20
+ If you have any questions, comments or interest in pursuing any other use cases, please reach out to us at metamask.license@consensys.net.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @metamask/snaps-execution-environments
2
+
3
+ Execution environments for [MetaMask Snaps](https://docs.metamask.io/guide/snaps.html), sandboxed using [Secure EcmaScript (SES)](https://github.com/endojs/endo/tree/master/packages/ses).
@@ -0,0 +1,68 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="ses" />
3
+ import { Duplex } from 'stream';
4
+ import { JsonRpcNotification, JsonRpcId, Json } from '@metamask/utils';
5
+ import { HandlerType, SnapExportsParameters } from '@metamask/snaps-utils';
6
+ export declare type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;
7
+ export declare type InvokeSnap = (target: string, handler: HandlerType, args: InvokeSnapArgs | undefined) => Promise<Json>;
8
+ export declare class BaseSnapExecutor {
9
+ private snapData;
10
+ private commandStream;
11
+ private rpcStream;
12
+ private methods;
13
+ private snapErrorHandler?;
14
+ private snapPromiseErrorHandler?;
15
+ private lastTeardown;
16
+ protected constructor(commandStream: Duplex, rpcStream: Duplex);
17
+ private errorHandler;
18
+ private onCommandRequest;
19
+ protected notify(requestObject: Omit<JsonRpcNotification<Record<string, Json> | Json[] | undefined>, 'jsonrpc'>): void;
20
+ protected respond(id: JsonRpcId, requestObject: Record<string, unknown>): void;
21
+ /**
22
+ * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw
23
+ * on errors.
24
+ *
25
+ * @param snapName - The name of the snap.
26
+ * @param sourceCode - The source code of the snap, in IIFE format.
27
+ * @param _endowments - An array of the names of the endowments.
28
+ */
29
+ protected startSnap(snapName: string, sourceCode: string, _endowments?: string[]): Promise<void>;
30
+ /**
31
+ * Cancels all running evaluations of all snaps and clears all snap data.
32
+ * NOTE:** Should only be called in response to the `terminate` RPC command.
33
+ */
34
+ protected onTerminate(): void;
35
+ private registerSnapExports;
36
+ /**
37
+ * Instantiates a snap API object (i.e. `globalThis.snap`).
38
+ *
39
+ * @param provider - A StreamProvider connected to MetaMask.
40
+ * @returns The snap provider object.
41
+ */
42
+ private createSnapGlobal;
43
+ /**
44
+ * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).
45
+ *
46
+ * @param provider - A StreamProvider connected to MetaMask.
47
+ * @returns The EIP-1193 Ethereum provider object.
48
+ */
49
+ private createEIP1193Provider;
50
+ /**
51
+ * Removes the snap with the given name.
52
+ *
53
+ * @param snapName - The name of the snap to remove.
54
+ */
55
+ private removeSnap;
56
+ /**
57
+ * Calls the specified executor function in the context of the specified snap.
58
+ * Essentially, this means that the operation performed by the executor is
59
+ * counted as an evaluation of the specified snap. When the count of running
60
+ * evaluations of a snap reaches zero, its endowments are torn down.
61
+ *
62
+ * @param snapName - The name of the snap whose context to execute in.
63
+ * @param executor - The function that will be executed in the snap's context.
64
+ * @returns The executor's return value.
65
+ * @template Result - The return value of the executor.
66
+ */
67
+ private executeInSnapContext;
68
+ }
@@ -0,0 +1,324 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BaseSnapExecutor = void 0;
7
+ const providers_1 = require("@metamask/providers");
8
+ const json_rpc_engine_1 = require("json-rpc-engine");
9
+ const eth_rpc_errors_1 = require("eth-rpc-errors");
10
+ const utils_1 = require("@metamask/utils");
11
+ const snaps_utils_1 = require("@metamask/snaps-utils");
12
+ const superstruct_1 = require("superstruct");
13
+ const openrpc_json_1 = __importDefault(require("../openrpc.json"));
14
+ const commands_1 = require("./commands");
15
+ const endowments_1 = require("./endowments");
16
+ const globalEvents_1 = require("./globalEvents");
17
+ const keyring_1 = require("./keyring");
18
+ const sortParams_1 = require("./sortParams");
19
+ const utils_2 = require("./utils");
20
+ const validation_1 = require("./validation");
21
+ const fallbackError = {
22
+ code: eth_rpc_errors_1.errorCodes.rpc.internal,
23
+ message: 'Execution Environment Error',
24
+ };
25
+ /**
26
+ * The supported methods in the execution environment. The validator checks the
27
+ * incoming JSON-RPC request, and the `params` property is used for sorting the
28
+ * parameters, if they are an object.
29
+ */
30
+ const EXECUTION_ENVIRONMENT_METHODS = {
31
+ ping: {
32
+ struct: validation_1.PingRequestArgumentsStruct,
33
+ params: [],
34
+ },
35
+ executeSnap: {
36
+ struct: validation_1.ExecuteSnapRequestArgumentsStruct,
37
+ params: ['snapName', 'sourceCode', 'endowments'],
38
+ },
39
+ terminate: {
40
+ struct: validation_1.TerminateRequestArgumentsStruct,
41
+ params: [],
42
+ },
43
+ snapRpc: {
44
+ struct: validation_1.SnapRpcRequestArgumentsStruct,
45
+ params: ['target', 'handler', 'origin', 'request'],
46
+ },
47
+ };
48
+ class BaseSnapExecutor {
49
+ constructor(commandStream, rpcStream) {
50
+ this.lastTeardown = 0;
51
+ this.snapData = new Map();
52
+ this.commandStream = commandStream;
53
+ this.commandStream.on('data', this.onCommandRequest.bind(this));
54
+ this.rpcStream = rpcStream;
55
+ this.methods = (0, commands_1.getCommandMethodImplementations)(this.startSnap.bind(this), async (target, handlerName, args) => {
56
+ const data = this.snapData.get(target);
57
+ // We're capturing the handler in case someone modifies the data object before the call
58
+ const handler = handlerName === snaps_utils_1.HandlerType.SnapKeyring
59
+ ? (0, keyring_1.wrapKeyring)(this.notify.bind(this), data === null || data === void 0 ? void 0 : data.exports.keyring)
60
+ : data === null || data === void 0 ? void 0 : data.exports[handlerName];
61
+ (0, utils_1.assert)(handler !== undefined, `No ${handlerName} handler exported for snap "${target}`);
62
+ // TODO: fix handler args type cast
63
+ let result = await this.executeInSnapContext(target, () => handler(args));
64
+ // The handler might not return anything, but undefined is not valid JSON.
65
+ if (result === undefined) {
66
+ result = null;
67
+ }
68
+ (0, utils_1.assert)((0, utils_1.isValidJson)(result), new TypeError('Received non-JSON-serializable value.'));
69
+ return result;
70
+ }, this.onTerminate.bind(this));
71
+ }
72
+ errorHandler(error, data) {
73
+ var _a;
74
+ const constructedError = (0, utils_2.constructError)(error);
75
+ const serializedError = (0, eth_rpc_errors_1.serializeError)(constructedError, {
76
+ fallbackError,
77
+ shouldIncludeStack: false,
78
+ });
79
+ // We're setting it this way to avoid sentData.stack = undefined
80
+ const sentData = Object.assign(Object.assign({}, data), { stack: (_a = constructedError === null || constructedError === void 0 ? void 0 : constructedError.stack) !== null && _a !== void 0 ? _a : null });
81
+ this.notify({
82
+ method: 'UnhandledError',
83
+ params: {
84
+ error: Object.assign(Object.assign({}, serializedError), { data: sentData }),
85
+ },
86
+ });
87
+ }
88
+ async onCommandRequest(message) {
89
+ if (!(0, utils_1.isJsonRpcRequest)(message)) {
90
+ throw new Error('Command stream received a non-JSON-RPC request.');
91
+ }
92
+ const { id, method, params } = message;
93
+ if (method === 'rpc.discover') {
94
+ this.respond(id, {
95
+ result: openrpc_json_1.default,
96
+ });
97
+ return;
98
+ }
99
+ if (!(0, utils_1.hasProperty)(EXECUTION_ENVIRONMENT_METHODS, method)) {
100
+ this.respond(id, {
101
+ error: eth_rpc_errors_1.ethErrors.rpc
102
+ .methodNotFound({
103
+ data: {
104
+ method,
105
+ },
106
+ })
107
+ .serialize(),
108
+ });
109
+ return;
110
+ }
111
+ const methodObject = EXECUTION_ENVIRONMENT_METHODS[method];
112
+ // support params by-name and by-position
113
+ const paramsAsArray = (0, sortParams_1.sortParamKeys)(methodObject.params, params);
114
+ const [error] = (0, superstruct_1.validate)(paramsAsArray, methodObject.struct);
115
+ if (error) {
116
+ this.respond(id, {
117
+ error: eth_rpc_errors_1.ethErrors.rpc
118
+ .invalidParams({
119
+ message: `Invalid parameters for method "${method}": ${error.message}.`,
120
+ data: {
121
+ method,
122
+ params: paramsAsArray,
123
+ },
124
+ })
125
+ .serialize(),
126
+ });
127
+ return;
128
+ }
129
+ try {
130
+ const result = await this.methods[method](...paramsAsArray);
131
+ this.respond(id, { result });
132
+ }
133
+ catch (e) {
134
+ this.respond(id, {
135
+ error: (0, eth_rpc_errors_1.serializeError)(e, {
136
+ fallbackError,
137
+ }),
138
+ });
139
+ }
140
+ }
141
+ notify(requestObject) {
142
+ if (!(0, utils_1.isValidJson)(requestObject) || !(0, utils_1.isObject)(requestObject)) {
143
+ throw new Error('JSON-RPC notifications must be JSON serializable objects');
144
+ }
145
+ this.commandStream.write(Object.assign(Object.assign({}, requestObject), { jsonrpc: '2.0' }));
146
+ }
147
+ respond(id, requestObject) {
148
+ if (!(0, utils_1.isValidJson)(requestObject) || !(0, utils_1.isObject)(requestObject)) {
149
+ throw new Error('JSON-RPC responses must be JSON serializable objects.');
150
+ }
151
+ this.commandStream.write(Object.assign(Object.assign({}, requestObject), { id, jsonrpc: '2.0' }));
152
+ }
153
+ /**
154
+ * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw
155
+ * on errors.
156
+ *
157
+ * @param snapName - The name of the snap.
158
+ * @param sourceCode - The source code of the snap, in IIFE format.
159
+ * @param _endowments - An array of the names of the endowments.
160
+ */
161
+ async startSnap(snapName, sourceCode, _endowments) {
162
+ console.log(`starting snap '${snapName}' in worker`);
163
+ if (this.snapPromiseErrorHandler) {
164
+ (0, globalEvents_1.removeEventListener)('unhandledrejection', this.snapPromiseErrorHandler);
165
+ }
166
+ if (this.snapErrorHandler) {
167
+ (0, globalEvents_1.removeEventListener)('error', this.snapErrorHandler);
168
+ }
169
+ this.snapErrorHandler = (error) => {
170
+ this.errorHandler(error.error, { snapName });
171
+ };
172
+ this.snapPromiseErrorHandler = (error) => {
173
+ this.errorHandler(error instanceof Error ? error : error.reason, {
174
+ snapName,
175
+ });
176
+ };
177
+ const provider = new providers_1.StreamProvider(this.rpcStream, {
178
+ jsonRpcStreamName: 'metamask-provider',
179
+ rpcMiddleware: [(0, json_rpc_engine_1.createIdRemapMiddleware)()],
180
+ });
181
+ await provider.initialize();
182
+ const snap = this.createSnapGlobal(provider);
183
+ const ethereum = this.createEIP1193Provider(provider);
184
+ // We specifically use any type because the Snap can modify the object any way they want
185
+ const snapModule = { exports: {} };
186
+ try {
187
+ const { endowments, teardown: endowmentTeardown } = (0, endowments_1.createEndowments)(snap, ethereum, _endowments);
188
+ // !!! Ensure that this is the only place the data is being set.
189
+ // Other methods access the object value and mutate its properties.
190
+ this.snapData.set(snapName, {
191
+ idleTeardown: endowmentTeardown,
192
+ runningEvaluations: new Set(),
193
+ exports: {},
194
+ });
195
+ (0, globalEvents_1.addEventListener)('unhandledRejection', this.snapPromiseErrorHandler);
196
+ (0, globalEvents_1.addEventListener)('error', this.snapErrorHandler);
197
+ const compartment = new Compartment(Object.assign(Object.assign({}, endowments), { module: snapModule, exports: snapModule.exports, window: Object.assign({}, endowments), self: Object.assign({}, endowments) }));
198
+ await this.executeInSnapContext(snapName, () => {
199
+ compartment.evaluate(sourceCode);
200
+ this.registerSnapExports(snapName, snapModule);
201
+ });
202
+ }
203
+ catch (err) {
204
+ this.removeSnap(snapName);
205
+ throw new Error(`Error while running snap '${snapName}': ${err.message}`);
206
+ }
207
+ }
208
+ /**
209
+ * Cancels all running evaluations of all snaps and clears all snap data.
210
+ * NOTE:** Should only be called in response to the `terminate` RPC command.
211
+ */
212
+ onTerminate() {
213
+ // `stop()` tears down snap endowments.
214
+ // Teardown will also be run for each snap as soon as there are
215
+ // no more running evaluations for that snap.
216
+ this.snapData.forEach((data) => data.runningEvaluations.forEach((evaluation) => evaluation.stop()));
217
+ this.snapData.clear();
218
+ }
219
+ registerSnapExports(snapName, snapModule) {
220
+ const data = this.snapData.get(snapName);
221
+ // Somebody deleted the Snap before we could register
222
+ if (!data) {
223
+ return;
224
+ }
225
+ data.exports = snaps_utils_1.SNAP_EXPORT_NAMES.reduce((acc, exportName) => {
226
+ const snapExport = snapModule.exports[exportName];
227
+ if ((0, validation_1.validateExport)(exportName, snapExport)) {
228
+ return Object.assign(Object.assign({}, acc), { [exportName]: snapExport });
229
+ }
230
+ return acc;
231
+ }, {});
232
+ }
233
+ /**
234
+ * Instantiates a snap API object (i.e. `globalThis.snap`).
235
+ *
236
+ * @param provider - A StreamProvider connected to MetaMask.
237
+ * @returns The snap provider object.
238
+ */
239
+ createSnapGlobal(provider) {
240
+ const originalRequest = provider.request;
241
+ const request = async (args) => {
242
+ (0, utils_1.assert)(args.method.startsWith('wallet_') || args.method.startsWith('snap_'), 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.');
243
+ this.notify({ method: 'OutboundRequest' });
244
+ try {
245
+ return await (0, utils_2.withTeardown)(originalRequest(args), this);
246
+ }
247
+ finally {
248
+ this.notify({ method: 'OutboundResponse' });
249
+ }
250
+ };
251
+ return { request };
252
+ }
253
+ /**
254
+ * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).
255
+ *
256
+ * @param provider - A StreamProvider connected to MetaMask.
257
+ * @returns The EIP-1193 Ethereum provider object.
258
+ */
259
+ createEIP1193Provider(provider) {
260
+ const originalRequest = provider.request;
261
+ provider.request = async (args) => {
262
+ (0, utils_1.assert)(!args.method.startsWith('snap_'), eth_rpc_errors_1.ethErrors.rpc.methodNotFound({
263
+ data: {
264
+ method: args.method,
265
+ },
266
+ }));
267
+ this.notify({ method: 'OutboundRequest' });
268
+ try {
269
+ return await (0, utils_2.withTeardown)(originalRequest(args), this);
270
+ }
271
+ finally {
272
+ this.notify({ method: 'OutboundResponse' });
273
+ }
274
+ };
275
+ return provider;
276
+ }
277
+ /**
278
+ * Removes the snap with the given name.
279
+ *
280
+ * @param snapName - The name of the snap to remove.
281
+ */
282
+ removeSnap(snapName) {
283
+ this.snapData.delete(snapName);
284
+ }
285
+ /**
286
+ * Calls the specified executor function in the context of the specified snap.
287
+ * Essentially, this means that the operation performed by the executor is
288
+ * counted as an evaluation of the specified snap. When the count of running
289
+ * evaluations of a snap reaches zero, its endowments are torn down.
290
+ *
291
+ * @param snapName - The name of the snap whose context to execute in.
292
+ * @param executor - The function that will be executed in the snap's context.
293
+ * @returns The executor's return value.
294
+ * @template Result - The return value of the executor.
295
+ */
296
+ async executeInSnapContext(snapName, executor) {
297
+ const data = this.snapData.get(snapName);
298
+ if (data === undefined) {
299
+ throw new Error(`Tried to execute in context of unknown snap: "${snapName}".`);
300
+ }
301
+ let stop;
302
+ const stopPromise = new Promise((_, reject) => (stop = () => reject(
303
+ // TODO(rekmarks): Specify / standardize error code for this case.
304
+ eth_rpc_errors_1.ethErrors.rpc.internal(`The snap "${snapName}" has been terminated during execution.`))));
305
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
306
+ const evaluationData = { stop: stop };
307
+ try {
308
+ data.runningEvaluations.add(evaluationData);
309
+ // Notice that we have to await this executor.
310
+ // If we didn't, we would decrease the amount of running evaluations
311
+ // before the promise actually resolves
312
+ return await Promise.race([executor(), stopPromise]);
313
+ }
314
+ finally {
315
+ data.runningEvaluations.delete(evaluationData);
316
+ if (data.runningEvaluations.size === 0) {
317
+ this.lastTeardown += 1;
318
+ await data.idleTeardown();
319
+ }
320
+ }
321
+ }
322
+ }
323
+ exports.BaseSnapExecutor = BaseSnapExecutor;
324
+ //# sourceMappingURL=BaseSnapExecutor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseSnapExecutor.js","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAGA,mDAAqD;AACrD,qDAA0D;AAE1D,mDAAuE;AACvE,2CAWyB;AACzB,uDAI+B;AAE/B,6CAAuC;AAEvC,mEAAgD;AAChD,yCAGoB;AACpB,6CAAgD;AAChD,iDAAuE;AACvE,uCAAwC;AACxC,6CAA6C;AAC7C,mCAAuD;AACvD,6CAMsB;AAYtB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,2BAAU,CAAC,GAAG,CAAC,QAAQ;IAC7B,OAAO,EAAE,6BAA6B;CACvC,CAAC;AAYF;;;;GAIG;AACH,MAAM,6BAA6B,GAAG;IACpC,IAAI,EAAE;QACJ,MAAM,EA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YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE;gBACtC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC;gBACvB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;aAC3B;SACF;IACH,CAAC;CACF;AA1YD,4CA0YC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/index.d.ts\" />\nimport { Duplex } from 'stream';\nimport { StreamProvider } from '@metamask/providers';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport { SnapExports, SnapsGlobalObject } from '@metamask/snaps-types';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport {\n isObject,\n isValidJson,\n JsonRpcNotification,\n assert,\n isJsonRpcRequest,\n JsonRpcId,\n JsonRpcRequest,\n JsonRpcParams,\n Json,\n hasProperty,\n} from '@metamask/utils';\nimport {\n HandlerType,\n SnapExportsParameters,\n SNAP_EXPORT_NAMES,\n} from '@metamask/snaps-utils';\n\nimport { validate } from 'superstruct';\nimport { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport EEOpenRPCDocument from '../openrpc.json';\nimport {\n CommandMethodsMapping,\n getCommandMethodImplementations,\n} from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { wrapKeyring } from './keyring';\nimport { sortParamKeys } from './sortParams';\nimport { constructError, withTeardown } from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n validateExport,\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\n// TODO: `KeyringParameters` expects a `chainId` for certain methods, but we're\n// not providing it in `getHandlerArguments`, resulting in type errors.\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: ['snapName', '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\nexport class BaseSnapExecutor {\n private snapData: Map<string, SnapData>;\n\n private commandStream: Duplex;\n\n private rpcStream: Duplex;\n\n private 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', this.onCommandRequest.bind(this));\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerName, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object before the call\n const handler =\n handlerName === HandlerType.SnapKeyring\n ? wrapKeyring(this.notify.bind(this), data?.exports.keyring)\n : data?.exports[handlerName];\n assert(\n handler !== undefined,\n `No ${handlerName} handler exported for snap \"${target}`,\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 assert(\n isValidJson(result),\n new TypeError('Received non-JSON-serializable value.'),\n );\n return result;\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<JsonRpcParams>) {\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 if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\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 =\n EXECUTION_ENVIRONMENT_METHODS[\n method as keyof typeof EXECUTION_ENVIRONMENT_METHODS\n ];\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 (e) {\n this.respond(id, {\n error: serializeError(e, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(\n requestObject: Omit<\n JsonRpcNotification<Record<string, Json> | Json[] | undefined>,\n 'jsonrpc'\n >,\n ) {\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 throw new Error('JSON-RPC responses must be JSON serializable objects.');\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 snapName - The name 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 snapName: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n console.log(`starting snap '${snapName}' 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, { snapName });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapName,\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 _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(snapName, {\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 window: { ...endowments },\n self: { ...endowments },\n });\n\n await this.executeInSnapContext(snapName, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapName, snapModule);\n });\n } catch (err) {\n this.removeSnap(snapName);\n throw new Error(\n `Error while running snap '${snapName}': ${(err 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(snapName: string, snapModule: any) {\n const data = this.snapData.get(snapName);\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 if (validateExport(exportName, 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;\n\n const request = async (args: RequestArguments) => {\n assert(\n args.method.startsWith('wallet_') || args.method.startsWith('snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n return { request };\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;\n\n provider.request = async (args) => {\n assert(\n !args.method.startsWith('snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n return provider;\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapName - The name of the snap to remove.\n */\n private removeSnap(snapName: string): void {\n this.snapData.delete(snapName);\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 snapName - The name 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 snapName: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapName);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapName}\".`,\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 \"${snapName}\" 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"]}
@@ -0,0 +1,30 @@
1
+ import { HandlerType } from '@metamask/snaps-utils';
2
+ import { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';
3
+ import { ExecuteSnap, JsonRpcRequestWithoutId, Ping, SnapRpc, Terminate } from './validation';
4
+ export declare type CommandMethodsMapping = {
5
+ ping: Ping;
6
+ terminate: Terminate;
7
+ executeSnap: ExecuteSnap;
8
+ snapRpc: SnapRpc;
9
+ };
10
+ /**
11
+ * Formats the arguments for the given handler.
12
+ *
13
+ * @param origin - The origin of the request.
14
+ * @param handler - The handler to pass the request to.
15
+ * @param request - The request object.
16
+ * @returns The formatted arguments.
17
+ */
18
+ export declare function getHandlerArguments(origin: string, handler: HandlerType, request: JsonRpcRequestWithoutId): InvokeSnapArgs;
19
+ /**
20
+ * Gets an object mapping internal, "command" JSON-RPC method names to their
21
+ * implementations.
22
+ *
23
+ * @param startSnap - A function that starts a snap.
24
+ * @param invokeSnap - A function that invokes the RPC method handler of a
25
+ * snap.
26
+ * @param onTerminate - A function that will be called when this executor is
27
+ * terminated in order to handle cleanup tasks.
28
+ * @returns An object containing the "command" method implementations.
29
+ */
30
+ export declare function getCommandMethodImplementations(startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>, invokeSnap: InvokeSnap, onTerminate: () => void): CommandMethodsMapping;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCommandMethodImplementations = exports.getHandlerArguments = void 0;
4
+ const utils_1 = require("@metamask/utils");
5
+ const snaps_utils_1 = require("@metamask/snaps-utils");
6
+ const validation_1 = require("./validation");
7
+ /**
8
+ * Formats the arguments for the given handler.
9
+ *
10
+ * @param origin - The origin of the request.
11
+ * @param handler - The handler to pass the request to.
12
+ * @param request - The request object.
13
+ * @returns The formatted arguments.
14
+ */
15
+ function getHandlerArguments(origin, handler, request) {
16
+ // `request` is already validated by the time this function is called.
17
+ switch (handler) {
18
+ case snaps_utils_1.HandlerType.OnTransaction: {
19
+ (0, validation_1.assertIsOnTransactionRequestArguments)(request.params);
20
+ const { transaction, chainId, transactionOrigin } = request.params;
21
+ return {
22
+ transaction,
23
+ chainId,
24
+ transactionOrigin,
25
+ };
26
+ }
27
+ case snaps_utils_1.HandlerType.OnRpcRequest:
28
+ case snaps_utils_1.HandlerType.SnapKeyring:
29
+ return { origin, request };
30
+ case snaps_utils_1.HandlerType.OnCronjob:
31
+ return { request };
32
+ default:
33
+ return (0, utils_1.assertExhaustive)(handler);
34
+ }
35
+ }
36
+ exports.getHandlerArguments = getHandlerArguments;
37
+ /**
38
+ * Gets an object mapping internal, "command" JSON-RPC method names to their
39
+ * implementations.
40
+ *
41
+ * @param startSnap - A function that starts a snap.
42
+ * @param invokeSnap - A function that invokes the RPC method handler of a
43
+ * snap.
44
+ * @param onTerminate - A function that will be called when this executor is
45
+ * terminated in order to handle cleanup tasks.
46
+ * @returns An object containing the "command" method implementations.
47
+ */
48
+ function getCommandMethodImplementations(startSnap, invokeSnap, onTerminate) {
49
+ return {
50
+ ping: async () => {
51
+ return 'OK';
52
+ },
53
+ terminate: async () => {
54
+ onTerminate();
55
+ return 'OK';
56
+ },
57
+ executeSnap: async (snapName, sourceCode, endowments) => {
58
+ await startSnap(snapName, sourceCode, endowments);
59
+ return 'OK';
60
+ },
61
+ snapRpc: async (target, handler, origin, request) => {
62
+ var _a;
63
+ return ((_a = (await invokeSnap(target, handler, getHandlerArguments(origin, handler, request)))) !== null && _a !== void 0 ? _a : null);
64
+ },
65
+ };
66
+ }
67
+ exports.getCommandMethodImplementations = getCommandMethodImplementations;
68
+ //# sourceMappingURL=commands.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commands.js","sourceRoot":"","sources":["../../src/common/commands.ts"],"names":[],"mappings":";;;AAAA,2CAAmD;AACnD,uDAAoD;AAEpD,6CAOsB;AAStB;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CACjC,MAAc,EACd,OAAoB,EACpB,OAAgC;IAEhC,sEAAsE;IAEtE,QAAQ,OAAO,EAAE;QACf,KAAK,yBAAW,CAAC,aAAa,CAAC,CAAC;YAC9B,IAAA,kDAAqC,EAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAEtD,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,iBAAiB,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;YACnE,OAAO;gBACL,WAAW;gBACX,OAAO;gBACP,iBAAiB;aAClB,CAAC;SACH;QAED,KAAK,yBAAW,CAAC,YAAY,CAAC;QAC9B,KAAK,yBAAW,CAAC,WAAW;YAC1B,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QAE7B,KAAK,yBAAW,CAAC,SAAS;YACxB,OAAO,EAAE,OAAO,EAAE,CAAC;QAErB;YACE,OAAO,IAAA,wBAAgB,EAAC,OAAO,CAAC,CAAC;KACpC;AACH,CAAC;AA7BD,kDA6BC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,+BAA+B,CAC7C,SAA8D,EAC9D,UAAsB,EACtB,WAAuB;IAEvB,OAAO;QACL,IAAI,EAAE,KAAK,IAAI,EAAE;YACf,OAAO,IAAI,CAAC;QACd,CAAC;QAED,SAAS,EAAE,KAAK,IAAI,EAAE;YACpB,WAAW,EAAE,CAAC;YACd,OAAO,IAAI,CAAC;QACd,CAAC;QAED,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE;YACtD,MAAM,SAAS,CAAC,QAAkB,EAAE,UAAoB,EAAE,UAAU,CAAC,CAAC;YACtE,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE;;YAClD,OAAO,CACL,MAAA,CAAC,MAAM,UAAU,CACf,MAAM,EACN,OAAO,EACP,mBAAmB,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAC9C,CAAC,mCAAI,IAAI,CACX,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AA9BD,0EA8BC","sourcesContent":["import { assertExhaustive } from '@metamask/utils';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport {\n assertIsOnTransactionRequestArguments,\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n SnapRpc,\n Terminate,\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\n case HandlerType.OnRpcRequest:\n case HandlerType.SnapKeyring:\n return { origin, request };\n\n case HandlerType.OnCronjob:\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 () => {\n return 'OK';\n },\n\n terminate: async () => {\n onTerminate();\n return 'OK';\n },\n\n executeSnap: async (snapName, sourceCode, endowments) => {\n await startSnap(snapName as string, sourceCode as string, 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"]}
@@ -0,0 +1,8 @@
1
+ declare const endowmentModule: {
2
+ names: readonly ["crypto", "SubtleCrypto"];
3
+ factory: () => {
4
+ readonly crypto: any;
5
+ readonly SubtleCrypto: any;
6
+ };
7
+ };
8
+ export default endowmentModule;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const globalObject_1 = require("../globalObject");
4
+ const createCrypto = () => {
5
+ if ('crypto' in globalObject_1.rootRealmGlobal &&
6
+ typeof globalObject_1.rootRealmGlobal.crypto === 'object' &&
7
+ 'SubtleCrypto' in globalObject_1.rootRealmGlobal &&
8
+ typeof globalObject_1.rootRealmGlobal.SubtleCrypto === 'function') {
9
+ return {
10
+ crypto: globalObject_1.rootRealmGlobal.crypto,
11
+ SubtleCrypto: globalObject_1.rootRealmGlobal.SubtleCrypto,
12
+ };
13
+ }
14
+ // For now, we expose the experimental webcrypto API for Node.js execution environments
15
+ // TODO: Figure out if this is enough long-term or if we should use a polyfill.
16
+ /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */
17
+ const crypto = require('crypto').webcrypto;
18
+ return { crypto, SubtleCrypto: crypto.subtle.constructor };
19
+ };
20
+ const endowmentModule = {
21
+ names: ['crypto', 'SubtleCrypto'],
22
+ factory: createCrypto,
23
+ };
24
+ exports.default = endowmentModule;
25
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../../src/common/endowments/crypto.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD,MAAM,YAAY,GAAG,GAAG,EAAE;IACxB,IACE,QAAQ,IAAI,8BAAe;QAC3B,OAAO,8BAAe,CAAC,MAAM,KAAK,QAAQ;QAC1C,cAAc,IAAI,8BAAe;QACjC,OAAO,8BAAe,CAAC,YAAY,KAAK,UAAU,EAClD;QACA,OAAO;YACL,MAAM,EAAE,8BAAe,CAAC,MAAM;YAC9B,YAAY,EAAE,8BAAe,CAAC,YAAY;SAC3C,CAAC;KACH;IACD,uFAAuF;IACvF,+EAA+E;IAC/E,6HAA6H;IAC7H,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC;IAC3C,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,WAAW,EAAW,CAAC;AACtE,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,QAAQ,EAAE,cAAc,CAAU;IAC1C,OAAO,EAAE,YAAY;CACtB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\nconst createCrypto = () => {\n if (\n 'crypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.crypto === 'object' &&\n 'SubtleCrypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.SubtleCrypto === 'function'\n ) {\n return {\n crypto: rootRealmGlobal.crypto,\n SubtleCrypto: rootRealmGlobal.SubtleCrypto,\n };\n }\n // For now, we expose the experimental webcrypto API for Node.js execution environments\n // TODO: Figure out if this is enough long-term or if we should use a polyfill.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */\n const crypto = require('crypto').webcrypto;\n return { crypto, SubtleCrypto: crypto.subtle.constructor } as const;\n};\n\nconst endowmentModule = {\n names: ['crypto', 'SubtleCrypto'] as const,\n factory: createCrypto,\n};\nexport default endowmentModule;\n"]}
@@ -0,0 +1,25 @@
1
+ import { SnapsGlobalObject } from '@metamask/snaps-types';
2
+ import { StreamProvider } from '@metamask/providers';
3
+ /**
4
+ * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`
5
+ * and `clearTimeout`, must be attenuated so that they can only affect behavior
6
+ * within the Snap's own realm. Therefore, we use factory functions to create
7
+ * such attenuated / modified endowments. Otherwise, the value that's on the
8
+ * root realm global will be used.
9
+ *
10
+ * @param snap - The Snaps global API object.
11
+ * @param ethereum - The Snap's EIP-1193 provider object.
12
+ * @param endowments - The list of endowments to provide to the snap.
13
+ * @returns An object containing the Snap's endowments.
14
+ */
15
+ export declare function createEndowments(snap: SnapsGlobalObject, ethereum: StreamProvider, endowments?: string[]): {
16
+ endowments: Record<string, unknown>;
17
+ teardown: () => Promise<void>;
18
+ };
19
+ /**
20
+ * Checks whether the specified function is a constructor.
21
+ *
22
+ * @param value - Any function value.
23
+ * @returns Whether the specified function is a constructor.
24
+ */
25
+ export declare function isConstructor<T extends Function>(value: T): boolean;