@metamask/snaps-execution-environments 2.0.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -1
- package/dist/browserify/iframe/bundle.js +5 -5
- package/dist/browserify/iframe/index.html +7569 -7166
- package/dist/browserify/node-process/bundle.js +7570 -7167
- package/dist/browserify/node-thread/bundle.js +7570 -7167
- package/dist/browserify/offscreen/bundle.js +4 -4
- package/dist/browserify/offscreen/index.html +7569 -7166
- package/dist/browserify/worker-executor/bundle.js +7574 -7171
- package/dist/browserify/worker-pool/bundle.js +1 -1
- package/dist/browserify/worker-pool/index.html +7569 -7166
- package/dist/cjs/common/BaseSnapExecutor.js +12 -15
- 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/utils.js +9 -0
- package/dist/cjs/common/utils.js.map +1 -1
- package/dist/esm/common/BaseSnapExecutor.js +13 -11
- 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/utils.js +12 -1
- package/dist/esm/common/utils.js.map +1 -1
- package/dist/types/common/utils.d.ts +7 -0
- package/package.json +11 -12
|
@@ -17,7 +17,6 @@ const _ethrpcerrors = require("eth-rpc-errors");
|
|
|
17
17
|
const _jsonrpcengine = require("json-rpc-engine");
|
|
18
18
|
const _superstruct = require("superstruct");
|
|
19
19
|
const _logging = require("../logging");
|
|
20
|
-
const _openrpcjson = /*#__PURE__*/ _interop_require_default(require("../openrpc.json"));
|
|
21
20
|
const _commands = require("./commands");
|
|
22
21
|
const _endowments = require("./endowments");
|
|
23
22
|
const _globalEvents = require("./globalEvents");
|
|
@@ -37,11 +36,6 @@ function _define_property(obj, key, value) {
|
|
|
37
36
|
}
|
|
38
37
|
return obj;
|
|
39
38
|
}
|
|
40
|
-
function _interop_require_default(obj) {
|
|
41
|
-
return obj && obj.__esModule ? obj : {
|
|
42
|
-
default: obj
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
39
|
const fallbackError = {
|
|
46
40
|
code: _ethrpcerrors.errorCodes.rpc.internal,
|
|
47
41
|
message: 'Execution Environment Error'
|
|
@@ -104,12 +98,6 @@ class BaseSnapExecutor {
|
|
|
104
98
|
throw new Error('Command stream received a non-JSON-RPC request.');
|
|
105
99
|
}
|
|
106
100
|
const { id, method, params } = message;
|
|
107
|
-
if (method === 'rpc.discover') {
|
|
108
|
-
this.respond(id, {
|
|
109
|
-
result: _openrpcjson.default
|
|
110
|
-
});
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
101
|
if (!(0, _utils.hasProperty)(EXECUTION_ENVIRONMENT_METHODS, method)) {
|
|
114
102
|
this.respond(id, {
|
|
115
103
|
error: _ethrpcerrors.ethErrors.rpc.methodNotFound({
|
|
@@ -160,7 +148,16 @@ class BaseSnapExecutor {
|
|
|
160
148
|
}
|
|
161
149
|
respond(id, requestObject) {
|
|
162
150
|
if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
|
|
163
|
-
|
|
151
|
+
// Instead of throwing, we directly respond with an error.
|
|
152
|
+
// This prevents an issue where we wouldn't respond when errors were non-serializable
|
|
153
|
+
this.commandStream.write({
|
|
154
|
+
error: (0, _ethrpcerrors.serializeError)(new Error('JSON-RPC responses must be JSON serializable objects.'), {
|
|
155
|
+
fallbackError
|
|
156
|
+
}),
|
|
157
|
+
id,
|
|
158
|
+
jsonrpc: '2.0'
|
|
159
|
+
});
|
|
160
|
+
return;
|
|
164
161
|
}
|
|
165
162
|
this.commandStream.write({
|
|
166
163
|
...requestObject,
|
|
@@ -275,7 +272,7 @@ class BaseSnapExecutor {
|
|
|
275
272
|
*/ createSnapGlobal(provider) {
|
|
276
273
|
const originalRequest = provider.request.bind(provider);
|
|
277
274
|
const request = async (args)=>{
|
|
278
|
-
const sanitizedArgs = (0,
|
|
275
|
+
const sanitizedArgs = (0, _utils1.sanitizeRequestArguments)(args);
|
|
279
276
|
(0, _utils1.assertSnapOutboundRequest)(sanitizedArgs);
|
|
280
277
|
this.notify({
|
|
281
278
|
method: 'OutboundRequest'
|
|
@@ -313,7 +310,7 @@ class BaseSnapExecutor {
|
|
|
313
310
|
*/ createEIP1193Provider(provider) {
|
|
314
311
|
const originalRequest = provider.request.bind(provider);
|
|
315
312
|
const request = async (args)=>{
|
|
316
|
-
const sanitizedArgs = (0,
|
|
313
|
+
const sanitizedArgs = (0, _utils1.sanitizeRequestArguments)(args);
|
|
317
314
|
(0, _utils1.assertEthereumOutboundRequest)(sanitizedArgs);
|
|
318
315
|
this.notify({
|
|
319
316
|
method: 'OutboundRequest'
|
|
@@ -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 EEOpenRPCDocument from '../openrpc.json';\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 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 if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = 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 throw new Error('JSON-RPC responses must be JSON serializable objects.');\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param 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 = getSafeJson(args) as RequestArguments;\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 = getSafeJson(args) as RequestArguments;\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","respond","result","EEOpenRPCDocument","hasProperty","ethErrors","methodNotFound","serialize","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","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","getSafeJson","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","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BAuGnDA;;;eAAAA;;;2BAtGkB;4BAYxB;uBAcA;8BAC+C;+BACd;6BAEf;yBAEL;oEACU;0BAEkB;4BACf;8BACqB;4BACxB;wBAOvB;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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AAQ,CAACzH;YAC7B,IAAI,CAACU,gBAAgB,CAACV,MAAM0H,KAAK,CAAC,CAAC3H;gBACjC,qCAAqC;gBACrC4H,IAAAA,oBAAQ,EAAC5H;YACX;QACF;QACA,IAAI,CAAC8C,SAAS,GAAGA;QAEjB,IAAI,CAACnB,OAAO,GAAGkG,IAAAA,yCAA+B,EAC5C,IAAI,CAAC1F,SAAS,CAAC0D,IAAI,CAAC,IAAI,GACxB,OAAOiC,QAAQC,aAAajC;YAC1B,MAAM7F,OAAO,IAAI,CAAC4D,QAAQ,CAACsB,GAAG,CAAC2C;YAC/B,uEAAuE;YACvE,mBAAmB;YACnB,MAAME,UAAU/H,MAAMuD,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,IAAIhH,SAAS,MAAM,IAAI,CAAC0D,oBAAoB,CAACoD,QAAQ,IACnDE,QAAQlC;YAGV,0EAA0E;YAC1E,IAAI9E,WAAWyF,WAAW;gBACxBzF,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOgF,IAAAA,kBAAW,EAAChF;YACrB,EAAE,OAAOhB,OAAO;gBACd,MAAM,IAAImI,UACR,CAAC,sCAAsC,EAAEnI,MAAMb,OAAO,CAACiJ,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAACtD,WAAW,CAACe,IAAI,CAAC,IAAI;IAE9B;AAkWF"}
|
|
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,EAACH;QACxC,MAAMI,kBAAkBC,IAAAA,4BAAc,EAACH,kBAAkB;YACvDpB;YACAwB,oBAAoB;QACtB;QAEA,gEAAgE;QAChE,MAAMC,WAAiB;YAAE,GAAGN,IAAI;YAAEO,OAAON,kBAAkBM,SAAS;QAAK;QAEzE,IAAI,CAACC,MAAM,CAAC;YACVC,QAAQ;YACRlB,QAAQ;gBACNQ,OAAO;oBACL,GAAGI,eAAe;oBAClBH,MAAMM;gBACR;YACF;QACF;IACF;IAEA,MAAcI,iBAAiBxB,OAAuB,EAAE;QACtD,IAAI,CAACyB,IAAAA,uBAAgB,EAACzB,UAAU;YAC9B,MAAM,IAAI0B,MAAM;QAClB;QAEA,MAAM,EAAEC,EAAE,EAAEJ,MAAM,EAAElB,MAAM,EAAE,GAAGL;QAE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AED,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 +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;;;4BA7FY;uBACK;4BAc1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKN,uBAAW,CAACO,YAAY;YAAE;gBAC7BC,IAAAA,gDAAoC,EAACT,QAAQI,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEI,MAAM,EAAEC,OAAO,EAAE,GAChCX,QAAQI,MAAM;gBAEhB,OAAOM,SACH;oBACEJ;oBACAI;gBACF,IACA;oBACEJ;oBACAK;gBACF;YACN;QACA,KAAKV,uBAAW,CAACW,YAAY;QAC7B,KAAKX,uBAAW,CAACY,gBAAgB;YAC/B,OAAO;gBAAEf;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACa,SAAS;QAC1B,KAAKb,uBAAW,CAACc,SAAS;QAC1B,KAAKd,uBAAW,CAACe,QAAQ;YACvB,OAAO;gBAAEhB;YAAQ;QAEnB;YACE,OAAOiB,IAAAA,uBAAgB,EAAClB;IAC5B;AACF;AAaO,SAASF,gCACdqB,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQ/B,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMmB,WACLW,QACA/B,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
|
|
@@ -1 +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;AAMlE;;;;;;;;CAQC,GACD,SAASC,WAAWC,MAAc,EAAEC,OAAgB,EAAE,GAAGC,IAAe;IACtE,MAAMC,SAAS,CAAC,OAAO,EAAEH,OAAO,CAAC,CAAC;IAElC,qFAAqF;IACrF,+BAA+B;IAC/B,IAAI,OAAOC,YAAY,UAAU;QAC/B,OAAO;YAAC,CAAC,EAAEE,OAAO,CAAC,EAAEF,QAAQ,CAAC;eAAKC;SAAK;IAC1C;IAEA,sFAAsF;IACtF,4BAA4B;IAC5B,OAAO;QAACC;QAAQF;WAAYC;KAAK;AACnC;AAEA;;;;;;;CAOC,GACD,SAASE,cAAc,EAAEJ,MAAM,EAA2B,GAAG,CAAC,CAAC;IAC7DK,IAAAA,aAAM,EAACL,WAAWM;IAClB,MAAMC,OAAOC,OAAOC,mBAAmB,CACrCC,6BAAe,CAACC,OAAO;IAGzB,MAAMC,oBAAoBL,KAAKM,MAAM,CAAC,CAACC,QAAQC;QAC7C,IAAInB,eAAeoB,GAAG,CAACD,QAAQ,CAACpB,yBAAyBqB,GAAG,CAACD,MAAM;YACjE,OAAO;gBAAE,GAAGD,MAAM;gBAAE,CAACC,IAAI,EAAEL,6BAAe,CAACC,OAAO,CAACI,IAAI;YAAC;QAC1D;QAEA,OAAOD;IACT,GAAG,CAAC;IAEJ,OAAOG,OAAO;QACZN,SAAS;YACP,GAAGC,iBAAiB;YACpBP,QAAQ,CACNa,OACAjB,SACA,GAAGkB;gBAEHT,6BAAe,CAACC,OAAO,CAACN,MAAM,CAC5Ba,UACGnB,WAAWC,QAAQC,YAAYkB;YAEtC;YACA,GAAGrB,iBAAiBe,MAAM,CAAmB,CAACC,QAAQC;gBACpD,OAAO;oBACL,GAAGD,MAAM;oBACT,CAACC,IAAI,EAAE,CAACd,SAAmB,GAAGkB;wBAC5BT,6BAAe,CAACC,OAAO,CAACI,IAAI,IACvBhB,WAAWC,QAAQC,YAAYkB;oBAEtC;gBACF;YACF,GAAG,CAAC,EAAsB;QAC5B;IACF;AACF;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;IAAS;IAAS;IAAQ;CAAO;AAMlE;;;;;;;;CAQC,GACD,SAASC,WAAWC,MAAc,EAAEC,OAAgB,EAAE,GAAGC,IAAe;IACtE,MAAMC,SAAS,CAAC,OAAO,EAAEH,OAAO,CAAC,CAAC;IAElC,qFAAqF;IACrF,+BAA+B;IAC/B,IAAI,OAAOC,YAAY,UAAU;QAC/B,OAAO;YAAC,CAAC,EAAEE,OAAO,CAAC,EAAEF,QAAQ,CAAC;eAAKC;SAAK;IAC1C;IAEA,sFAAsF;IACtF,4BAA4B;IAC5B,OAAO;QAACC;QAAQF;WAAYC;KAAK;AACnC;AAEA;;;;;;;CAOC,GACD,SAASE,cAAc,EAAEJ,MAAM,EAA2B,GAAG,CAAC,CAAC;IAC7DK,IAAAA,aAAM,EAACL,WAAWM;IAClB,MAAMC,OAAOC,OAAOC,mBAAmB,CACrCC,6BAAe,CAACC,OAAO;IAGzB,MAAMC,oBAAoBL,KAAKM,MAAM,CAAC,CAACC,QAAQC;QAC7C,IAAInB,eAAeoB,GAAG,CAACD,QAAQ,CAACpB,yBAAyBqB,GAAG,CAACD,MAAM;YACjE,OAAO;gBAAE,GAAGD,MAAM;gBAAE,CAACC,IAAI,EAAEL,6BAAe,CAACC,OAAO,CAACI,IAAI;YAAC;QAC1D;QAEA,OAAOD;IACT,GAAG,CAAC;IAEJ,OAAOG,OAAO;QACZN,SAAS;YACP,GAAGC,iBAAiB;YACpBP,QAAQ,CACNa,OACAjB,SACA,GAAGkB;gBAEHT,6BAAe,CAACC,OAAO,CAACN,MAAM,CAC5Ba,UACGnB,WAAWC,QAAQC,YAAYkB;YAEtC;YACA,GAAGrB,iBAAiBe,MAAM,CAAmB,CAACC,QAAQC;gBACpD,OAAO;oBACL,GAAGD,MAAM;oBACT,CAACC,IAAI,EAAE,CAACd,SAAmB,GAAGkB;wBAC5BT,6BAAe,CAACC,OAAO,CAACI,IAAI,IACvBhB,WAAWC,QAAQC,YAAYkB;oBAEtC;gBACF;YACF,GAAG,CAAC,EAAsB;QAC5B;IACF;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAASlB;AACX;MAEA,WAAegB"}
|
package/dist/cjs/common/utils.js
CHANGED
|
@@ -26,6 +26,9 @@ _export(exports, {
|
|
|
26
26
|
},
|
|
27
27
|
assertEthereumOutboundRequest: function() {
|
|
28
28
|
return assertEthereumOutboundRequest;
|
|
29
|
+
},
|
|
30
|
+
sanitizeRequestArguments: function() {
|
|
31
|
+
return sanitizeRequestArguments;
|
|
29
32
|
}
|
|
30
33
|
});
|
|
31
34
|
const _utils = require("@metamask/utils");
|
|
@@ -128,5 +131,11 @@ function assertEthereumOutboundRequest(args) {
|
|
|
128
131
|
}));
|
|
129
132
|
(0, _utils.assertStruct)(args, _utils.JsonStruct, 'Provided value is not JSON-RPC compatible');
|
|
130
133
|
}
|
|
134
|
+
function sanitizeRequestArguments(value) {
|
|
135
|
+
// Before passing to getSafeJson we run the value through JSON serialization.
|
|
136
|
+
// This lets request arguments contain undefined which is normally disallowed.
|
|
137
|
+
const json = JSON.parse(JSON.stringify(value));
|
|
138
|
+
return (0, _utils.getSafeJson)(json);
|
|
139
|
+
}
|
|
131
140
|
|
|
132
141
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/utils.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { assert, assertStruct, JsonStruct } from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { log } from '../logging';\n\n/**\n * Takes an error that was thrown, determines if it is\n * an error object. If it is then it will return that. Otherwise,\n * an error object is created with the original error message.\n *\n * @param originalError - The error that was originally thrown.\n * @returns An error object.\n */\nexport function constructError(originalError: unknown) {\n let _originalError: Error | undefined;\n if (originalError instanceof Error) {\n _originalError = originalError;\n } else if (typeof originalError === 'string') {\n _originalError = new Error(originalError);\n // The stack is useless in this case.\n delete _originalError.stack;\n }\n return _originalError;\n}\n\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<Type>(\n originalPromise: Promise<Type>,\n teardownRef: { lastTeardown: number },\n): Promise<Type> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<Type>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that narrows down (attenuates) the fields available on\n * the StreamProvider and replaces the request implementation.\n *\n * @param provider - Instance of a StreamProvider to be limited.\n * @param request - Custom attenuated request object.\n * @returns Proxy to the StreamProvider instance.\n */\nexport function proxyStreamProvider(\n provider: StreamProvider,\n request: unknown,\n): StreamProvider {\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 proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return (\n typeof prop === 'string' &&\n ['request', 'on', 'removeListener'].includes(prop)\n );\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return provider[prop];\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendRawTransaction',\n 'eth_sendTransaction',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n"],"names":["constructError","withTeardown","proxyStreamProvider","BLOCKED_RPC_METHODS","assertSnapOutboundRequest","assertEthereumOutboundRequest","originalError","_originalError","Error","stack","originalPromise","teardownRef","myTeardown","lastTeardown","Promise","resolve","reject","then","value","log","catch","reason","provider","request","proxy","Proxy","has","_target","prop","includes","get","undefined","Object","freeze","args","assert","String","prototype","startsWith","call","method","ethErrors","rpc","methodNotFound","data","assertStruct","JsonStruct"],"mappings":";;;;;;;;;;;IAegBA,cAAc;eAAdA;;IAsBMC,YAAY;eAAZA;;IAoCNC,mBAAmB;eAAnBA;;IA+BHC,mBAAmB;eAAnBA;;IAyBGC,yBAAyB;eAAzBA;;IAuBAC,6BAA6B;eAA7BA;;;
|
|
1
|
+
{"version":3,"sources":["../../../src/common/utils.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { assert, assertStruct, getSafeJson, JsonStruct } from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { log } from '../logging';\n\n/**\n * Takes an error that was thrown, determines if it is\n * an error object. If it is then it will return that. Otherwise,\n * an error object is created with the original error message.\n *\n * @param originalError - The error that was originally thrown.\n * @returns An error object.\n */\nexport function constructError(originalError: unknown) {\n let _originalError: Error | undefined;\n if (originalError instanceof Error) {\n _originalError = originalError;\n } else if (typeof originalError === 'string') {\n _originalError = new Error(originalError);\n // The stack is useless in this case.\n delete _originalError.stack;\n }\n return _originalError;\n}\n\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<Type>(\n originalPromise: Promise<Type>,\n teardownRef: { lastTeardown: number },\n): Promise<Type> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<Type>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that narrows down (attenuates) the fields available on\n * the StreamProvider and replaces the request implementation.\n *\n * @param provider - Instance of a StreamProvider to be limited.\n * @param request - Custom attenuated request object.\n * @returns Proxy to the StreamProvider instance.\n */\nexport function proxyStreamProvider(\n provider: StreamProvider,\n request: unknown,\n): StreamProvider {\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 proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return (\n typeof prop === 'string' &&\n ['request', 'on', 'removeListener'].includes(prop)\n );\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return provider[prop];\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendRawTransaction',\n 'eth_sendTransaction',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n\n/**\n * Gets a sanitized value to be used for passing to the underlying MetaMask provider.\n *\n * @param value - An unsanitized value from a snap.\n * @returns A sanitized value ready to be passed to a MetaMask provider.\n */\nexport function sanitizeRequestArguments(value: unknown): RequestArguments {\n // Before passing to getSafeJson we run the value through JSON serialization.\n // This lets request arguments contain undefined which is normally disallowed.\n const json = JSON.parse(JSON.stringify(value));\n return getSafeJson(json) as RequestArguments;\n}\n"],"names":["constructError","withTeardown","proxyStreamProvider","BLOCKED_RPC_METHODS","assertSnapOutboundRequest","assertEthereumOutboundRequest","sanitizeRequestArguments","originalError","_originalError","Error","stack","originalPromise","teardownRef","myTeardown","lastTeardown","Promise","resolve","reject","then","value","log","catch","reason","provider","request","proxy","Proxy","has","_target","prop","includes","get","undefined","Object","freeze","args","assert","String","prototype","startsWith","call","method","ethErrors","rpc","methodNotFound","data","assertStruct","JsonStruct","json","JSON","parse","stringify","getSafeJson"],"mappings":";;;;;;;;;;;IAegBA,cAAc;eAAdA;;IAsBMC,YAAY;eAAZA;;IAoCNC,mBAAmB;eAAnBA;;IA+BHC,mBAAmB;eAAnBA;;IAyBGC,yBAAyB;eAAzBA;;IAuBAC,6BAA6B;eAA7BA;;IA2BAC,wBAAwB;eAAxBA;;;uBAjL8C;8BACpC;yBAEN;AAUb,SAASN,eAAeO,aAAsB;IACnD,IAAIC;IACJ,IAAID,yBAAyBE,OAAO;QAClCD,iBAAiBD;IACnB,OAAO,IAAI,OAAOA,kBAAkB,UAAU;QAC5CC,iBAAiB,IAAIC,MAAMF;QAC3B,qCAAqC;QACrC,OAAOC,eAAeE,KAAK;IAC7B;IACA,OAAOF;AACT;AAYO,eAAeP,aACpBU,eAA8B,EAC9BC,WAAqC;IAErC,MAAMC,aAAaD,YAAYE,YAAY;IAC3C,OAAO,IAAIC,QAAc,CAACC,SAASC;QACjCN,gBACGO,IAAI,CAAC,CAACC;YACL,IAAIP,YAAYE,YAAY,KAAKD,YAAY;gBAC3CG,QAAQG;YACV,OAAO;gBACLC,IAAAA,YAAG,EACD;YAEJ;QACF,GACCC,KAAK,CAAC,CAACC;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AAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACL,KAAKM,MAAM,EAAE,UAC/CC,uBAAS,CAACC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFL,IAAAA,aAAM,EACJ,CAACjC,oBAAoB2B,QAAQ,CAACK,KAAKM,MAAM,GACzCC,uBAAS,CAACC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFK,IAAAA,mBAAY,EAACX,MAAMY,iBAAU,EAAE;AACjC;AAQO,SAASzC,yBAAyBa,KAAc;IACrD,6EAA6E;IAC7E,8EAA8E;IAC9E,MAAM6B,OAAOC,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAAChC;IACvC,OAAOiC,IAAAA,kBAAW,EAACJ;AACrB"}
|
|
@@ -20,12 +20,11 @@ import { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';
|
|
|
20
20
|
import { createIdRemapMiddleware } from 'json-rpc-engine';
|
|
21
21
|
import { validate } from 'superstruct';
|
|
22
22
|
import { log } from '../logging';
|
|
23
|
-
import EEOpenRPCDocument from '../openrpc.json';
|
|
24
23
|
import { getCommandMethodImplementations } from './commands';
|
|
25
24
|
import { createEndowments } from './endowments';
|
|
26
25
|
import { addEventListener, removeEventListener } from './globalEvents';
|
|
27
26
|
import { sortParamKeys } from './sortParams';
|
|
28
|
-
import { assertEthereumOutboundRequest, assertSnapOutboundRequest, constructError, proxyStreamProvider, withTeardown } from './utils';
|
|
27
|
+
import { assertEthereumOutboundRequest, assertSnapOutboundRequest, constructError, sanitizeRequestArguments, proxyStreamProvider, withTeardown } from './utils';
|
|
29
28
|
import { ExecuteSnapRequestArgumentsStruct, PingRequestArgumentsStruct, SnapRpcRequestArgumentsStruct, TerminateRequestArgumentsStruct } from './validation';
|
|
30
29
|
const fallbackError = {
|
|
31
30
|
code: errorCodes.rpc.internal,
|
|
@@ -89,12 +88,6 @@ export class BaseSnapExecutor {
|
|
|
89
88
|
throw new Error('Command stream received a non-JSON-RPC request.');
|
|
90
89
|
}
|
|
91
90
|
const { id, method, params } = message;
|
|
92
|
-
if (method === 'rpc.discover') {
|
|
93
|
-
this.respond(id, {
|
|
94
|
-
result: EEOpenRPCDocument
|
|
95
|
-
});
|
|
96
|
-
return;
|
|
97
|
-
}
|
|
98
91
|
if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {
|
|
99
92
|
this.respond(id, {
|
|
100
93
|
error: ethErrors.rpc.methodNotFound({
|
|
@@ -145,7 +138,16 @@ export class BaseSnapExecutor {
|
|
|
145
138
|
}
|
|
146
139
|
respond(id, requestObject) {
|
|
147
140
|
if (!isValidJson(requestObject) || !isObject(requestObject)) {
|
|
148
|
-
|
|
141
|
+
// Instead of throwing, we directly respond with an error.
|
|
142
|
+
// This prevents an issue where we wouldn't respond when errors were non-serializable
|
|
143
|
+
this.commandStream.write({
|
|
144
|
+
error: serializeError(new Error('JSON-RPC responses must be JSON serializable objects.'), {
|
|
145
|
+
fallbackError
|
|
146
|
+
}),
|
|
147
|
+
id,
|
|
148
|
+
jsonrpc: '2.0'
|
|
149
|
+
});
|
|
150
|
+
return;
|
|
149
151
|
}
|
|
150
152
|
this.commandStream.write({
|
|
151
153
|
...requestObject,
|
|
@@ -260,7 +262,7 @@ export class BaseSnapExecutor {
|
|
|
260
262
|
*/ createSnapGlobal(provider) {
|
|
261
263
|
const originalRequest = provider.request.bind(provider);
|
|
262
264
|
const request = async (args)=>{
|
|
263
|
-
const sanitizedArgs =
|
|
265
|
+
const sanitizedArgs = sanitizeRequestArguments(args);
|
|
264
266
|
assertSnapOutboundRequest(sanitizedArgs);
|
|
265
267
|
this.notify({
|
|
266
268
|
method: 'OutboundRequest'
|
|
@@ -298,7 +300,7 @@ export class BaseSnapExecutor {
|
|
|
298
300
|
*/ createEIP1193Provider(provider) {
|
|
299
301
|
const originalRequest = provider.request.bind(provider);
|
|
300
302
|
const request = async (args)=>{
|
|
301
|
-
const sanitizedArgs =
|
|
303
|
+
const sanitizedArgs = sanitizeRequestArguments(args);
|
|
302
304
|
assertEthereumOutboundRequest(sanitizedArgs);
|
|
303
305
|
this.notify({
|
|
304
306
|
method: 'OutboundRequest'
|
|
@@ -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 EEOpenRPCDocument from '../openrpc.json';\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 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 if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = 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 throw new Error('JSON-RPC responses must be JSON serializable objects.');\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param 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 = getSafeJson(args) as RequestArguments;\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 = getSafeJson(args) as RequestArguments;\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":["StreamProvider","SNAP_EXPORT_NAMES","logError","SNAP_EXPORTS","isObject","isValidJson","assert","isJsonRpcRequest","hasProperty","getSafeJson","errorCodes","ethErrors","serializeError","createIdRemapMiddleware","validate","log","EEOpenRPCDocument","getCommandMethodImplementations","createEndowments","addEventListener","removeEventListener","sortParamKeys","assertEthereumOutboundRequest","assertSnapOutboundRequest","constructError","proxyStreamProvider","withTeardown","ExecuteSnapRequestArgumentsStruct","PingRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","TerminateRequestArgumentsStruct","fallbackError","code","rpc","internal","message","EXECUTION_ENVIRONMENT_METHODS","ping","struct","params","executeSnap","terminate","snapRpc","BaseSnapExecutor","errorHandler","error","data","constructedError","serializedError","shouldIncludeStack","sentData","stack","notify","method","onCommandRequest","Error","id","respond","result","methodNotFound","serialize","methodObject","paramsAsArray","invalidParams","methods","rpcError","requestObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","snapPromiseErrorHandler","snapErrorHandler","reason","provider","rpcStream","jsonRpcStreamName","rpcMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","snapData","set","idleTeardown","runningEvaluations","Set","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","onTerminate","forEach","evaluation","stop","clear","get","reduce","acc","exportName","snapExport","validator","originalRequest","request","bind","args","sanitizedArgs","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","streamProviderProxy","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","target","handlerType","handler","required","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;;;;;;;;;;AAChE,SAASA,cAAc,QAAQ,sBAAsB;AAQrD,SACEC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,QACP,wBAAwB;AAO/B,SACEC,QAAQ,EACRC,WAAW,EACXC,MAAM,EACNC,gBAAgB,EAChBC,WAAW,EACXC,WAAW,QACN,kBAAkB;AACzB,SAASC,UAAU,EAAEC,SAAS,EAAEC,cAAc,QAAQ,iBAAiB;AACvE,SAASC,uBAAuB,QAAQ,kBAAkB;AAE1D,SAASC,QAAQ,QAAQ,cAAc;AAEvC,SAASC,GAAG,QAAQ,aAAa;AACjC,OAAOC,uBAAuB,kBAAkB;AAEhD,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,gBAAgB,QAAQ,eAAe;AAChD,SAASC,gBAAgB,EAAEC,mBAAmB,QAAQ,iBAAiB;AACvE,SAASC,aAAa,QAAQ,eAAe;AAC7C,SACEC,6BAA6B,EAC7BC,yBAAyB,EACzBC,cAAc,EACdC,mBAAmB,EACnBC,YAAY,QACP,UAAU;AACjB,SACEC,iCAAiC,EACjCC,0BAA0B,EAC1BC,6BAA6B,EAC7BC,+BAA+B,QAC1B,eAAe;AAYtB,MAAMC,gBAAgB;IACpBC,MAAMtB,WAAWuB,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAUA;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQV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CAACd,OAAO,GAAG/C,gCACb,IAAI,CAACqD,SAAS,CAACkD,IAAI,CAAC,IAAI,GACxB,OAAO0B,QAAQC,aAAa1B;YAC1B,MAAM3E,OAAO,IAAI,CAAC6C,QAAQ,CAACqB,GAAG,CAACkC;YAC/B,uEAAuE;YACvE,mBAAmB;YACnB,MAAME,UAAUtG,MAAMyC,OAAO,CAAC4D,YAAY;YAC1C,MAAM,EAAEE,QAAQ,EAAE,GAAGlJ,YAAY,CAACgJ,YAAY;YAE9C7I,OACE,CAAC+I,YAAYD,YAAYnB,WACzB,CAAC,GAAG,EAAEkB,YAAY,4BAA4B,EAAED,OAAO,CAAC;YAG1D,kEAAkE;YAClE,eAAe;YACf,IAAI,CAACE,SAAS;gBACZ,OAAO;YACT;YAEA,mCAAmC;YACnC,IAAI1F,SAAS,MAAM,IAAI,CAAC6C,oBAAoB,CAAC2C,QAAQ,IACnDE,QAAQ3B;YAGV,0EAA0E;YAC1E,IAAI/D,WAAWuE,WAAW;gBACxBvE,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOjD,YAAYiD;YACrB,EAAE,OAAOb,OAAO;gBACd,MAAM,IAAIyG,UACR,CAAC,sCAAsC,EAAEzG,MAAMV,OAAO,CAACoH,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAAC5C,WAAW,CAACa,IAAI,CAAC,IAAI;IAE9B;AAkWF"}
|
|
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":["StreamProvider","SNAP_EXPORT_NAMES","logError","SNAP_EXPORTS","isObject","isValidJson","assert","isJsonRpcRequest","hasProperty","getSafeJson","errorCodes","ethErrors","serializeError","createIdRemapMiddleware","validate","log","getCommandMethodImplementations","createEndowments","addEventListener","removeEventListener","sortParamKeys","assertEthereumOutboundRequest","assertSnapOutboundRequest","constructError","sanitizeRequestArguments","proxyStreamProvider","withTeardown","ExecuteSnapRequestArgumentsStruct","PingRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","TerminateRequestArgumentsStruct","fallbackError","code","rpc","internal","message","EXECUTION_ENVIRONMENT_METHODS","ping","struct","params","executeSnap","terminate","snapRpc","BaseSnapExecutor","errorHandler","error","data","constructedError","serializedError","shouldIncludeStack","sentData","stack","notify","method","onCommandRequest","Error","id","respond","methodNotFound","serialize","methodObject","paramsAsArray","invalidParams","result","methods","rpcError","requestObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","snapPromiseErrorHandler","snapErrorHandler","reason","provider","rpcStream","jsonRpcStreamName","rpcMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","snapData","set","idleTeardown","runningEvaluations","Set","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","onTerminate","forEach","evaluation","stop","clear","get","reduce","acc","exportName","snapExport","validator","originalRequest","request","bind","args","sanitizedArgs","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","streamProviderProxy","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","target","handlerType","handler","required","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;;;;;;;;;;AAChE,SAASA,cAAc,QAAQ,sBAAsB;AAQrD,SACEC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,QACP,wBAAwB;AAO/B,SACEC,QAAQ,EACR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BACZ,OAAO;YACT;YAEA,mCAAmC;YACnC,IAAIrF,SAAS,MAAM,IAAI,CAACwC,oBAAoB,CAAC2C,QAAQ,IACnDE,QAAQ3B;YAGV,0EAA0E;YAC1E,IAAI1D,WAAWkE,WAAW;gBACxBlE,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOtD,YAAYsD;YACrB,EAAE,OAAOlB,OAAO;gBACd,MAAM,IAAIyG,UACR,CAAC,sCAAsC,EAAEzG,MAAMV,OAAO,CAACoH,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAAC5C,WAAW,CAACa,IAAI,CAAC,IAAI;IAE9B;AAwWF"}
|
|
@@ -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":["HandlerType","assertExhaustive","assertIsOnTransactionRequestArguments","assertIsOnNameLookupRequestArguments","getHandlerArguments","origin","handler","request","OnTransaction","params","transaction","chainId","transactionOrigin","OnNameLookup","domain","address","OnRpcRequest","OnCronjob","OnInstall","OnUpdate","getCommandMethodImplementations","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":"AAAA,SAASA,WAAW,QAAQ,wBAAwB;AACpD,SAASC,gBAAgB,QAAQ,kBAAkB;AAWnD,SACEC,qCAAqC,EACrCC,oCAAoC,QAC/B,eAAe;AAStB;;;;;;;CAOC,GACD,OAAO,SAASC,oBACdC,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKN,YAAYQ,aAAa;YAAE;gBAC9BN,sCAAsCK,QAAQE,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGL,QAAQE,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKZ,YAAYa,YAAY;YAAE;gBAC7BV,qCAAqCI,QAAQE,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEG,MAAM,EAAEC,OAAO,EAAE,GAChCR,QAAQE,MAAM;gBAEhB,OAAOK,SACH;oBACEH;oBACAG;gBACF,IACA;oBACEH;oBACAI;gBACF;YACN;QACA,KAAKf,YAAYgB,YAAY;
|
|
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":["HandlerType","assertExhaustive","assertIsOnTransactionRequestArguments","assertIsOnNameLookupRequestArguments","getHandlerArguments","origin","handler","request","OnTransaction","params","transaction","chainId","transactionOrigin","OnNameLookup","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","getCommandMethodImplementations","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","execut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