@metamask/snaps-execution-environments 6.9.1 → 6.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/dist/browserify/iframe/bundle.js +5 -5
  3. package/dist/browserify/node-process/bundle.js +4 -4
  4. package/dist/browserify/node-thread/bundle.js +4 -4
  5. package/dist/browserify/webview/index.html +5 -5
  6. package/dist/browserify/worker-executor/bundle.js +5 -5
  7. package/dist/browserify/worker-pool/bundle.js +5 -5
  8. package/dist/common/BaseSnapExecutor.cjs +8 -4
  9. package/dist/common/BaseSnapExecutor.cjs.map +1 -1
  10. package/dist/common/BaseSnapExecutor.d.cts.map +1 -1
  11. package/dist/common/BaseSnapExecutor.d.mts.map +1 -1
  12. package/dist/common/BaseSnapExecutor.mjs +9 -5
  13. package/dist/common/BaseSnapExecutor.mjs.map +1 -1
  14. package/dist/common/endowments/commonEndowmentFactory.cjs +1 -0
  15. package/dist/common/endowments/commonEndowmentFactory.cjs.map +1 -1
  16. package/dist/common/endowments/commonEndowmentFactory.d.cts.map +1 -1
  17. package/dist/common/endowments/commonEndowmentFactory.d.mts.map +1 -1
  18. package/dist/common/endowments/commonEndowmentFactory.mjs +1 -0
  19. package/dist/common/endowments/commonEndowmentFactory.mjs.map +1 -1
  20. package/dist/common/endowments/index.cjs.map +1 -1
  21. package/dist/common/endowments/index.d.cts +2 -3
  22. package/dist/common/endowments/index.d.cts.map +1 -1
  23. package/dist/common/endowments/index.d.mts +2 -3
  24. package/dist/common/endowments/index.d.mts.map +1 -1
  25. package/dist/common/endowments/index.mjs.map +1 -1
  26. package/dist/common/endowments/network.cjs +11 -1
  27. package/dist/common/endowments/network.cjs.map +1 -1
  28. package/dist/common/endowments/network.d.cts +29 -7
  29. package/dist/common/endowments/network.d.cts.map +1 -1
  30. package/dist/common/endowments/network.d.mts +29 -7
  31. package/dist/common/endowments/network.d.mts.map +1 -1
  32. package/dist/common/endowments/network.mjs +10 -2
  33. package/dist/common/endowments/network.mjs.map +1 -1
  34. package/dist/common/utils.cjs +1 -27
  35. package/dist/common/utils.cjs.map +1 -1
  36. package/dist/common/utils.d.cts +1 -9
  37. package/dist/common/utils.d.cts.map +1 -1
  38. package/dist/common/utils.d.mts +1 -9
  39. package/dist/common/utils.d.mts.map +1 -1
  40. package/dist/common/utils.mjs +1 -26
  41. package/dist/common/utils.mjs.map +1 -1
  42. package/dist/common/validation.cjs +4 -1
  43. package/dist/common/validation.cjs.map +1 -1
  44. package/dist/common/validation.d.cts +1 -1
  45. package/dist/common/validation.d.cts.map +1 -1
  46. package/dist/common/validation.d.mts +1 -1
  47. package/dist/common/validation.d.mts.map +1 -1
  48. package/dist/common/validation.mjs +5 -2
  49. package/dist/common/validation.mjs.map +1 -1
  50. package/package.json +8 -8
