@metamask/snaps-execution-environments 2.0.1 → 3.1.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.
- package/CHANGELOG.md +16 -1
- package/dist/browserify/iframe/bundle.js +5 -5
- package/dist/browserify/node-process/bundle.js +4 -4
- package/dist/browserify/node-thread/bundle.js +4 -4
- package/dist/browserify/offscreen/bundle.js +4 -4
- package/dist/browserify/worker-executor/bundle.js +5 -5
- package/dist/browserify/worker-pool/bundle.js +4 -4
- package/dist/cjs/common/BaseSnapExecutor.js +37 -27
- package/dist/cjs/common/BaseSnapExecutor.js.map +1 -1
- package/dist/cjs/common/commands.js +1 -0
- package/dist/cjs/common/commands.js.map +1 -1
- package/dist/cjs/common/endowments/console.js.map +1 -1
- package/dist/cjs/common/endowments/index.js +2 -1
- package/dist/cjs/common/endowments/index.js.map +1 -1
- package/dist/cjs/common/endowments/interval.js +2 -1
- package/dist/cjs/common/endowments/interval.js.map +1 -1
- package/dist/cjs/common/endowments/timeout.js +2 -1
- package/dist/cjs/common/endowments/timeout.js.map +1 -1
- package/dist/cjs/common/globalEvents.js +2 -1
- package/dist/cjs/common/globalEvents.js.map +1 -1
- package/dist/cjs/common/globalObject.js.map +1 -1
- package/dist/cjs/common/utils.js +7 -21
- package/dist/cjs/common/utils.js.map +1 -1
- package/dist/cjs/common/validation.js +3 -2
- package/dist/cjs/common/validation.js.map +1 -1
- package/dist/esm/common/BaseSnapExecutor.js +37 -27
- package/dist/esm/common/BaseSnapExecutor.js.map +1 -1
- package/dist/esm/common/commands.js +1 -0
- package/dist/esm/common/commands.js.map +1 -1
- package/dist/esm/common/endowments/console.js.map +1 -1
- package/dist/esm/common/endowments/index.js +2 -1
- package/dist/esm/common/endowments/index.js.map +1 -1
- package/dist/esm/common/endowments/interval.js +2 -1
- package/dist/esm/common/endowments/interval.js.map +1 -1
- package/dist/esm/common/endowments/timeout.js +2 -1
- package/dist/esm/common/endowments/timeout.js.map +1 -1
- package/dist/esm/common/globalEvents.js +2 -1
- package/dist/esm/common/globalEvents.js.map +1 -1
- package/dist/esm/common/globalObject.js.map +1 -1
- package/dist/esm/common/utils.js +7 -25
- package/dist/esm/common/utils.js.map +1 -1
- package/dist/esm/common/validation.js +3 -2
- package/dist/esm/common/validation.js.map +1 -1
- package/dist/types/common/endowments/index.d.ts +1 -1
- package/dist/types/common/utils.d.ts +0 -9
- package/package.json +21 -23
|
@@ -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");
|
|
@@ -37,9 +37,12 @@ function _define_property(obj, key, value) {
|
|
|
37
37
|
return obj;
|
|
38
38
|
}
|
|
39
39
|
const fallbackError = {
|
|
40
|
-
code:
|
|
40
|
+
code: _rpcerrors.errorCodes.rpc.internal,
|
|
41
41
|
message: 'Execution Environment Error'
|
|
42
42
|
};
|
|
43
|
+
const unhandledError = _rpcerrors.rpcErrors.internal({
|
|
44
|
+
message: 'Unhandled Snap Error'
|
|
45
|
+
}).serialize();
|
|
43
46
|
/**
|
|
44
47
|
* The supported methods in the execution environment. The validator checks the
|
|
45
48
|
* incoming JSON-RPC request, and the `params` property is used for sorting the
|
|
@@ -73,34 +76,35 @@ const fallbackError = {
|
|
|
73
76
|
};
|
|
74
77
|
class BaseSnapExecutor {
|
|
75
78
|
errorHandler(error, data) {
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
fallbackError,
|
|
79
|
+
const serializedError = (0, _rpcerrors.serializeError)(error, {
|
|
80
|
+
fallbackError: unhandledError,
|
|
79
81
|
shouldIncludeStack: false
|
|
80
82
|
});
|
|
81
|
-
|
|
82
|
-
const sentData = {
|
|
83
|
-
...data,
|
|
84
|
-
stack: constructedError?.stack ?? null
|
|
85
|
-
};
|
|
83
|
+
const errorData = (0, _snapsutils.getErrorData)(serializedError);
|
|
86
84
|
this.notify({
|
|
87
85
|
method: 'UnhandledError',
|
|
88
86
|
params: {
|
|
89
87
|
error: {
|
|
90
88
|
...serializedError,
|
|
91
|
-
data:
|
|
89
|
+
data: {
|
|
90
|
+
...errorData,
|
|
91
|
+
...data
|
|
92
|
+
}
|
|
92
93
|
}
|
|
93
94
|
}
|
|
94
95
|
});
|
|
95
96
|
}
|
|
96
97
|
async onCommandRequest(message) {
|
|
97
98
|
if (!(0, _utils.isJsonRpcRequest)(message)) {
|
|
98
|
-
throw
|
|
99
|
+
throw _rpcerrors.rpcErrors.invalidRequest({
|
|
100
|
+
message: 'Command stream received a non-JSON-RPC request.',
|
|
101
|
+
data: message
|
|
102
|
+
});
|
|
99
103
|
}
|
|
100
104
|
const { id, method, params } = message;
|
|
101
105
|
if (!(0, _utils.hasProperty)(EXECUTION_ENVIRONMENT_METHODS, method)) {
|
|
102
106
|
this.respond(id, {
|
|
103
|
-
error:
|
|
107
|
+
error: _rpcerrors.rpcErrors.methodNotFound({
|
|
104
108
|
data: {
|
|
105
109
|
method
|
|
106
110
|
}
|
|
@@ -114,7 +118,7 @@ class BaseSnapExecutor {
|
|
|
114
118
|
const [error] = (0, _superstruct.validate)(paramsAsArray, methodObject.struct);
|
|
115
119
|
if (error) {
|
|
116
120
|
this.respond(id, {
|
|
117
|
-
error:
|
|
121
|
+
error: _rpcerrors.rpcErrors.invalidParams({
|
|
118
122
|
message: `Invalid parameters for method "${method}": ${error.message}.`,
|
|
119
123
|
data: {
|
|
120
124
|
method,
|
|
@@ -131,7 +135,7 @@ class BaseSnapExecutor {
|
|
|
131
135
|
});
|
|
132
136
|
} catch (rpcError) {
|
|
133
137
|
this.respond(id, {
|
|
134
|
-
error: (0,
|
|
138
|
+
error: (0, _rpcerrors.serializeError)(rpcError, {
|
|
135
139
|
fallbackError
|
|
136
140
|
})
|
|
137
141
|
});
|
|
@@ -139,7 +143,7 @@ class BaseSnapExecutor {
|
|
|
139
143
|
}
|
|
140
144
|
notify(requestObject) {
|
|
141
145
|
if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
|
|
142
|
-
throw
|
|
146
|
+
throw _rpcerrors.rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects');
|
|
143
147
|
}
|
|
144
148
|
this.commandStream.write({
|
|
145
149
|
...requestObject,
|
|
@@ -151,9 +155,7 @@ class BaseSnapExecutor {
|
|
|
151
155
|
// Instead of throwing, we directly respond with an error.
|
|
152
156
|
// This prevents an issue where we wouldn't respond when errors were non-serializable
|
|
153
157
|
this.commandStream.write({
|
|
154
|
-
error: (0,
|
|
155
|
-
fallbackError
|
|
156
|
-
}),
|
|
158
|
+
error: (0, _rpcerrors.serializeError)(_rpcerrors.rpcErrors.internal('JSON-RPC responses must be JSON serializable objects.')),
|
|
157
159
|
id,
|
|
158
160
|
jsonrpc: '2.0'
|
|
159
161
|
});
|
|
@@ -233,7 +235,13 @@ class BaseSnapExecutor {
|
|
|
233
235
|
});
|
|
234
236
|
} catch (error) {
|
|
235
237
|
this.removeSnap(snapId);
|
|
236
|
-
|
|
238
|
+
const [cause] = (0, _snapsutils.unwrapError)(error);
|
|
239
|
+
throw _rpcerrors.rpcErrors.internal({
|
|
240
|
+
message: `Error while running snap '${snapId}': ${cause.message}`,
|
|
241
|
+
data: {
|
|
242
|
+
cause: cause.serialize()
|
|
243
|
+
}
|
|
244
|
+
});
|
|
237
245
|
}
|
|
238
246
|
}
|
|
239
247
|
/**
|
|
@@ -346,11 +354,11 @@ class BaseSnapExecutor {
|
|
|
346
354
|
*/ async executeInSnapContext(snapId, executor) {
|
|
347
355
|
const data = this.snapData.get(snapId);
|
|
348
356
|
if (data === undefined) {
|
|
349
|
-
throw
|
|
357
|
+
throw _rpcerrors.rpcErrors.internal(`Tried to execute in context of unknown snap: "${snapId}".`);
|
|
350
358
|
}
|
|
351
359
|
let stop;
|
|
352
360
|
const stopPromise = new Promise((_, reject)=>stop = ()=>reject(// TODO(rekmarks): Specify / standardize error code for this case.
|
|
353
|
-
|
|
361
|
+
_rpcerrors.rpcErrors.internal(`The snap "${snapId}" has been terminated during execution.`)));
|
|
354
362
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
355
363
|
const evaluationData = {
|
|
356
364
|
stop: stop
|
|
@@ -364,6 +372,8 @@ class BaseSnapExecutor {
|
|
|
364
372
|
executor(),
|
|
365
373
|
stopPromise
|
|
366
374
|
]);
|
|
375
|
+
} catch (error) {
|
|
376
|
+
throw new _snapsutils.WrappedSnapError(error);
|
|
367
377
|
} finally{
|
|
368
378
|
data.runningEvaluations.delete(evaluationData);
|
|
369
379
|
if (data.runningEvaluations.size === 0) {
|
|
@@ -395,14 +405,14 @@ class BaseSnapExecutor {
|
|
|
395
405
|
// before the call.
|
|
396
406
|
const handler = data?.exports[handlerType];
|
|
397
407
|
const { required } = _snapsutils.SNAP_EXPORTS[handlerType];
|
|
398
|
-
(0, _utils.assert)(!required || handler !== undefined, `No ${handlerType} handler exported for snap "${target}
|
|
408
|
+
(0, _utils.assert)(!required || handler !== undefined, `No ${handlerType} handler exported for snap "${target}`, _rpcerrors.rpcErrors.methodNotSupported);
|
|
399
409
|
// Certain handlers are not required. If they are not exported, we
|
|
400
410
|
// return null.
|
|
401
411
|
if (!handler) {
|
|
402
412
|
return null;
|
|
403
413
|
}
|
|
404
|
-
|
|
405
|
-
|
|
414
|
+
let result = await this.executeInSnapContext(target, ()=>// TODO: fix handler args type cast
|
|
415
|
+
handler(args));
|
|
406
416
|
// The handler might not return anything, but undefined is not valid JSON.
|
|
407
417
|
if (result === undefined) {
|
|
408
418
|
result = null;
|
|
@@ -411,7 +421,7 @@ class BaseSnapExecutor {
|
|
|
411
421
|
try {
|
|
412
422
|
return (0, _utils.getSafeJson)(result);
|
|
413
423
|
} catch (error) {
|
|
414
|
-
throw
|
|
424
|
+
throw _rpcerrors.rpcErrors.internal(`Received non-JSON-serializable value: ${error.message.replace(/^Assertion failed: /u, '')}`);
|
|
415
425
|
}
|
|
416
426
|
}, this.onTerminate.bind(this));
|
|
417
427
|
}
|
|
@@ -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,QAAQM,2CAA+B;QACvCJ,QAAQ,EAAE;IACZ;IACAK,SAAS;QACPP,QAAQQ,yCAA6B;QACrCN,QAAQ;YAAC;YAAU;YAAW;YAAU;SAAU;IACpD;AACF;AAIO,MAAMX;IAwEHkB,aAAaC,KAAc,EAAEC,IAA0B,EAAE;QAC/D,MAAMC,mBAAmBC,IAAAA,sBAAc,EA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,oBAAQ,EAAC3H;YACX;QACF;QACA,IAAI,CAAC6C,SAAS,GAAGA;QAEjB,IAAI,CAACnB,OAAO,GAAGkG,IAAAA,yCAA+B,EAC5C,IAAI,CAAC1F,SAAS,CAAC0D,IAAI,CAAC,IAAI,GACxB,OAAOiC,QAAQC,aAAajC;YAC1B,MAAM5F,OAAO,IAAI,CAAC2D,QAAQ,CAACsB,GAAG,CAAC2C;YAC/B,uEAAuE;YACvE,mBAAmB;YACnB,MAAME,UAAU9H,MAAMsD,OAAO,CAACuE,YAAY;YAC1C,MAAM,EAAEE,QAAQ,EAAE,GAAGvC,wBAAY,CAACqC,YAAY;YAE9CG,IAAAA,aAAM,EACJ,CAACD,YAAYD,YAAYvB,WACzB,CAAC,GAAG,EAAEsB,YAAY,4BAA4B,EAAED,OAAO,CAAC;YAG1D,kEAAkE;YAClE,eAAe;YACf,IAAI,CAACE,SAAS;gBACZ,OAAO;YACT;YAEA,mCAAmC;YACnC,IAAItG,SAAS,MAAM,IAAI,CAACgD,oBAAoB,CAACoD,QAAQ,IACnDE,QAAQlC;YAGV,0EAA0E;YAC1E,IAAIpE,WAAW+E,WAAW;gBACxB/E,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOyG,IAAAA,kBAAW,EAACzG;YACrB,EAAE,OAAOzB,OAAO;gBACd,MAAM,IAAImI,UACR,CAAC,sCAAsC,EAAEnI,MAAMb,OAAO,CAACiJ,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAACvD,WAAW,CAACe,IAAI,CAAC,IAAI;IAE9B;AAwWF"}
|
|
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 { 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 });\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 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 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 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 rpcErrors.internal(\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 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 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\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 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 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","onCommandRequest","isJsonRpcRequest","invalidRequest","id","hasProperty","respond","methodNotFound","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","result","methods","rpcError","requestObject","isValidJson","isObject","commandStream","write","jsonrpc","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","Map","on","catch","logError","getCommandMethodImplementations","target","handlerType","handler","required","assert","methodNotSupported","getSafeJson","replace"],"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;IACAG,WAAW;QACTL,QAAQM,2CAA+B;QACvCJ,QAAQ,EAAE;IACZ;IACAK,SAAS;QACPP,QAAQQ,yCAA6B;QACrCN,QAAQ;YAAC;YAAU;YAAW;YAAU;SAAU;IACpD;AACF;AAIO,MAAMd;IAyEHqB,aAAaC,KAAc,EAAEC,IAA0B,EAAE;QAC/D,MAAMC,kBAAkBC,IAAAA,yBAAc,EAACH,OAAO;YAC5CrB,eAAeM;YACfmB,oBAAoB;QACtB;QAEA,MAAMC,YAAYC,IAAAA,wBAAY,EAACJ;QAE/B,IAAI,CAACK,MAAM,CAAC;YACVC,QAAQ;YACRhB,QAAQ;gBACNQ,OAAO;oBACL,GAAGE,eAAe;oBAClBD,MAAM;wBACJ,GAAGI,SAAS;wBACZ,GAAGJ,IAAI;oBACT;gBACF;YACF;QACF;IACF;IAEA,MAAcQ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I,CAACpB,OAAO,GAAGsG,IAAAA,yCAA+B,EAC5C,IAAI,CAAC9F,SAAS,CAAC6D,IAAI,CAAC,IAAI,GACxB,OAAOkC,QAAQC,aAAalC;YAC1B,MAAM3F,OAAO,IAAI,CAACwD,QAAQ,CAACwB,GAAG,CAAC4C;YAC/B,uEAAuE;YACvE,mBAAmB;YACnB,MAAME,UAAU9H,MAAMmD,OAAO,CAAC0E,YAAY;YAC1C,MAAM,EAAEE,QAAQ,EAAE,GAAGxC,wBAAY,CAACsC,YAAY;YAE9CG,IAAAA,aAAM,EACJ,CAACD,YAAYD,YAAYxB,WACzB,CAAC,GAAG,EAAEuB,YAAY,4BAA4B,EAAED,OAAO,CAAC,EACxD3I,oBAAS,CAACgJ,kBAAkB;YAG9B,kEAAkE;YAClE,eAAe;YACf,IAAI,CAACH,SAAS;gBACZ,OAAO;YACT;YAEA,IAAI1G,SAAS,MAAM,IAAI,CAACiD,oBAAoB,CAACuD,QAAQ,IACnD,mCAAmC;gBACnCE,QAAQnC;YAGV,0EAA0E;YAC1E,IAAIvE,WAAWkF,WAAW;gBACxBlF,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAO8G,IAAAA,kBAAW,EAAC9G;YACrB,EAAE,OAAOrB,OAAO;gBACd,MAAMd,oBAAS,CAACH,QAAQ,CACtB,CAAC,sCAAsC,EAAEiB,MAAMhB,OAAO,CAACoJ,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAACxD,WAAW,CAACe,IAAI,CAAC,IAAI;IAE9B;AAmXF"}
|
|
@@ -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 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","OnCronjob","OnInstall","OnUpdate","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IAgCgBA,mBAAmB;eAAnBA;;
|
|
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;;;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AAQC,SAASC,aACjC;QAEV;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/common/endowments/console.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\nexport const consoleAttenuatedMethods = new Set([\n 'log',\n 'assert',\n 'error',\n 'debug',\n 'info',\n 'warn',\n]);\n\n/**\n * A set of all the `console` values that will be passed to the snap. This has\n * all the values that are available in both the browser and Node.js.\n */\nexport const consoleMethods = new Set([\n 'debug',\n 'error',\n 'info',\n 'log',\n 'warn',\n 'dir',\n 'dirxml',\n 'table',\n 'trace',\n 'group',\n 'groupCollapsed',\n 'groupEnd',\n 'clear',\n 'count',\n 'countReset',\n 'assert',\n 'profile',\n 'profileEnd',\n 'time',\n 'timeLog',\n 'timeEnd',\n 'timeStamp',\n 'context',\n]);\n\nconst consoleFunctions = ['log', 'error', 'debug', 'info', 'warn'] as const;\n\ntype ConsoleFunctions = {\n [Key in typeof consoleFunctions[number]]: typeof rootRealmGlobal.console[Key];\n};\n\n/**\n * Gets the appropriate (prepended) message to pass to one of the attenuated\n * method calls.\n *\n * @param snapId - Id of the snap that we're getting a message for.\n * @param message - The id of the snap that will interact with the endowment.\n * @param args - The array of additional arguments.\n * @returns An array of arguments to be passed into an attenuated console method call.\n */\nfunction getMessage(snapId: SnapId, message: unknown, ...args: unknown[]) {\n const prefix = `[Snap: ${snapId}]`;\n\n // If the first argument is a string, prepend the prefix to the message, and keep the\n // rest of the arguments as-is.\n if (typeof message === 'string') {\n return [`${prefix} ${message}`, ...args];\n }\n\n // Otherwise, the `message` is an object, array, etc., so add the prefix as a separate\n // message to the arguments.\n return [prefix, message, ...args];\n}\n\n/**\n * Create a a {@link console} object, with the same properties as the global\n * {@link console} object, but with some methods replaced.\n *\n * @param options - Factory options used in construction of the endowment.\n * @param options.snapId - The id of the snap that will interact with the endowment.\n * @returns The {@link console} object with the replaced methods.\n */\nfunction createConsole({ snapId }: EndowmentFactoryOptions = {}) {\n assert(snapId !== undefined);\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.console,\n ) as (keyof typeof console)[];\n\n const attenuatedConsole = keys.reduce((target, key) => {\n if (consoleMethods.has(key) && !consoleAttenuatedMethods.has(key)) {\n return { ...target, [key]: rootRealmGlobal.console[key] };\n }\n\n return target;\n }, {});\n\n return harden({\n console: {\n ...attenuatedConsole,\n assert: (\n value: any,\n message?: string | undefined,\n ...optionalParams: any[]\n ) => {\n rootRealmGlobal.console.assert(\n value,\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n ...consoleFunctions.reduce<ConsoleFunctions>((target, key) => {\n return {\n ...target,\n [key]: (message?: unknown, ...optionalParams: any[]) => {\n rootRealmGlobal.console[key](\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n };\n }, {} as ConsoleFunctions),\n },\n });\n}\n\nconst endowmentModule = {\n names: ['console'] as const,\n factory: createConsole,\n};\n\nexport default endowmentModule;\n"],"names":["consoleAttenuatedMethods","consoleMethods","Set","consoleFunctions","getMessage","snapId","message","args","prefix","createConsole","assert","undefined","keys","Object","getOwnPropertyNames","rootRealmGlobal","console","attenuatedConsole","reduce","target","key","has","harden","value","optionalParams","endowmentModule","names","factory"],"mappings":";;;;;;;;;;;IAMaA,wBAAwB;eAAxBA;;IAaAC,cAAc;eAAdA;;IA6Gb,OAA+B;eAA/B;;;uBA/HuB;8BAES;AAGzB,MAAMD,2BAA2B,IAAIE,IAAI;IAC9C;IACA;IACA;IACA;IACA;IACA;CACD;AAMM,MAAMD,iBAAiB,IAAIC,IAAI;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAMC,mBAAmB;IAAC;IAAO;IAAS;IAAS;IAAQ;CAAO;AA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AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAASlB;AACX;MAEA,WAAegB"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/common/endowments/console.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\nexport const consoleAttenuatedMethods = new Set([\n 'log',\n 'assert',\n 'error',\n 'debug',\n 'info',\n 'warn',\n]);\n\n/**\n * A set of all the `console` values that will be passed to the snap. This has\n * all the values that are available in both the browser and Node.js.\n */\nexport const consoleMethods = new Set([\n 'debug',\n 'error',\n 'info',\n 'log',\n 'warn',\n 'dir',\n 'dirxml',\n 'table',\n 'trace',\n 'group',\n 'groupCollapsed',\n 'groupEnd',\n 'clear',\n 'count',\n 'countReset',\n 'assert',\n 'profile',\n 'profileEnd',\n 'time',\n 'timeLog',\n 'timeEnd',\n 'timeStamp',\n 'context',\n]);\n\nconst consoleFunctions = ['log', 'error', 'debug', 'info', 'warn'] as const;\n\ntype ConsoleFunctions = {\n [Key in (typeof consoleFunctions)[number]]: (typeof rootRealmGlobal.console)[Key];\n};\n\n/**\n * Gets the appropriate (prepended) message to pass to one of the attenuated\n * method calls.\n *\n * @param snapId - Id of the snap that we're getting a message for.\n * @param message - The id of the snap that will interact with the endowment.\n * @param args - The array of additional arguments.\n * @returns An array of arguments to be passed into an attenuated console method call.\n */\nfunction getMessage(snapId: SnapId, message: unknown, ...args: unknown[]) {\n const prefix = `[Snap: ${snapId}]`;\n\n // If the first argument is a string, prepend the prefix to the message, and keep the\n // rest of the arguments as-is.\n if (typeof message === 'string') {\n return [`${prefix} ${message}`, ...args];\n }\n\n // Otherwise, the `message` is an object, array, etc., so add the prefix as a separate\n // message to the arguments.\n return [prefix, message, ...args];\n}\n\n/**\n * Create a a {@link console} object, with the same properties as the global\n * {@link console} object, but with some methods replaced.\n *\n * @param options - Factory options used in construction of the endowment.\n * @param options.snapId - The id of the snap that will interact with the endowment.\n * @returns The {@link console} object with the replaced methods.\n */\nfunction createConsole({ snapId }: EndowmentFactoryOptions = {}) {\n assert(snapId !== undefined);\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.console,\n ) as (keyof typeof console)[];\n\n const attenuatedConsole = keys.reduce((target, key) => {\n if (consoleMethods.has(key) && !consoleAttenuatedMethods.has(key)) {\n return { ...target, [key]: rootRealmGlobal.console[key] };\n }\n\n return target;\n }, {});\n\n return harden({\n console: {\n ...attenuatedConsole,\n assert: (\n value: any,\n message?: string | undefined,\n ...optionalParams: any[]\n ) => {\n rootRealmGlobal.console.assert(\n value,\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n ...consoleFunctions.reduce<ConsoleFunctions>((target, key) => {\n return {\n ...target,\n [key]: (message?: unknown, ...optionalParams: any[]) => {\n rootRealmGlobal.console[key](\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n };\n }, {} as ConsoleFunctions),\n },\n });\n}\n\nconst endowmentModule = {\n names: ['console'] as const,\n factory: createConsole,\n};\n\nexport default endowmentModule;\n"],"names":["consoleAttenuatedMethods","consoleMethods","Set","consoleFunctions","getMessage","snapId","message","args","prefix","createConsole","assert","undefined","keys","Object","getOwnPropertyNames","rootRealmGlobal","console","attenuatedConsole","reduce","target","key","has","harden","value","optionalParams","endowmentModule","names","factory"],"mappings":";;;;;;;;;;;IAMaA,wBAAwB;eAAxBA;;IAaAC,cAAc;eAAdA;;IA6Gb,OAA+B;eAA/B;;;uBA/HuB;8BAES;AAGzB,MAAMD,2BAA2B,IAAIE,IAAI;IAC9C;IACA;IACA;IACA;IACA;IACA;CACD;AAMM,MAAMD,iBAAiB,IAAIC,IAAI;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAMC,mBAAmB;IAAC;IAAO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AAC,EAAsB;QAC5B;IACF;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAASlB;AACX;MAEA,WAAegB"}
|
|
@@ -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
|
|
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
|
|
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
|
|
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":["
|
|
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
|
|
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));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/common/endowments/timeout.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"sources":["../../../../src/common/endowments/timeout.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\n\nconst MINIMUM_TIMEOUT = 10;\n\n/**\n * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such\n * that:\n * - `setTimeout` throws if its \"handler\" parameter is not a function.\n * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setTimeout` and `clearTimeout`\n * functions.\n */\nconst createTimeout = () => {\n const registeredHandles = new Map<unknown, unknown>();\n const _setTimeout = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw rpcErrors.internal(\n `The timeout handler must be a function. Received: ${typeof handler}.`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setTimeout(() => {\n registeredHandles.delete(handle);\n handler();\n }, Math.max(MINIMUM_TIMEOUT, timeout ?? 0));\n\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearTimeout = (handle: unknown): void => {\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearTimeout(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearTimeout(handle);\n }\n };\n\n return {\n setTimeout: harden(_setTimeout),\n clearTimeout: harden(_clearTimeout),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setTimeout', 'clearTimeout'] as const,\n factory: createTimeout,\n};\nexport default endowmentModule;\n"],"names":["MINIMUM_TIMEOUT","createTimeout","registeredHandles","Map","_setTimeout","handler","timeout","rpcErrors","internal","harden","handle","Object","freeze","create","platformHandle","setTimeout","delete","Math","max","set","_clearTimeout","get","undefined","clearTimeout","teardownFunction","keys","endowmentModule","names","factory"],"mappings":";;;;+BA0DA;;;eAAA;;;2BA1D0B;AAE1B,MAAMA,kBAAkB;AAExB;;;;;;;;;CASC,GACD,MAAMC,gBAAgB;IACpB,MAAMC,oBAAoB,IAAIC;IAC9B,MAAMC,cAAc,CAACC,SAAuBC;QAC1C,IAAI,OAAOD,YAAY,YAAY;YACjC,MAAME,oBAAS,CAACC,QAAQ,CACtB,CAAC,kDAAkD,EAAE,OAAOH,QAAQ,CAAC,CAAC;QAE1E;QACAI,OAAOJ;QACP,MAAMK,SAASC,OAAOC,MAAM,CAACD,OAAOE,MAAM,CAAC;QAC3C,MAAMC,iBAAiBC,WAAW;YAChCb,kBAAkBc,MAAM,CAACN;YACzBL;QACF,GAAGY,KAAKC,GAAG,CAAClB,iBAAiBM,WAAW;QAExCJ,kBAAkBiB,GAAG,CAACT,QAAQI;QAC9B,OAAOJ;IACT;IAEA,MAAMU,gBAAgB,CAACV;QACrB,MAAMI,iBAAiBZ,kBAAkBmB,GAAG,CAACX;QAC7C,IAAII,mBAAmBQ,WAAW;YAChCC,aAAaT;YACbZ,kBAAkBc,MAAM,CAACN;QAC3B;IACF;IAEA,MAAMc,mBAAmB;QACvB,KAAK,MAAMd,UAAUR,kBAAkBuB,IAAI,GAAI;YAC7CL,cAAcV;QAChB;IACF;IAEA,OAAO;QACLK,YAAYN,OAAOL;QACnBmB,cAAcd,OAAOW;QACrBI;IACF;AACF;AAEA,MAAME,kBAAkB;IACtBC,OAAO;QAAC;QAAc;KAAe;IACrCC,SAAS3B;AACX;MACA,WAAeyB"}
|
|
@@ -16,6 +16,7 @@ _export(exports, {
|
|
|
16
16
|
return removeEventListener;
|
|
17
17
|
}
|
|
18
18
|
});
|
|
19
|
+
const _rpcerrors = require("@metamask/rpc-errors");
|
|
19
20
|
const _globalObject = require("./globalObject");
|
|
20
21
|
function addEventListener(event, listener) {
|
|
21
22
|
if ('addEventListener' in _globalObject.rootRealmGlobal && typeof _globalObject.rootRealmGlobal.addEventListener === 'function') {
|
|
@@ -24,7 +25,7 @@ function addEventListener(event, listener) {
|
|
|
24
25
|
if (_globalObject.rootRealmGlobal.process && 'on' in _globalObject.rootRealmGlobal.process && typeof _globalObject.rootRealmGlobal.process.on === 'function') {
|
|
25
26
|
return _globalObject.rootRealmGlobal.process.on(event, listener);
|
|
26
27
|
}
|
|
27
|
-
throw
|
|
28
|
+
throw _rpcerrors.rpcErrors.internal('Platform agnostic addEventListener failed.');
|
|
28
29
|
}
|
|
29
30
|
function removeEventListener(event, listener) {
|
|
30
31
|
if ('removeEventListener' in _globalObject.rootRealmGlobal && typeof _globalObject.rootRealmGlobal.removeEventListener === 'function') {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/globalEvents.ts"],"sourcesContent":["import { rootRealmGlobal } from './globalObject';\n\n/**\n * Adds an event listener platform agnostically, trying both `globalThis.addEventListener` and `globalThis.process.on`\n *\n * @param event - The event to listen for.\n * @param listener - The listener to be triggered when the event occurs.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function addEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'addEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.addEventListener === 'function'\n ) {\n return rootRealmGlobal.addEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'on' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.on === 'function'\n ) {\n return rootRealmGlobal.process.on(event, listener);\n }\n\n throw
|
|
1
|
+
{"version":3,"sources":["../../../src/common/globalEvents.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\n\nimport { rootRealmGlobal } from './globalObject';\n\n/**\n * Adds an event listener platform agnostically, trying both `globalThis.addEventListener` and `globalThis.process.on`\n *\n * @param event - The event to listen for.\n * @param listener - The listener to be triggered when the event occurs.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function addEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'addEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.addEventListener === 'function'\n ) {\n return rootRealmGlobal.addEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'on' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.on === 'function'\n ) {\n return rootRealmGlobal.process.on(event, listener);\n }\n\n throw rpcErrors.internal('Platform agnostic addEventListener failed.');\n}\n\n/**\n * Removes an event listener platform agnostically, trying both `globalThis.removeEventListener` and `globalThis.process.removeListener`\n *\n * @param event - The event to remove the listener for.\n * @param listener - The currently attached listener.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function removeEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'removeEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.removeEventListener === 'function'\n ) {\n return rootRealmGlobal.removeEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'removeListener' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.removeListener === 'function'\n ) {\n return rootRealmGlobal.process.removeListener(event, listener);\n }\n\n throw new Error('Platform agnostic removeEventListener failed');\n}\n"],"names":["addEventListener","removeEventListener","event","listener","rootRealmGlobal","toLowerCase","process","on","rpcErrors","internal","removeListener","Error"],"mappings":";;;;;;;;;;;IAYgBA,gBAAgB;eAAhBA;;IA8BAC,mBAAmB;eAAnBA;;;2BA1CU;8BAEM;AAUzB,SAASD,iBACdE,KAAa,EACbC,QAAkC;IAElC,IACE,sBAAsBC,6BAAe,IACrC,OAAOA,6BAAe,CAACJ,gBAAgB,KAAK,YAC5C;QACA,OAAOI,6BAAe,CAACJ,gBAAgB,CAACE,MAAMG,WAAW,IAAIF;IAC/D;IAEA,IACEC,6BAAe,CAACE,OAAO,IACvB,QAAQF,6BAAe,CAACE,OAAO,IAC/B,OAAOF,6BAAe,CAACE,OAAO,CAACC,EAAE,KAAK,YACtC;QACA,OAAOH,6BAAe,CAACE,OAAO,CAACC,EAAE,CAACL,OAAOC;IAC3C;IAEA,MAAMK,oBAAS,CAACC,QAAQ,CAAC;AAC3B;AAUO,SAASR,oBACdC,KAAa,EACbC,QAAkC;IAElC,IACE,yBAAyBC,6BAAe,IACxC,OAAOA,6BAAe,CAACH,mBAAmB,KAAK,YAC/C;QACA,OAAOG,6BAAe,CAACH,mBAAmB,CAACC,MAAMG,WAAW,IAAIF;IAClE;IAEA,IACEC,6BAAe,CAACE,OAAO,IACvB,oBAAoBF,6BAAe,CAACE,OAAO,IAC3C,OAAOF,6BAAe,CAACE,OAAO,CAACI,cAAc,KAAK,YAClD;QACA,OAAON,6BAAe,CAACE,OAAO,CAACI,cAAc,CAACR,OAAOC;IACvD;IAEA,MAAM,IAAIQ,MAAM;AAClB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/globalObject.ts"],"sourcesContent":["enum GlobalObjectNames {\n // The globalThis entry is incorrectly identified as shadowing the global\n // globalThis.\n /* eslint-disable @typescript-eslint/naming-convention */\n // eslint-disable-next-line @typescript-eslint/no-shadow\n globalThis = 'globalThis',\n global = 'global',\n self = 'self',\n window = 'window',\n /* eslint-
|
|
1
|
+
{"version":3,"sources":["../../../src/common/globalObject.ts"],"sourcesContent":["enum GlobalObjectNames {\n // The globalThis entry is incorrectly identified as shadowing the global\n // globalThis.\n /* eslint-disable @typescript-eslint/naming-convention */\n // eslint-disable-next-line @typescript-eslint/no-shadow\n globalThis = 'globalThis',\n global = 'global',\n self = 'self',\n window = 'window',\n /* eslint-enable @typescript-eslint/naming-convention */\n}\n\nlet _rootRealmGlobal: typeof globalThis;\nlet _rootRealmGlobalName: string;\n\n/* istanbul ignore next */\n/* eslint-disable no-negated-condition */\nif (typeof globalThis !== 'undefined') {\n _rootRealmGlobal = globalThis;\n _rootRealmGlobalName = GlobalObjectNames.globalThis;\n} else if (typeof self !== 'undefined') {\n _rootRealmGlobal = self;\n _rootRealmGlobalName = GlobalObjectNames.self;\n} else if (typeof window !== 'undefined') {\n _rootRealmGlobal = window;\n _rootRealmGlobalName = GlobalObjectNames.window;\n} else if (typeof global !== 'undefined') {\n _rootRealmGlobal = global;\n _rootRealmGlobalName = GlobalObjectNames.global;\n} else {\n throw new Error('Unknown realm type; failed to identify global object.');\n}\n/* eslint-enable no-negated-condition */\n\n/**\n * A platform-agnostic alias for the root realm global object.\n */\nconst rootRealmGlobal = _rootRealmGlobal;\n\n/**\n * The string literal corresponding to the name of the root realm global object.\n */\nconst rootRealmGlobalName = _rootRealmGlobalName;\n\nexport { rootRealmGlobal, rootRealmGlobalName };\n"],"names":["rootRealmGlobal","rootRealmGlobalName","GlobalObjectNames","globalThis","global","self","window","_rootRealmGlobal","_rootRealmGlobalName","Error"],"mappings":";;;;;;;;;;;IA4CSA,eAAe;eAAfA;;IAAiBC,mBAAmB;eAAnBA;;;IA5C1B;UAAKC,iBAAiB;IAAjBA,kBACH,yEAAyE;IACzE,cAAc;IACd,uDAAuD,GACvD,wDAAwD;IACxDC,gBAAAA;IALGD,kBAMHE,YAAAA;IANGF,kBAOHG,UAAAA;IAPGH,kBAQHI,YAAAA;GARGJ,sBAAAA;AAYL,IAAIK;AACJ,IAAIC;AAEJ,wBAAwB,GACxB,uCAAuC,GACvC,IAAI,OAAOL,eAAe,aAAa;IACrCI,mBAAmBJ;IACnBK,uBAAuBN,kBAAkBC,UAAU;AACrD,OAAO,IAAI,OAAOE,SAAS,aAAa;IACtCE,mBAAmBF;IACnBG,uBAAuBN,kBAAkBG,IAAI;AAC/C,OAAO,IAAI,OAAOC,WAAW,aAAa;IACxCC,mBAAmBD;IACnBE,uBAAuBN,kBAAkBI,MAAM;AACjD,OAAO,IAAI,OAAOF,WAAW,aAAa;IACxCG,mBAAmBH;IACnBI,uBAAuBN,kBAAkBE,MAAM;AACjD,OAAO;IACL,MAAM,IAAIK,MAAM;AAClB;AACA,sCAAsC,GAEtC;;CAEC,GACD,MAAMT,kBAAkBO;AAExB;;CAEC,GACD,MAAMN,sBAAsBO"}
|