@@ -100,6 +100,7 @@ class BaseSnapExecutor {
100
100
  const serializedError = (0, rpc_errors_1.serializeError)(error, {
101
101
  fallbackError: unhandledError,
102
102
  shouldIncludeStack: false,
103
+ shouldPreserveMessage: false,
103
104
  });
104
105
  const errorData = (0, snaps_sdk_1.getErrorData)(serializedError);
105
106
  __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_notify).call(this, {
@@ -173,6 +174,7 @@ class BaseSnapExecutor {
173
174
  await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_respond).call(this, id, {
174
175
  error: (0, rpc_errors_1.serializeError)(rpcError, {
175
176
  fallbackError,
177
+ shouldPreserveMessage: false,
176
178
  }),
177
179
  });
178
180
  }
@@ -293,6 +295,7 @@ class BaseSnapExecutor {
293
295
  createSnapGlobal(provider) {
294
296
  const originalRequest = provider.request.bind(provider);
295
297
  const request = async (args) => {
298
+ // As part of the sanitization, we validate that the args are valid JSON.
296
299
  const sanitizedArgs = (0, utils_2.sanitizeRequestArguments)(args);
297
300
  (0, utils_2.assertSnapOutboundRequest)(sanitizedArgs);
298
301
  return await (0, utils_2.withTeardown)((async () => {
@@ -311,8 +314,8 @@ class BaseSnapExecutor {
311
314
  }
312
315
  })(), this);
313
316
  };
314
- const snapGlobalProxy = (0, utils_2.proxyStreamProvider)(request);
315
- return harden(snapGlobalProxy);
317
+ const snapsProvider = { request };
318
+ return harden(snapsProvider);
316
319
  }
317
320
  /**
318
321
  * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).
@@ -323,6 +326,7 @@ class BaseSnapExecutor {
323
326
  createEIP1193Provider(provider) {
324
327
  const originalRequest = provider.request.bind(provider);
325
328
  const request = async (args) => {
329
+ // As part of the sanitization, we validate that the args are valid JSON.
326
330
  const sanitizedArgs = (0, utils_2.sanitizeRequestArguments)(args);
327
331
  (0, utils_2.assertEthereumOutboundRequest)(sanitizedArgs);
328
332
  return await (0, utils_2.withTeardown)((async () => {
@@ -341,8 +345,8 @@ class BaseSnapExecutor {
341
345
  }
342
346
  })(), this);
343
347
  };
344
- const streamProviderProxy = (0, utils_2.proxyStreamProvider)(request);
345
- return harden(streamProviderProxy);
348
+ const ethereumProvider = { request };
349
+ return harden(ethereumProvider);
346
350
  }
347
351
  /**
348
352
  * Removes the snap with the given name.
@@ -1 +1 @@
1
- {"version":3,"file":"BaseSnapExecutor.cjs","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,+DAAoE;AAEpE,yEAAqE;AACrE,qDAA6E;AAE7E,mDAAmD;AAMnD,uDAO+B;AAC/B,uDAAqD;AAOrD,2CAMyB;AAGzB,4CAAiC;AAEjC,6CAA6D;AAC7D,uDAAgD;AAChD,qDAAuE;AACvE,iDAA6C;AAC7C,uCAOiB;AACjB,iDAKsB;AAYtB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,uBAAU,CAAC,GAAG,CAAC,QAAQ;IAC7B,OAAO,EAAE,6BAA6B;CACvC,CAAC;AAEF,MAAM,cAAc,GAAG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,CAAC,EAAE,CAAC;QACnC,MAAM,sBAAS,CAAC,QAAQ,CACtB,8EAA8E,CAC/E,CAAC;IACJ,CAAC;IAED,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;QAChB,GAAG,YAAY;QACf,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;AACL,CAAC,8BAED,KAAK,oCAAU,EAAa,EAAE,QAAiC;IAC7D,IAAI,CAAC,IAAA,uBAAe,EAAC,QAAQ,CAAC,EAAE,CAAC;QAC/B,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;YAChB,KAAK,EAAE,IAAA,2BAAc,EACnB,sBAAS,CAAC,QAAQ,CAChB,0EAA0E,CAC3E,CACF;YACD,EAAE;YACF,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;QAChB,GAAG,QAAQ;QACX,EAAE;QACF,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;AACL,CAAC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport type { RequestArguments } from '@metamask/providers';\nimport { StreamProvider } from '@metamask/providers/stream-provider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport { validate, is } from '@metamask/superstruct';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, unknown>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const 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: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n\n // If the Snap has no valid exports after this, fail.\n assert(Object.keys(data.exports).length > 0, 'Snap has no valid exports.');\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapGlobalProxy = proxyStreamProvider(request) as SnapsProvider;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"BaseSnapExecutor.cjs","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,+DAAoE;AAEpE,yEAAqE;AACrE,qDAA6E;AAE7E,mDAAmD;AAMnD,uDAO+B;AAC/B,uDAAqD;AAOrD,2CAMyB;AAGzB,4CAAiC;AAEjC,6CAA6D;AAC7D,uDAAgD;AAChD,qDAAuE;AACvE,iDAA6C;AAC7C,uCAMiB;AACjB,iDAKsB;AAYtB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,uBAAU,CAAC,GAAG,CAAC,QAAQ;IAC7B,OAAO,EAAE,6BAA6B;CACvC,CAAC;AAEF,MAAM,cAAc,GAAG,sBAAS;KAC7B,QAAQ,CAAO;IACd,OAAO,EAAE,sBAAsB;CAChC,CAAC;KACD,SAAS,EAAE,CAAC;AAUf;;;;GAIG;AACH,MAAM,6BAA6B,GAAG;IACpC,IAAI,EAAE;QACJ,MAAM,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,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;QAChB,GAAG,YAAY;QACf,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;AACL,CAAC,8BAED,KAAK,oCAAU,EAAa,EAAE,QAAiC;IAC7D,IAAI,CAAC,IAAA,uBAAe,EAAC,QAAQ,CAAC,EAAE,CAAC;QAC/B,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;YAChB,KAAK,EAAE,IAAA,2BAAc,EACnB,sBAAS,CAAC,QAAQ,CAChB,0EAA0E,CAC3E,CACF;YACD,EAAE;YACF,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;QAChB,GAAG,QAAQ;QACX,EAAE;QACF,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;AACL,CAAC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport type { RequestArguments } from '@metamask/providers';\nimport { StreamProvider } from '@metamask/providers/stream-provider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsEthereumProvider, SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport { validate, is } from '@metamask/superstruct';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n shouldPreserveMessage: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n shouldPreserveMessage: false,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, unknown>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const 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: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n\n // If the Snap has no valid exports after this, fail.\n assert(Object.keys(data.exports).length > 0, 'Snap has no valid exports.');\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n // As part of the sanitization, we validate that the args are valid JSON.\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapsProvider = { request } as SnapsProvider;\n\n return harden(snapsProvider);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(\n provider: StreamProvider,\n ): SnapsEthereumProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n // As part of the sanitization, we validate that the args are valid JSON.\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const ethereumProvider = { request };\n\n return harden(ethereumProvider);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"BaseSnapExecutor.d.cts","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;AAQA,OAAO,KAAK,EAEV,WAAW,EACX,qBAAqB,EACtB,8BAA8B;AAU/B,OAAO,KAAK,EACV,mBAAmB,EAGnB,IAAI,EACL,wBAAwB;AAQzB,OAAO,KAAK,EAAE,MAAM,EAAE,wBAAwB;AA4C9C,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,qBAAqB,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;AAEvE,MAAM,MAAM,UAAU,GAAG,CACvB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,WAAW,EACpB,IAAI,EAAE,cAAc,GAAG,SAAS,KAC7B,OAAO,CAAC,IAAI,CAAC,CAAC;AA4BnB,MAAM,MAAM,cAAc,GAAG,CAC3B,YAAY,EAAE,IAAI,CAAC,mBAAmB,EAAE,SAAS,CAAC,KAC/C,OAAO,CAAC,IAAI,CAAC,CAAC;AAEnB,qBAAa,gBAA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AmB;IAoB3B;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;IA+BxB;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAiC7B;;;;OAIG;IACH,OAAO,CAAC,UAAU;IAIlB;;;;;;;;;;OAUG;YACW,oBAAoB;CA2CnC"}
@@ -18,7 +18,7 @@ import { getCommandMethodImplementations } from "./commands.mjs";
18
18
  import { createEndowments } from "./endowments/index.mjs";
19
19
  import { addEventListener, removeEventListener } from "./globalEvents.mjs";
20
20
  import { sortParamKeys } from "./sortParams.mjs";
21
- import { assertEthereumOutboundRequest, assertSnapOutboundRequest, sanitizeRequestArguments, proxyStreamProvider, withTeardown, isValidResponse } from "./utils.mjs";
21
+ import { assertEthereumOutboundRequest, assertSnapOutboundRequest, sanitizeRequestArguments, withTeardown, isValidResponse } from "./utils.mjs";
22
22
  import { ExecuteSnapRequestArgumentsStruct, PingRequestArgumentsStruct, SnapRpcRequestArgumentsStruct, TerminateRequestArgumentsStruct } from "./validation.mjs";
23
23
  const fallbackError = {
24
24
  code: errorCodes.rpc.internal,
@@ -97,6 +97,7 @@ export class BaseSnapExecutor {
97
97
  const serializedError = serializeError(error, {
98
98
  fallbackError: unhandledError,
99
99
  shouldIncludeStack: false,
100
+ shouldPreserveMessage: false,
100
101
  });
101
102
  const errorData = getErrorData(serializedError);
102
103
  __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_notify).call(this, {
@@ -170,6 +171,7 @@ export class BaseSnapExecutor {
170
171
  await __classPrivateFieldGet(this, _BaseSnapExecutor_instances, "m", _BaseSnapExecutor_respond).call(this, id, {
171
172
  error: serializeError(rpcError, {
172
173
  fallbackError,
174
+ shouldPreserveMessage: false,
173
175
  }),
174
176
  });
175
177
  }
@@ -290,6 +292,7 @@ export class BaseSnapExecutor {
290
292
  createSnapGlobal(provider) {
291
293
  const originalRequest = provider.request.bind(provider);
292
294
  const request = async (args) => {
295
+ // As part of the sanitization, we validate that the args are valid JSON.
293
296
  const sanitizedArgs = sanitizeRequestArguments(args);
294
297
  assertSnapOutboundRequest(sanitizedArgs);
295
298
  return await withTeardown((async () => {
@@ -308,8 +311,8 @@ export class BaseSnapExecutor {
308
311
  }
309
312
  })(), this);
310
313
  };
311
- const snapGlobalProxy = proxyStreamProvider(request);
312
- return harden(snapGlobalProxy);
314
+ const snapsProvider = { request };
315
+ return harden(snapsProvider);
313
316
  }
314
317
  /**
315
318
  * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).
@@ -320,6 +323,7 @@ export class BaseSnapExecutor {
320
323
  createEIP1193Provider(provider) {
321
324
  const originalRequest = provider.request.bind(provider);
322
325
  const request = async (args) => {
326
+ // As part of the sanitization, we validate that the args are valid JSON.
323
327
  const sanitizedArgs = sanitizeRequestArguments(args);
324
328
  assertEthereumOutboundRequest(sanitizedArgs);
325
329
  return await withTeardown((async () => {
@@ -338,8 +342,8 @@ export class BaseSnapExecutor {
338
342
  }
339
343
  })(), this);
340
344
  };
341
- const streamProviderProxy = proxyStreamProvider(request);
342
- return harden(streamProviderProxy);
345
+ const ethereumProvider = { request };
346
+ return harden(ethereumProvider);
343
347
  }
344
348
  /**
345
349
  * Removes the snap with the given name.
@@ -1 +1 @@
1
- {"version":3,"file":"BaseSnapExecutor.mjs","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,OAAO,EAAE,uBAAuB,EAAE,kCAAkC;AAEpE,OAAO,EAAE,cAAc,EAAE,4CAA4C;AACrE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,EAAE,6BAA6B;AAE7E,OAAO,EAAE,YAAY,EAAE,4BAA4B;AAMnD,OAAO,EACL,iBAAiB,EACjB,QAAQ,EACR,YAAY,EACZ,gBAAgB,EAChB,WAAW,EACX,OAAO,EACR,8BAA8B;AAC/B,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,8BAA8B;AAOrD,OA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IACtB,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC3C,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE;YACxC,IAAI,KAAK,EAAE,CAAC;gBACV,MAAM,CAAC,KAAK,CAAC,CAAC;gBACd,OAAO;YACT,CAAC;YACD,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,6BAED,KAAK,mCAAS,YAAkD;IAC9D,IAAI,CAAC,eAAe,CAAC,YAAY,CAAC,EAAE,CAAC;QACnC,MAAM,SAAS,CAAC,QAAQ,CACtB,8EAA8E,CAC/E,CAAC;IACJ,CAAC;IAED,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;QAChB,GAAG,YAAY;QACf,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;AACL,CAAC,8BAED,KAAK,oCAAU,EAAa,EAAE,QAAiC;IAC7D,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC/B,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;YAChB,KAAK,EAAE,cAAc,CACnB,SAAS,CAAC,QAAQ,CAChB,0EAA0E,CAC3E,CACF;YACD,EAAE;YACF,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;QAChB,GAAG,QAAQ;QACX,EAAE;QACF,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;AACL,CAAC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport type { RequestArguments } from '@metamask/providers';\nimport { StreamProvider } from '@metamask/providers/stream-provider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport { validate, is } from '@metamask/superstruct';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, unknown>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const 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: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n\n // If the Snap has no valid exports after this, fail.\n assert(Object.keys(data.exports).length > 0, 'Snap has no valid exports.');\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapGlobalProxy = proxyStreamProvider(request) as SnapsProvider;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"BaseSnapExecutor.mjs","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,OAAO,EAAE,uBAAuB,EAAE,kCAAkC;AAEpE,OAAO,EAAE,cAAc,EAAE,4CAA4C;AACrE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,EAAE,6BAA6B;AAE7E,OAA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X,EAAE;QACF,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;AACL,CAAC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport type { RequestArguments } from '@metamask/providers';\nimport { StreamProvider } from '@metamask/providers/stream-provider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsEthereumProvider, SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport { validate, is } from '@metamask/superstruct';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n shouldPreserveMessage: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n shouldPreserveMessage: false,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, unknown>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const 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: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n\n // If the Snap has no valid exports after this, fail.\n assert(Object.keys(data.exports).length > 0, 'Snap has no valid exports.');\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n // As part of the sanitization, we validate that the args are valid JSON.\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapsProvider = { request } as SnapsProvider;\n\n return harden(snapsProvider);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(\n provider: StreamProvider,\n ): SnapsEthereumProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n // As part of the sanitization, we validate that the args are valid JSON.\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const ethereumProvider = { request };\n\n return harden(ethereumProvider);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
@@ -29,6 +29,7 @@ const commonEndowments = [
29
29
  { endowment: Int8Array, name: 'Int8Array' },
30
30
  { endowment: Int16Array, name: 'Int16Array' },
31
31
  { endowment: Int32Array, name: 'Int32Array' },
32
+ { endowment: globalThis.isSecureContext, name: 'isSecureContext' },
32
33
  { endowment: Uint8Array, name: 'Uint8Array' },
33
34
  { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },
34
35
  { endowment: Uint16Array, name: 'Uint16Array' },
@@ -1 +1 @@
1
- {"version":3,"file":"commonEndowmentFactory.cjs","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":";;;;;AACA,sDAAkD;AAClD,4DAAyC;AACzC,0DAA8B;AAC9B,sDAA0B;AAC1B,8DAAkC;AAClC,sDAA0B;AAC1B,4DAAgC;AAChC,oEAAwC;AACxC,oEAAwC;AACxC,4DAAgC;AAkBhC,6BAA6B;AAC7B,MAAM,gBAAgB,GAAmC;IACvD,EAAE,SAAS,EAAE,eAAe,EAAE,IAAI,EAAE,iBAAiB,EAAE;IACvD,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE;IAC7C,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;IACrC,EAAE,SAAS,EAAE,aAAa,EAAE,IAAI,EAAE,eAAe,EAAE;IACnD,EAAE,SAAS,EAAE,cAAc,EAAE,IAAI,EAAE,gBAAgB,EAAE;IACrD,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE;IAC7C,EAAE,SAAS,EAAE,QAAQ,EAAE,IAAI,EAAE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CAAC;oBACxD,CAAC,CAAC,sBAAsB,CAAC,SAAS,CAAC;gBACvC,OAAO;oBACL,CAAC,sBAAsB,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,cAAc,CAAC;iBAC7C,CAAC;YACb,CAAC;SACF,CAAC;QACF,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,OAAO,kBAAkB,CAAC;AAC5B,CAAC,CAAC;AAEF,kBAAe,qBAAqB,CAAC","sourcesContent":["import type { NotifyFunction } from '../BaseSnapExecutor';\nimport { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactoryOptions = {\n snapId?: string;\n notify?: NotifyFunction;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n consoleEndowment,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"]}
1
+ {"version":3,"file":"commonEndowmentFactory.cjs","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":";;;;;AACA,sDAAkD;AAClD,4DAAyC;AACzC,0DAA8B;AAC9B,sDAA0B;AAC1B,8DAAkC;AAClC,sDAA0B;AAC1B,4DAAgC;AAChC,oEAAwC;AACxC,oEAAwC;AACxC,4DAAgC;AAkBhC,6BAA6B;AAC7B,MAAM,gBAAgB,GAAmC;IACvD,EAAE,SAAS,EAAE,eAAe,EAAE,IAAI,EAAE,iBAAiB,EAAE;IACvD,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE;IAC7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BAAO;QACP,qBAAW;QACX,qBAAW;QACX,cAAI;QACJ,iBAAgB;KACjB,CAAC;IAEF,gBAAgB,CAAC,OAAO,CAAC,CAAC,sBAAsB,EAAE,EAAE;QAClD,MAAM,SAAS,GAAG;YAChB,KAAK,EAAE,CAAC,sBAAsB,CAAC,IAAI,CAAU;YAC7C,OAAO,EAAE,GAAG,EAAE;gBACZ,MAAM,cAAc,GAClB,OAAO,sBAAsB,CAAC,SAAS,KAAK,UAAU;oBACtD,sBAAsB,CAAC,IAAI;oBACzB,CAAC,CAAC,sBAAsB,CAAC,SAAS,CAAC,IAAI,CAAC,8BAAe,CAAC;oBACxD,CAAC,CAAC,sBAAsB,CAAC,SAAS,CAAC;gBACvC,OAAO;oBACL,CAAC,sBAAsB,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,cAAc,CAAC;iBAC7C,CAAC;YACb,CAAC;SACF,CAAC;QACF,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,OAAO,kBAAkB,CAAC;AAC5B,CAAC,CAAC;AAEF,kBAAe,qBAAqB,CAAC","sourcesContent":["import type { NotifyFunction } from '../BaseSnapExecutor';\nimport { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactoryOptions = {\n snapId?: string;\n notify?: NotifyFunction;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: globalThis.isSecureContext, name: 'isSecureContext' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n consoleEndowment,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"commonEndowmentFactory.d.cts","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,gCAA4B;AAY1D,MAAM,MAAM,uBAAuB,GAAG;IACpC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,cAAc,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,uBAAuB,KAAK;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;CAC5E,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG;IACzC,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB,CAAC;AA0BF;;;;;;GAMG;AACH,QAAA,MAAM,qBAAqB,QAAO,gBAAgB,EA+BjD,CAAC;AAEF,eAAe,qBAAqB,CAAC"}
1
+ {"version":3,"file":"commonEndowmentFactory.d.cts","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,gCAA4B;AAY1D,MAAM,MAAM,uBAAuB,GAAG;IACpC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,cAAc,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,uBAAuB,KAAK;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;CAC5E,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG;IACzC,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB,CAAC;AA2BF;;;;;;GAMG;AACH,QAAA,MAAM,qBAAqB,QAAO,gBAAgB,EA+BjD,CAAC;AAEF,eAAe,qBAAqB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"commonEndowmentFactory.d.mts","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,gCAA4B;AAY1D,MAAM,MAAM,uBAAuB,GAAG;IACpC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,cAAc,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,uBAAuB,KAAK;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;CAC5E,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG;IACzC,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB,CAAC;AA0BF;;;;;;GAMG;AACH,QAAA,MAAM,qBAAqB,QAAO,gBAAgB,EA+BjD,CAAC;AAEF,eAAe,qBAAqB,CAAC"}
1
+ {"version":3,"file":"commonEndowmentFactory.d.mts","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,gCAA4B;AAY1D,MAAM,MAAM,uBAAuB,GAAG;IACpC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,cAAc,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,uBAAuB,KAAK;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;CAC5E,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG;IACzC,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB,CAAC;AA2BF;;;;;;GAMG;AACH,QAAA,MAAM,qBAAqB,QAAO,gBAAgB,EA+BjD,CAAC;AAEF,eAAe,qBAAqB,CAAC"}
@@ -24,6 +24,7 @@ const commonEndowments = [
24
24
  { endowment: Int8Array, name: 'Int8Array' },
25
25
  { endowment: Int16Array, name: 'Int16Array' },
26
26
  { endowment: Int32Array, name: 'Int32Array' },
27
+ { endowment: globalThis.isSecureContext, name: 'isSecureContext' },
27
28
  { endowment: Uint8Array, name: 'Uint8Array' },
28
29
  { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },
29
30
  { endowment: Uint16Array, name: 'Uint16Array' },
@@ -1 +1 @@
1
- {"version":3,"file":"commonEndowmentFactory.mjs","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,4BAAwB;AAClD,OAAO,gBAAgB,sBAAkB;AACzC,OAAO,MAAM,qBAAiB;AAC9B,OAAO,IAAI,mBAAe;AAC1B,OAAO,QAAQ,uBAAmB;AAClC,OAAO,IAAI,mBAAe;AAC1B,OAAO,OAAO,sBAAkB;AAChC,OAAO,WAAW,0BAAsB;AACxC,OAAO,WAAW,0BAAsB;AACxC,OAAO,OAAO,sBAAkB;AAkBhC,6BAA6B;AAC7B,MAAM,gBAAgB,GAAmC;IACvD,EAAE,SAAS,EAAE,eAAe,EAAE,IAAI,EAAE,iBAAiB,EAAE;IACvD,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IA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IAEF,gBAAgB,CAAC,OAAO,CAAC,CAAC,sBAAsB,EAAE,EAAE;QAClD,MAAM,SAAS,GAAG;YAChB,KAAK,EAAE,CAAC,sBAAsB,CAAC,IAAI,CAAU;YAC7C,OAAO,EAAE,GAAG,EAAE;gBACZ,MAAM,cAAc,GAClB,OAAO,sBAAsB,CAAC,SAAS,KAAK,UAAU;oBACtD,sBAAsB,CAAC,IAAI;oBACzB,CAAC,CAAC,sBAAsB,CAAC,SAAS,CAAC,IAAI,CAAC,eAAe,CAAC;oBACxD,CAAC,CAAC,sBAAsB,CAAC,SAAS,CAAC;gBACvC,OAAO;oBACL,CAAC,sBAAsB,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,cAAc,CAAC;iBAC7C,CAAC;YACb,CAAC;SACF,CAAC;QACF,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,OAAO,kBAAkB,CAAC;AAC5B,CAAC,CAAC;AAEF,eAAe,qBAAqB,CAAC","sourcesContent":["import type { NotifyFunction } from '../BaseSnapExecutor';\nimport { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactoryOptions = {\n snapId?: string;\n notify?: NotifyFunction;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n consoleEndowment,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"]}
1
+ {"version":3,"file":"commonEndowmentFactory.mjs","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,4BAAwB;AAClD,OAAO,gBAAgB,sBAAkB;AACzC,OAAO,MAAM,qBAAiB;AAC9B,OAAO,IAAI,mBAAe;AAC1B,OAAO,QAAQ,uBAAmB;AAClC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,EAAE,iBAAiB,EAAE,IAAI,EAAE,mBAAmB,EAAE;IAC3D,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;IAC/C,EAAE,SAAS,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE;IAC/B,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,aAAa,EAAE;CAChD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,qBAAqB,GAAG,GAAuB,EAAE;IACrD,MAAM,kBAAkB,GAAuB;QAC7C,MAAM;QACN,QAAQ;QACR,IAAI;QACJ,OAAO;QACP,OAAO;QACP,WAAW;QACX,WAAW;QACX,IAAI;QACJ,gBAAgB;KACjB,CAAC;IAEF,gBAAgB,CAAC,OAAO,CAAC,CAAC,sBAAsB,EAAE,EAAE;QAClD,MAAM,SAAS,GAAG;YAChB,KAAK,EAAE,CAAC,sBAAsB,CAAC,IAAI,CAAU;YAC7C,OAAO,EAAE,GAAG,EAAE;gBACZ,MAAM,cAAc,GAClB,OAAO,sBAAsB,CAAC,SAAS,KAAK,UAAU;oBACtD,sBAAsB,CAAC,IAAI;oBACzB,CAAC,CAAC,sBAAsB,CAAC,SAAS,CAAC,IAAI,CAAC,eAAe,CAAC;oBACxD,CAAC,CAAC,sBAAsB,CAAC,SAAS,CAAC;gBACvC,OAAO;oBACL,CAAC,sBAAsB,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,cAAc,CAAC;iBAC7C,CAAC;YACb,CAAC;SACF,CAAC;QACF,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;IAEH,OAAO,kBAAkB,CAAC;AAC5B,CAAC,CAAC;AAEF,eAAe,qBAAqB,CAAC","sourcesContent":["import type { NotifyFunction } from '../BaseSnapExecutor';\nimport { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactoryOptions = {\n snapId?: string;\n notify?: NotifyFunction;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: globalThis.isSecureContext, name: 'isSecureContext' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n consoleEndowment,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":";;;;;;AACA,qDAAiD;AAEjD,uDAAmD;AACnD,2CAA8C;AAG9C,sDAAkD;AAElD,0FAA6D;AAe7D;;GAEG;AACH,MAAM,oBAAoB,GAAG,IAAA,gCAAqB,GAAE,CAAC;AAErD;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE;IAC5E,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC7B,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC,CAAC,CAAC;IACH,OAAO,SAAS,CAAC;AACnB,CAAC,EAAE,IAAI,GAAG,EAAyE,CAAC,CAAC;AAErF;;;;;;;;;;;;;;GAcG;AACH,SAAgB,gBAAgB,CAAC,EAC/B,IAAI,EACJ,QAAQ,EACR,MAAM,EACN,UAAU,EACV,MAAM,GAOP;IACC,MAAM,oBAAoB,GAA4B,EAAE,CAAC;IAEzD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAI9B,CAAC,EAAE,aAAa,EAAE,SAAS,EAAE,EAAE,aAAa,EAAE,EAAE;QAC9C,oEAAoE;QACpE,IAAI,kBAAkB,CAAC,GAAG,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ACd,CACF,CAAC;IAEF,MAAM,QAAQ,GAAG,KAAK,IAAI,EAAE;QAC1B,MAAM,OAAO,CAAC,GAAG,CACf,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,gBAAgB,EAAE,EAAE,CAAC,gBAAgB,EAAE,CAAC,CAC/D,CAAC;IACJ,CAAC,CAAC;IACF,OAAO,EAAE,UAAU,EAAE,MAAM,CAAC,aAAa,EAAE,QAAQ,EAAE,CAAC;AACxD,CAAC;AAzED,4CAyEC","sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport type { NotifyFunction } from '../BaseSnapExecutor';\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param options - An options bag.\n * @param options.snap - The Snaps global API object.\n * @param options.ethereum - The Snap's EIP-1193 provider object.\n * @param options.snapId - The id of the snap that will use the created endowments.\n * @param options.endowments - The list of endowments to provide to the snap.\n * @param options.notify - A reference to the notify function of the snap executor.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments({\n snap,\n ethereum,\n snapId,\n endowments,\n notify,\n}: {\n snap: SnapsProvider;\n ethereum: StreamProvider;\n snapId: string;\n endowments: string[];\n notify: NotifyFunction;\n}): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId, notify });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw rpcErrors.internal(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"]}
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":";;;;;;AAAA,qDAAiD;AAEjD,uDAAmD;AACnD,2CAA8C;AAG9C,sDAAkD;AAElD,0FAA6D;AAe7D;;GAEG;AACH,MAAM,oBAAoB,GAAG,IAAA,gCAAqB,GAAE,CAAC;AAErD;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE;IAC5E,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC7B,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC,CAAC,CAAC;IACH,OAAO,SAAS,CAAC;AACnB,CAAC,EAAE,IAAI,GAAG,EAAyE,CAAC,CAAC;AAErF;;;;;;;;;;;;;;GAcG;AACH,SAAgB,gBAAgB,CAAC,EAC/B,IAAI,EACJ,QAAQ,EACR,MAAM,EACN,UAAU,EACV,MAAM,GAOP;IACC,MAAM,oBAAoB,GAA4B,EAAE,CAAC;IAEzD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAI9B,CAAC,EAAE,aAAa,EAAE,SAAS,EAAE,EAAE,aAAa,EAAE,EAAE;QAC9C,oEAAoE;QACpE,IAAI,kBAAkB,CAAC,GAAG,CAAC,aAAa,CAAC,EAA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AAM,QAAQ,GAAG,KAAK,IAAI,EAAE;QAC1B,MAAM,OAAO,CAAC,GAAG,CACf,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,gBAAgB,EAAE,EAAE,CAAC,gBAAgB,EAAE,CAAC,CAC/D,CAAC;IACJ,CAAC,CAAC;IACF,OAAO,EAAE,UAAU,EAAE,MAAM,CAAC,aAAa,EAAE,QAAQ,EAAE,CAAC;AACxD,CAAC;AAzED,4CAyEC","sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsEthereumProvider, SnapsProvider } from '@metamask/snaps-sdk';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport type { NotifyFunction } from '../BaseSnapExecutor';\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param options - An options bag.\n * @param options.snap - The Snaps global API object.\n * @param options.ethereum - The Snap's EIP-1193 provider object.\n * @param options.snapId - The id of the snap that will use the created endowments.\n * @param options.endowments - The list of endowments to provide to the snap.\n * @param options.notify - A reference to the notify function of the snap executor.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments({\n snap,\n ethereum,\n snapId,\n endowments,\n notify,\n}: {\n snap: SnapsProvider;\n ethereum: SnapsEthereumProvider;\n snapId: string;\n endowments: string[];\n notify: NotifyFunction;\n}): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId, notify });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw rpcErrors.internal(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"]}
@@ -1,5 +1,4 @@
1
- import type { StreamProvider } from "@metamask/providers";
2
- import type { SnapsProvider } from "@metamask/snaps-sdk";
1
+ import type { SnapsEthereumProvider, SnapsProvider } from "@metamask/snaps-sdk";
3
2
  import type { NotifyFunction } from "../BaseSnapExecutor.cjs";
4
3
  /**
5
4
  * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`
@@ -18,7 +17,7 @@ import type { NotifyFunction } from "../BaseSnapExecutor.cjs";
18
17
  */
19
18
  export declare function createEndowments({ snap, ethereum, snapId, endowments, notify, }: {
20
19
  snap: SnapsProvider;
21
- ethereum: StreamProvider;
20
+ ethereum: SnapsEthereumProvider;
22
21
  snapId: string;
23
22
  endowments: string[];
24
23
  notify: NotifyFunction;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,4BAA4B;AAE1D,OAAO,KAAK,EAAE,aAAa,EAAE,4BAA4B;AAIzD,OAAO,KAAK,EAAE,cAAc,EAAE,gCAA4B;AAmC1D;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAAC,EAC/B,IAAI,EACJ,QAAQ,EACR,MAAM,EACN,UAAU,EACV,MAAM,GACP,EAAE;IACD,IAAI,EAAE,aAAa,CAAC;IACpB,QAAQ,EAAE,cAAc,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,MAAM,EAAE,cAAc,CAAC;CACxB,GAAG;IAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CA6DzE"}
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAE,aAAa,EAAE,4BAA4B;AAIhF,OAAO,KAAK,EAAE,cAAc,EAAE,gCAA4B;AAmC1D;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAAC,EAC/B,IAAI,EACJ,QAAQ,EACR,MAAM,EACN,UAAU,EACV,MAAM,GACP,EAAE;IACD,IAAI,EAAE,aAAa,CAAC;IACpB,QAAQ,EAAE,qBAAqB,CAAC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,MAAM,EAAE,cAAc,CAAC;CACxB,GAAG;IAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CA6DzE"}