@metamask/snaps-execution-environments 11.0.1 → 11.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -1
- package/dist/common/BaseSnapExecutor.cjs.map +1 -1
- package/dist/common/BaseSnapExecutor.d.cts +2 -2
- package/dist/common/BaseSnapExecutor.d.cts.map +1 -1
- package/dist/common/BaseSnapExecutor.d.mts +2 -2
- package/dist/common/BaseSnapExecutor.d.mts.map +1 -1
- package/dist/common/BaseSnapExecutor.mjs.map +1 -1
- package/dist/common/endowments/commonEndowmentFactory.cjs.map +1 -1
- package/dist/common/endowments/commonEndowmentFactory.d.cts +44 -5
- package/dist/common/endowments/commonEndowmentFactory.d.cts.map +1 -1
- package/dist/common/endowments/commonEndowmentFactory.d.mts +44 -5
- package/dist/common/endowments/commonEndowmentFactory.d.mts.map +1 -1
- package/dist/common/endowments/commonEndowmentFactory.mjs.map +1 -1
- package/dist/common/endowments/console.cjs +13 -12
- package/dist/common/endowments/console.cjs.map +1 -1
- package/dist/common/endowments/console.d.cts +8 -7
- package/dist/common/endowments/console.d.cts.map +1 -1
- package/dist/common/endowments/console.d.mts +8 -7
- package/dist/common/endowments/console.d.mts.map +1 -1
- package/dist/common/endowments/console.mjs +13 -12
- package/dist/common/endowments/console.mjs.map +1 -1
- package/dist/common/endowments/index.cjs +1 -1
- package/dist/common/endowments/index.cjs.map +1 -1
- package/dist/common/endowments/index.d.cts +1 -1
- package/dist/common/endowments/index.d.cts.map +1 -1
- package/dist/common/endowments/index.d.mts +1 -1
- package/dist/common/endowments/index.d.mts.map +1 -1
- package/dist/common/endowments/index.mjs +1 -1
- package/dist/common/endowments/index.mjs.map +1 -1
- package/dist/common/endowments/network.cjs +5 -4
- package/dist/common/endowments/network.cjs.map +1 -1
- package/dist/common/endowments/network.d.cts.map +1 -1
- package/dist/common/endowments/network.d.mts.map +1 -1
- package/dist/common/endowments/network.mjs +5 -4
- package/dist/common/endowments/network.mjs.map +1 -1
- package/dist/common/validation.d.cts +17 -17
- package/dist/common/validation.d.mts +17 -17
- package/dist/endowments.cjs +61 -0
- package/dist/endowments.cjs.map +1 -0
- package/dist/endowments.d.cts +59 -0
- package/dist/endowments.d.cts.map +1 -0
- package/dist/endowments.d.mts +59 -0
- package/dist/endowments.d.mts.map +1 -0
- package/dist/endowments.mjs +47 -0
- package/dist/endowments.mjs.map +1 -0
- package/dist/webpack/iframe/bundle.js +1 -1
- package/dist/webpack/node-process/bundle.js +417 -270
- package/dist/webpack/node-process/bundle.js.LICENSE.txt +416 -269
- package/dist/webpack/node-thread/bundle.js +417 -270
- package/dist/webpack/node-thread/bundle.js.LICENSE.txt +416 -269
- package/dist/webpack/webview/index.html +1 -1
- package/package.json +18 -8
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [11.1.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Export endowment factories via `@metamask/snaps-execution-environments/endowments` ([#3957](https://github.com/MetaMask/snaps/pull/3957))
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- Bump `@metamask/utils` from `11.10.0` to `11.11.0` ([#3935](https://github.com/MetaMask/snaps/pull/3935))
|
|
19
|
+
- Bump `@metamask/json-rpc-engine` from `10.2.3` to `10.2.4` ([#3925](https://github.com/MetaMask/snaps/pull/3925))
|
|
20
|
+
- Bump `@lavamoat/webpack` from `2.0.0` to `2.1.1` ([#3945](https://github.com/MetaMask/snaps/pull/3945))
|
|
21
|
+
|
|
22
|
+
## [11.0.2]
|
|
23
|
+
|
|
24
|
+
### Changed
|
|
25
|
+
|
|
26
|
+
- Bump `lavamoat` from `10.1.1` to `11.0.0` ([#3908](https://github.com/MetaMask/snaps/pull/3908))
|
|
27
|
+
- Bump `@lavamoat/webpack` from `1.5.8` to `2.0.0` ([#3909](https://github.com/MetaMask/snaps/pull/3909))
|
|
28
|
+
|
|
10
29
|
## [11.0.1]
|
|
11
30
|
|
|
12
31
|
### Changed
|
|
@@ -610,7 +629,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
610
629
|
- The version of the package no longer needs to match the version of all other
|
|
611
630
|
MetaMask Snaps packages.
|
|
612
631
|
|
|
613
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@11.0
|
|
632
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@11.1.0...HEAD
|
|
633
|
+
[11.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@11.0.2...@metamask/snaps-execution-environments@11.1.0
|
|
634
|
+
[11.0.2]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@11.0.1...@metamask/snaps-execution-environments@11.0.2
|
|
614
635
|
[11.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@11.0.0...@metamask/snaps-execution-environments@11.0.1
|
|
615
636
|
[11.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@10.4.1...@metamask/snaps-execution-environments@11.0.0
|
|
616
637
|
[10.4.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-execution-environments@10.4.0...@metamask/snaps-execution-environments@10.4.1
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseSnapExecutor.cjs","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,+DAAoE;AACpE,kFAAyD;AAEzD,qDAA6E;AAE7E,mDAAmD;AAMnD,uDAO+B;AAC/B,uDAA2C;AAO3C,2CAOyB;AAEzB,qDAA2C;AAE3C,6CAAsE;AACtE,uDAAgD;AAChD,qDAAuE;AACvE,qDAA8C;AA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,CAAC,CAAC,CAAC;QACvD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,8BAAgB,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;gBACvC,IAAI,CAAC,YAAY,CAAC,YAAY,IAAI,CAAC,CAAC;gBACpC,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;YAC5B,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA7fD,4CA6fC","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 ObjectMultiplex from '@metamask/object-multiplex';\nimport type { RequestArguments, StreamProvider } from '@metamask/providers';\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 { 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 createDeferredPromise,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\n\nimport { assertCommandParams, getHandlerArguments } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { SnapProvider } from './SnapProvider';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n withTeardown,\n isValidResponse,\n isMultichainRequest,\n assertMultichainOutboundRequest,\n} from './utils';\nimport type {\n ExecuteSnapRequestArguments,\n SnapRpcRequestArguments,\n} from './validation';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n} from './validation';\nimport { log } from '../logging';\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\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n readonly #snapData: Map<string, SnapData>;\n\n readonly #commandStream: Duplex;\n\n readonly #rpcStream: Duplex;\n\n #snapErrorHandler?: (event: ErrorEvent) => void;\n\n #snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n readonly #teardownRef = { 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 /* istanbul ignore next 2 */\n this.#onCommandRequest(data).catch((error) => {\n logError(error);\n });\n });\n this.#rpcStream = rpcStream;\n }\n\n #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 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.#respond((message as Pick<JsonRpcRequest, 'id'>).id, {\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\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 try {\n const result = await this.#handleCommand(method, params);\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 /**\n * Handle an incoming JSON-RPC command request.\n *\n * @param method - The JSON-RPC method name.\n * @param params - The optional JSON-RPC parameters.\n * @returns The response based on the JSON-RPC method invoked.\n * @throws If the passed method is not available.\n */\n async #handleCommand(method: string, params?: Json) {\n switch (method) {\n case 'ping':\n return 'OK';\n\n case 'terminate': {\n this.#handleTerminate();\n return 'OK';\n }\n\n case 'executeSnap': {\n assertCommandParams(method, params, ExecuteSnapRequestArgumentsStruct);\n await this.#startSnap(params);\n return 'OK';\n }\n\n case 'snapRpc': {\n assertCommandParams(method, params, SnapRpcRequestArgumentsStruct);\n return await this.#invokeSnap(params);\n }\n\n default:\n throw rpcErrors.methodNotFound({\n data: {\n method,\n },\n });\n }\n }\n\n /**\n * Invoke an exported handler on a running Snap.\n *\n * @param options - An options bag.\n * @param options.snapId - The Snap ID.\n * @param options.handler - The handler to invoke.\n * @param options.origin - The origin invoking the handler.\n * @param options.request - The JSON-RPC request to invoke the handler with.\n * @returns The result of invoking the handler on the Snap.\n */\n async #invokeSnap({\n snapId,\n handler: handlerType,\n origin,\n request,\n }: SnapRpcRequestArguments) {\n const args = getHandlerArguments(origin, handlerType, request);\n\n const data = this.#snapData.get(snapId);\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 \"${snapId}\".`,\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 const result = await this.#executeInSnapContext(snapId, async () =>\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 || result === null) {\n return 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\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, Json>) {\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 params - The parameters.\n * @param params.snapId - The id of the snap.\n * @param params.sourceCode - The source code of the snap, in IIFE format.\n * @param params.endowments - An array of the names of the endowments.\n */\n async #startSnap({\n snapId,\n sourceCode,\n endowments: endowmentKeys,\n }: ExecuteSnapRequestArguments): 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 multiplex = new ObjectMultiplex();\n pipeline(this.#rpcStream, multiplex, this.#rpcStream, (error) => {\n if (error && !error.message?.match('Premature close')) {\n logError(`Provider stream failure.`, error);\n }\n });\n\n const provider = new SnapProvider(\n multiplex.createStream('metamask-provider'),\n {\n rpcMiddleware: [createIdRemapMiddleware()],\n },\n );\n\n provider.initializeSync();\n\n const multichainProvider = new SnapProvider(\n multiplex.createStream('metamask-multichain-provider'),\n {\n rpcMiddleware: [createIdRemapMiddleware()],\n },\n );\n\n multichainProvider.initializeSync();\n\n const snap = this.#createSnapGlobal(provider, multichainProvider);\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: endowmentKeys,\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, async () => {\n compartment.evaluate(sourceCode);\n await 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 #handleTerminate() {\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 async #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 // If the module is async, we must await the exports.\n const snapExports = await snapModule.exports;\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapExports[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 the EIP-1193 client stream.\n * @param multichainProvider - A StreamProvider connected to the CAIP-27 client stream.\n * @returns The snap provider object.\n */\n #createSnapGlobal(\n provider: StreamProvider,\n multichainProvider: StreamProvider,\n ): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n const originalMultichainRequest =\n multichainProvider.request.bind(multichainProvider);\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\n if (isMultichainRequest(sanitizedArgs)) {\n assertMultichainOutboundRequest(sanitizedArgs);\n return await withTeardown(\n originalMultichainRequest(sanitizedArgs),\n this.#teardownRef,\n );\n }\n\n return await withTeardown(\n originalRequest(sanitizedArgs),\n this.#teardownRef,\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 #createEIP1193Provider(provider: StreamProvider): 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 originalRequest(sanitizedArgs),\n this.#teardownRef,\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 #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 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 const { promise: stopPromise, reject } = createDeferredPromise<Result>();\n\n const stop = () =>\n reject(\n rpcErrors.internal(\n `The Snap \"${snapId}\" has been terminated during execution.`,\n ),\n );\n\n const evaluationData = { 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.#teardownRef.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;AACpE,kFAAyD;AAEzD,qDAA6E;AAE7E,mDAAmD;AAMnD,uDAO+B;AAC/B,uDAA2C;AAO3C,2CAOyB;AAEzB,qDAA2C;AAE3C,6CAAsE;AACtE,uDAAgD;AAChD,qDAAuE;AACvE,qDAA8C;AAC9C,uCAQiB;AAKjB,iDAGsB;AACtB,4CAAiC;AAYjC,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;AAYf,MAAa,gBAAgB;IAClB,SAAS,CAAwB;IAEjC,cAAc,CAAS;IAEvB,UAAU,CAAS;IAE5B,iBAAiB,CAA+B;I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CAAC;QACH,CAAC;IACH,CAAC;CACF;AA7fD,4CA6fC","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 ObjectMultiplex from '@metamask/object-multiplex';\nimport type { RequestArguments, StreamProvider } from '@metamask/providers';\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 { 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 createDeferredPromise,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\n\nimport { assertCommandParams, getHandlerArguments } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { SnapProvider } from './SnapProvider';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n withTeardown,\n isValidResponse,\n isMultichainRequest,\n assertMultichainOutboundRequest,\n} from './utils';\nimport type {\n ExecuteSnapRequestArguments,\n SnapRpcRequestArguments,\n} from './validation';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n} from './validation';\nimport { log } from '../logging';\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\nexport type { NotifyFunction } from './endowments/commonEndowmentFactory';\n\nexport class BaseSnapExecutor {\n readonly #snapData: Map<string, SnapData>;\n\n readonly #commandStream: Duplex;\n\n readonly #rpcStream: Duplex;\n\n #snapErrorHandler?: (event: ErrorEvent) => void;\n\n #snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n readonly #teardownRef = { 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 /* istanbul ignore next 2 */\n this.#onCommandRequest(data).catch((error) => {\n logError(error);\n });\n });\n this.#rpcStream = rpcStream;\n }\n\n #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 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.#respond((message as Pick<JsonRpcRequest, 'id'>).id, {\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\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 try {\n const result = await this.#handleCommand(method, params);\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 /**\n * Handle an incoming JSON-RPC command request.\n *\n * @param method - The JSON-RPC method name.\n * @param params - The optional JSON-RPC parameters.\n * @returns The response based on the JSON-RPC method invoked.\n * @throws If the passed method is not available.\n */\n async #handleCommand(method: string, params?: Json) {\n switch (method) {\n case 'ping':\n return 'OK';\n\n case 'terminate': {\n this.#handleTerminate();\n return 'OK';\n }\n\n case 'executeSnap': {\n assertCommandParams(method, params, ExecuteSnapRequestArgumentsStruct);\n await this.#startSnap(params);\n return 'OK';\n }\n\n case 'snapRpc': {\n assertCommandParams(method, params, SnapRpcRequestArgumentsStruct);\n return await this.#invokeSnap(params);\n }\n\n default:\n throw rpcErrors.methodNotFound({\n data: {\n method,\n },\n });\n }\n }\n\n /**\n * Invoke an exported handler on a running Snap.\n *\n * @param options - An options bag.\n * @param options.snapId - The Snap ID.\n * @param options.handler - The handler to invoke.\n * @param options.origin - The origin invoking the handler.\n * @param options.request - The JSON-RPC request to invoke the handler with.\n * @returns The result of invoking the handler on the Snap.\n */\n async #invokeSnap({\n snapId,\n handler: handlerType,\n origin,\n request,\n }: SnapRpcRequestArguments) {\n const args = getHandlerArguments(origin, handlerType, request);\n\n const data = this.#snapData.get(snapId);\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 \"${snapId}\".`,\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 const result = await this.#executeInSnapContext(snapId, async () =>\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 || result === null) {\n return 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\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, Json>) {\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 params - The parameters.\n * @param params.snapId - The id of the snap.\n * @param params.sourceCode - The source code of the snap, in IIFE format.\n * @param params.endowments - An array of the names of the endowments.\n */\n async #startSnap({\n snapId,\n sourceCode,\n endowments: endowmentKeys,\n }: ExecuteSnapRequestArguments): 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 multiplex = new ObjectMultiplex();\n pipeline(this.#rpcStream, multiplex, this.#rpcStream, (error) => {\n if (error && !error.message?.match('Premature close')) {\n logError(`Provider stream failure.`, error);\n }\n });\n\n const provider = new SnapProvider(\n multiplex.createStream('metamask-provider'),\n {\n rpcMiddleware: [createIdRemapMiddleware()],\n },\n );\n\n provider.initializeSync();\n\n const multichainProvider = new SnapProvider(\n multiplex.createStream('metamask-multichain-provider'),\n {\n rpcMiddleware: [createIdRemapMiddleware()],\n },\n );\n\n multichainProvider.initializeSync();\n\n const snap = this.#createSnapGlobal(provider, multichainProvider);\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: endowmentKeys,\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, async () => {\n compartment.evaluate(sourceCode);\n await 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 #handleTerminate() {\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 async #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 // If the module is async, we must await the exports.\n const snapExports = await snapModule.exports;\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapExports[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 the EIP-1193 client stream.\n * @param multichainProvider - A StreamProvider connected to the CAIP-27 client stream.\n * @returns The snap provider object.\n */\n #createSnapGlobal(\n provider: StreamProvider,\n multichainProvider: StreamProvider,\n ): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n const originalMultichainRequest =\n multichainProvider.request.bind(multichainProvider);\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\n if (isMultichainRequest(sanitizedArgs)) {\n assertMultichainOutboundRequest(sanitizedArgs);\n return await withTeardown(\n originalMultichainRequest(sanitizedArgs),\n this.#teardownRef,\n );\n }\n\n return await withTeardown(\n originalRequest(sanitizedArgs),\n this.#teardownRef,\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 #createEIP1193Provider(provider: StreamProvider): 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 originalRequest(sanitizedArgs),\n this.#teardownRef,\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 #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 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 const { promise: stopPromise, reject } = createDeferredPromise<Result>();\n\n const stop = () =>\n reject(\n rpcErrors.internal(\n `The Snap \"${snapId}\" has been terminated during execution.`,\n ),\n );\n\n const evaluationData = { 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.#teardownRef.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
2
|
/// <reference types="src/types/vendor/readable-stream" />
|
|
3
3
|
import type { HandlerType, SnapExportsParameters } from "@metamask/snaps-utils";
|
|
4
|
-
import type {
|
|
4
|
+
import type { Json } from "@metamask/utils";
|
|
5
5
|
import type { Duplex } from "readable-stream";
|
|
6
6
|
export type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;
|
|
7
7
|
export type InvokeSnap = (target: string, handler: HandlerType, args: InvokeSnapArgs | undefined) => Promise<Json>;
|
|
8
|
-
export type NotifyFunction
|
|
8
|
+
export type { NotifyFunction } from "./endowments/commonEndowmentFactory.cjs";
|
|
9
9
|
export declare class BaseSnapExecutor {
|
|
10
10
|
#private;
|
|
11
11
|
protected constructor(commandStream: Duplex, rpcStream: Duplex);
|
|
@@ -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,
|
|
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,EAIV,IAAI,EACL,wBAAwB;AASzB,OAAO,KAAK,EAAE,MAAM,EAAE,wBAAwB;AA+C9C,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;AAEnB,YAAY,EAAE,cAAc,EAAE,gDAA4C;AAE1E,qBAAa,gBAAgB;;IAa3B,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;CAgf/D"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
2
|
/// <reference types="src/types/vendor/readable-stream" />
|
|
3
3
|
import type { HandlerType, SnapExportsParameters } from "@metamask/snaps-utils";
|
|
4
|
-
import type {
|
|
4
|
+
import type { Json } from "@metamask/utils";
|
|
5
5
|
import type { Duplex } from "readable-stream";
|
|
6
6
|
export type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;
|
|
7
7
|
export type InvokeSnap = (target: string, handler: HandlerType, args: InvokeSnapArgs | undefined) => Promise<Json>;
|
|
8
|
-
export type NotifyFunction
|
|
8
|
+
export type { NotifyFunction } from "./endowments/commonEndowmentFactory.mjs";
|
|
9
9
|
export declare class BaseSnapExecutor {
|
|
10
10
|
#private;
|
|
11
11
|
protected constructor(commandStream: Duplex, rpcStream: Duplex);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseSnapExecutor.d.mts","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;AAQA,OAAO,KAAK,EAEV,WAAW,EACX,qBAAqB,EACtB,8BAA8B;AAU/B,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"BaseSnapExecutor.d.mts","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;AAQA,OAAO,KAAK,EAEV,WAAW,EACX,qBAAqB,EACtB,8BAA8B;AAU/B,OAAO,KAAK,EAIV,IAAI,EACL,wBAAwB;AASzB,OAAO,KAAK,EAAE,MAAM,EAAE,wBA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C,kBAAkB,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;gBACvC,IAAI,CAAC,YAAY,CAAC,YAAY,IAAI,CAAC,CAAC;gBACpC,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;YAC5B,CAAC;QACH,CAAC;IACH,CAAC;CACF","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 ObjectMultiplex from '@metamask/object-multiplex';\nimport type { RequestArguments, StreamProvider } from '@metamask/providers';\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 { 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 createDeferredPromise,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\n\nimport { assertCommandParams, getHandlerArguments } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { SnapProvider } from './SnapProvider';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n withTeardown,\n isValidResponse,\n isMultichainRequest,\n assertMultichainOutboundRequest,\n} from './utils';\nimport type {\n ExecuteSnapRequestArguments,\n SnapRpcRequestArguments,\n} from './validation';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n} from './validation';\nimport { log } from '../logging';\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\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n readonly #snapData: Map<string, SnapData>;\n\n readonly #commandStream: Duplex;\n\n readonly #rpcStream: Duplex;\n\n #snapErrorHandler?: (event: ErrorEvent) => void;\n\n #snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n readonly #teardownRef = { 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 /* istanbul ignore next 2 */\n this.#onCommandRequest(data).catch((error) => {\n logError(error);\n });\n });\n this.#rpcStream = rpcStream;\n }\n\n #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 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.#respond((message as Pick<JsonRpcRequest, 'id'>).id, {\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\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 try {\n const result = await this.#handleCommand(method, params);\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 /**\n * Handle an incoming JSON-RPC command request.\n *\n * @param method - The JSON-RPC method name.\n * @param params - The optional JSON-RPC parameters.\n * @returns The response based on the JSON-RPC method invoked.\n * @throws If the passed method is not available.\n */\n async #handleCommand(method: string, params?: Json) {\n switch (method) {\n case 'ping':\n return 'OK';\n\n case 'terminate': {\n this.#handleTerminate();\n return 'OK';\n }\n\n case 'executeSnap': {\n assertCommandParams(method, params, ExecuteSnapRequestArgumentsStruct);\n await this.#startSnap(params);\n return 'OK';\n }\n\n case 'snapRpc': {\n assertCommandParams(method, params, SnapRpcRequestArgumentsStruct);\n return await this.#invokeSnap(params);\n }\n\n default:\n throw rpcErrors.methodNotFound({\n data: {\n method,\n },\n });\n }\n }\n\n /**\n * Invoke an exported handler on a running Snap.\n *\n * @param options - An options bag.\n * @param options.snapId - The Snap ID.\n * @param options.handler - The handler to invoke.\n * @param options.origin - The origin invoking the handler.\n * @param options.request - The JSON-RPC request to invoke the handler with.\n * @returns The result of invoking the handler on the Snap.\n */\n async #invokeSnap({\n snapId,\n handler: handlerType,\n origin,\n request,\n }: SnapRpcRequestArguments) {\n const args = getHandlerArguments(origin, handlerType, request);\n\n const data = this.#snapData.get(snapId);\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 \"${snapId}\".`,\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 const result = await this.#executeInSnapContext(snapId, async () =>\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 || result === null) {\n return 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\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, Json>) {\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 params - The parameters.\n * @param params.snapId - The id of the snap.\n * @param params.sourceCode - The source code of the snap, in IIFE format.\n * @param params.endowments - An array of the names of the endowments.\n */\n async #startSnap({\n snapId,\n sourceCode,\n endowments: endowmentKeys,\n }: ExecuteSnapRequestArguments): 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 multiplex = new ObjectMultiplex();\n pipeline(this.#rpcStream, multiplex, this.#rpcStream, (error) => {\n if (error && !error.message?.match('Premature close')) {\n logError(`Provider stream failure.`, error);\n }\n });\n\n const provider = new SnapProvider(\n multiplex.createStream('metamask-provider'),\n {\n rpcMiddleware: [createIdRemapMiddleware()],\n },\n );\n\n provider.initializeSync();\n\n const multichainProvider = new SnapProvider(\n multiplex.createStream('metamask-multichain-provider'),\n {\n rpcMiddleware: [createIdRemapMiddleware()],\n },\n );\n\n multichainProvider.initializeSync();\n\n const snap = this.#createSnapGlobal(provider, multichainProvider);\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: endowmentKeys,\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, async () => {\n compartment.evaluate(sourceCode);\n await 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 #handleTerminate() {\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 async #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 // If the module is async, we must await the exports.\n const snapExports = await snapModule.exports;\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapExports[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 the EIP-1193 client stream.\n * @param multichainProvider - A StreamProvider connected to the CAIP-27 client stream.\n * @returns The snap provider object.\n */\n #createSnapGlobal(\n provider: StreamProvider,\n multichainProvider: StreamProvider,\n ): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n const originalMultichainRequest =\n multichainProvider.request.bind(multichainProvider);\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\n if (isMultichainRequest(sanitizedArgs)) {\n assertMultichainOutboundRequest(sanitizedArgs);\n return await withTeardown(\n originalMultichainRequest(sanitizedArgs),\n this.#teardownRef,\n );\n }\n\n return await withTeardown(\n originalRequest(sanitizedArgs),\n this.#teardownRef,\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 #createEIP1193Provider(provider: StreamProvider): 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 originalRequest(sanitizedArgs),\n this.#teardownRef,\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 #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 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 const { promise: stopPromise, reject } = createDeferredPromise<Result>();\n\n const stop = () =>\n reject(\n rpcErrors.internal(\n `The Snap \"${snapId}\" has been terminated during execution.`,\n ),\n );\n\n const evaluationData = { 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.#teardownRef.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;AACpE,OAAO,gBAAe,mCAAmC;;AAEzD,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,EAAE,EAAE,8BAA8B;AAO3C,OAAO,EACL,MAAM,EACN,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,eAAe,EACf,qBAAqB,EACtB,wBAAwB;AAEzB,OAAO,EAAE,QAAQ,EAAE,wBAAwB;AAE3C,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,uBAAmB;AACtE,OAAO,EAAE,gBAAgB,EAAE,+BAAqB;AAChD,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,2BAAuB;AACvE,OAAO,EAAE,YAAY,EAAE,2BAAuB;AAC9C,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,EACzB,wBAAwB,EACxB,YAAY,EACZ,eAA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Ac,CAAC,CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;gBACvC,IAAI,CAAC,YAAY,CAAC,YAAY,IAAI,CAAC,CAAC;gBACpC,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;YAC5B,CAAC;QACH,CAAC;IACH,CAAC;CACF","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 ObjectMultiplex from '@metamask/object-multiplex';\nimport type { RequestArguments, StreamProvider } from '@metamask/providers';\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 { 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 createDeferredPromise,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\n\nimport { assertCommandParams, getHandlerArguments } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { SnapProvider } from './SnapProvider';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n withTeardown,\n isValidResponse,\n isMultichainRequest,\n assertMultichainOutboundRequest,\n} from './utils';\nimport type {\n ExecuteSnapRequestArguments,\n SnapRpcRequestArguments,\n} from './validation';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n} from './validation';\nimport { log } from '../logging';\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\nexport type { NotifyFunction } from './endowments/commonEndowmentFactory';\n\nexport class BaseSnapExecutor {\n readonly #snapData: Map<string, SnapData>;\n\n readonly #commandStream: Duplex;\n\n readonly #rpcStream: Duplex;\n\n #snapErrorHandler?: (event: ErrorEvent) => void;\n\n #snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n readonly #teardownRef = { 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 /* istanbul ignore next 2 */\n this.#onCommandRequest(data).catch((error) => {\n logError(error);\n });\n });\n this.#rpcStream = rpcStream;\n }\n\n #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 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.#respond((message as Pick<JsonRpcRequest, 'id'>).id, {\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\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 try {\n const result = await this.#handleCommand(method, params);\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 /**\n * Handle an incoming JSON-RPC command request.\n *\n * @param method - The JSON-RPC method name.\n * @param params - The optional JSON-RPC parameters.\n * @returns The response based on the JSON-RPC method invoked.\n * @throws If the passed method is not available.\n */\n async #handleCommand(method: string, params?: Json) {\n switch (method) {\n case 'ping':\n return 'OK';\n\n case 'terminate': {\n this.#handleTerminate();\n return 'OK';\n }\n\n case 'executeSnap': {\n assertCommandParams(method, params, ExecuteSnapRequestArgumentsStruct);\n await this.#startSnap(params);\n return 'OK';\n }\n\n case 'snapRpc': {\n assertCommandParams(method, params, SnapRpcRequestArgumentsStruct);\n return await this.#invokeSnap(params);\n }\n\n default:\n throw rpcErrors.methodNotFound({\n data: {\n method,\n },\n });\n }\n }\n\n /**\n * Invoke an exported handler on a running Snap.\n *\n * @param options - An options bag.\n * @param options.snapId - The Snap ID.\n * @param options.handler - The handler to invoke.\n * @param options.origin - The origin invoking the handler.\n * @param options.request - The JSON-RPC request to invoke the handler with.\n * @returns The result of invoking the handler on the Snap.\n */\n async #invokeSnap({\n snapId,\n handler: handlerType,\n origin,\n request,\n }: SnapRpcRequestArguments) {\n const args = getHandlerArguments(origin, handlerType, request);\n\n const data = this.#snapData.get(snapId);\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 \"${snapId}\".`,\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 const result = await this.#executeInSnapContext(snapId, async () =>\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 || result === null) {\n return 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\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, Json>) {\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 params - The parameters.\n * @param params.snapId - The id of the snap.\n * @param params.sourceCode - The source code of the snap, in IIFE format.\n * @param params.endowments - An array of the names of the endowments.\n */\n async #startSnap({\n snapId,\n sourceCode,\n endowments: endowmentKeys,\n }: ExecuteSnapRequestArguments): 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 multiplex = new ObjectMultiplex();\n pipeline(this.#rpcStream, multiplex, this.#rpcStream, (error) => {\n if (error && !error.message?.match('Premature close')) {\n logError(`Provider stream failure.`, error);\n }\n });\n\n const provider = new SnapProvider(\n multiplex.createStream('metamask-provider'),\n {\n rpcMiddleware: [createIdRemapMiddleware()],\n },\n );\n\n provider.initializeSync();\n\n const multichainProvider = new SnapProvider(\n multiplex.createStream('metamask-multichain-provider'),\n {\n rpcMiddleware: [createIdRemapMiddleware()],\n },\n );\n\n multichainProvider.initializeSync();\n\n const snap = this.#createSnapGlobal(provider, multichainProvider);\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: endowmentKeys,\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, async () => {\n compartment.evaluate(sourceCode);\n await 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 #handleTerminate() {\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 async #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 // If the module is async, we must await the exports.\n const snapExports = await snapModule.exports;\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapExports[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 the EIP-1193 client stream.\n * @param multichainProvider - A StreamProvider connected to the CAIP-27 client stream.\n * @returns The snap provider object.\n */\n #createSnapGlobal(\n provider: StreamProvider,\n multichainProvider: StreamProvider,\n ): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n const originalMultichainRequest =\n multichainProvider.request.bind(multichainProvider);\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\n if (isMultichainRequest(sanitizedArgs)) {\n assertMultichainOutboundRequest(sanitizedArgs);\n return await withTeardown(\n originalMultichainRequest(sanitizedArgs),\n this.#teardownRef,\n );\n }\n\n return await withTeardown(\n originalRequest(sanitizedArgs),\n this.#teardownRef,\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 #createEIP1193Provider(provider: StreamProvider): 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 originalRequest(sanitizedArgs),\n this.#teardownRef,\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 #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 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 const { promise: stopPromise, reject } = createDeferredPromise<Result>();\n\n const stop = () =>\n reject(\n rpcErrors.internal(\n `The Snap \"${snapId}\" has been terminated during execution.`,\n ),\n );\n\n const evaluationData = { 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.#teardownRef.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commonEndowmentFactory.cjs","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"commonEndowmentFactory.cjs","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":";;;;;AAEA,4DAAyC;AACzC,0DAA8B;AAC9B,sDAA0B;AAC1B,8DAAkC;AAClC,sDAA0B;AAC1B,4DAAgC;AAChC,oEAAwC;AACxC,oEAAwC;AACxC,4DAAgC;AAChC,sDAAkD;AAgElD,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,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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 { JsonRpcNotification } from '@metamask/utils';\n\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';\nimport { rootRealmGlobal } from '../globalObject';\n\n/**\n * A function for sending JSON-RPC notifications from an endowment.\n * Used by endowments that perform outbound operations (e.g., network `fetch`)\n * to signal request lifecycle events.\n */\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\n/**\n * Options passed to endowment factory functions.\n */\nexport type EndowmentFactoryOptions = {\n /**\n * A label identifying the source of endowment interactions, used as a\n * prefix in console output. For example, passing `\"MyApp\"` causes console\n * messages to be prefixed with `[MyApp]`.\n */\n sourceLabel?: string;\n\n /**\n * A notification callback used by endowments that perform outbound\n * operations (e.g., network `fetch`).\n */\n notify?: NotifyFunction;\n};\n\n/**\n * The object returned by an endowment factory. Contains the endowment values\n * keyed by their global name (e.g., `setTimeout`, `Date`) and an optional\n * teardown function for lifecycle management.\n */\nexport type EndowmentFactoryResult = {\n /**\n * An optional function that performs cleanup when active resources (e.g.,\n * pending timers or open network connections) should be released. Must not\n * render endowments unusable — only restore them to their initial state,\n * since they may be reused without reconstruction.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Describes an endowment factory module. Each module exposes the names of\n * the endowments it provides and a factory function that produces them.\n */\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => EndowmentFactoryResult;\n};\n\n/**\n * Describes a simple global value that should be hardened and exposed as an\n * endowment without additional attenuation.\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: Intl, name: 'Intl' },\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: URLSearchParams, name: 'URLSearchParams' },\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,14 +1,53 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { JsonRpcNotification } from "@metamask/utils";
|
|
2
|
+
/**
|
|
3
|
+
* A function for sending JSON-RPC notifications from an endowment.
|
|
4
|
+
* Used by endowments that perform outbound operations (e.g., network `fetch`)
|
|
5
|
+
* to signal request lifecycle events.
|
|
6
|
+
*/
|
|
7
|
+
export type NotifyFunction = (notification: Omit<JsonRpcNotification, 'jsonrpc'>) => Promise<void>;
|
|
8
|
+
/**
|
|
9
|
+
* Options passed to endowment factory functions.
|
|
10
|
+
*/
|
|
2
11
|
export type EndowmentFactoryOptions = {
|
|
3
|
-
|
|
12
|
+
/**
|
|
13
|
+
* A label identifying the source of endowment interactions, used as a
|
|
14
|
+
* prefix in console output. For example, passing `"MyApp"` causes console
|
|
15
|
+
* messages to be prefixed with `[MyApp]`.
|
|
16
|
+
*/
|
|
17
|
+
sourceLabel?: string;
|
|
18
|
+
/**
|
|
19
|
+
* A notification callback used by endowments that perform outbound
|
|
20
|
+
* operations (e.g., network `fetch`).
|
|
21
|
+
*/
|
|
4
22
|
notify?: NotifyFunction;
|
|
5
23
|
};
|
|
24
|
+
/**
|
|
25
|
+
* The object returned by an endowment factory. Contains the endowment values
|
|
26
|
+
* keyed by their global name (e.g., `setTimeout`, `Date`) and an optional
|
|
27
|
+
* teardown function for lifecycle management.
|
|
28
|
+
*/
|
|
29
|
+
export type EndowmentFactoryResult = {
|
|
30
|
+
/**
|
|
31
|
+
* An optional function that performs cleanup when active resources (e.g.,
|
|
32
|
+
* pending timers or open network connections) should be released. Must not
|
|
33
|
+
* render endowments unusable — only restore them to their initial state,
|
|
34
|
+
* since they may be reused without reconstruction.
|
|
35
|
+
*/
|
|
36
|
+
teardownFunction?: () => Promise<void> | void;
|
|
37
|
+
[key: string]: unknown;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Describes an endowment factory module. Each module exposes the names of
|
|
41
|
+
* the endowments it provides and a factory function that produces them.
|
|
42
|
+
*/
|
|
6
43
|
export type EndowmentFactory = {
|
|
7
44
|
names: readonly string[];
|
|
8
|
-
factory: (options?: EndowmentFactoryOptions) =>
|
|
9
|
-
[key: string]: unknown;
|
|
10
|
-
};
|
|
45
|
+
factory: (options?: EndowmentFactoryOptions) => EndowmentFactoryResult;
|
|
11
46
|
};
|
|
47
|
+
/**
|
|
48
|
+
* Describes a simple global value that should be hardened and exposed as an
|
|
49
|
+
* endowment without additional attenuation.
|
|
50
|
+
*/
|
|
12
51
|
export type CommonEndowmentSpecification = {
|
|
13
52
|
endowment: unknown;
|
|
14
53
|
name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commonEndowmentFactory.d.cts","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"commonEndowmentFactory.d.cts","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,wBAAwB;AAa3D;;;;GAIG;AACH,MAAM,MAAM,cAAc,GAAG,CAC3B,YAAY,EAAE,IAAI,CAAC,mBAAmB,EAAE,SAAS,CAAC,KAC/C,OAAO,CAAC,IAAI,CAAC,CAAC;AAEnB;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG;IACpC;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACH,MAAM,CAAC,EAAE,cAAc,CAAC;CACzB,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC9C,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,uBAAuB,KAAK,sBAAsB,CAAC;CACxE,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,4BAA4B,GAAG;IACzC,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB,CAAC;AA6BF;;;;;;GAMG;AACH,QAAA,MAAM,qBAAqB,QAAO,gBAAgB,EA+BjD,CAAC;AAEF,eAAe,qBAAqB,CAAC"}
|
|
@@ -1,14 +1,53 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { JsonRpcNotification } from "@metamask/utils";
|
|
2
|
+
/**
|
|
3
|
+
* A function for sending JSON-RPC notifications from an endowment.
|
|
4
|
+
* Used by endowments that perform outbound operations (e.g., network `fetch`)
|
|
5
|
+
* to signal request lifecycle events.
|
|
6
|
+
*/
|
|
7
|
+
export type NotifyFunction = (notification: Omit<JsonRpcNotification, 'jsonrpc'>) => Promise<void>;
|
|
8
|
+
/**
|
|
9
|
+
* Options passed to endowment factory functions.
|
|
10
|
+
*/
|
|
2
11
|
export type EndowmentFactoryOptions = {
|
|
3
|
-
|
|
12
|
+
/**
|
|
13
|
+
* A label identifying the source of endowment interactions, used as a
|
|
14
|
+
* prefix in console output. For example, passing `"MyApp"` causes console
|
|
15
|
+
* messages to be prefixed with `[MyApp]`.
|
|
16
|
+
*/
|
|
17
|
+
sourceLabel?: string;
|
|
18
|
+
/**
|
|
19
|
+
* A notification callback used by endowments that perform outbound
|
|
20
|
+
* operations (e.g., network `fetch`).
|
|
21
|
+
*/
|
|
4
22
|
notify?: NotifyFunction;
|
|
5
23
|
};
|
|
24
|
+
/**
|
|
25
|
+
* The object returned by an endowment factory. Contains the endowment values
|
|
26
|
+
* keyed by their global name (e.g., `setTimeout`, `Date`) and an optional
|
|
27
|
+
* teardown function for lifecycle management.
|
|
28
|
+
*/
|
|
29
|
+
export type EndowmentFactoryResult = {
|
|
30
|
+
/**
|
|
31
|
+
* An optional function that performs cleanup when active resources (e.g.,
|
|
32
|
+
* pending timers or open network connections) should be released. Must not
|
|
33
|
+
* render endowments unusable — only restore them to their initial state,
|
|
34
|
+
* since they may be reused without reconstruction.
|
|
35
|
+
*/
|
|
36
|
+
teardownFunction?: () => Promise<void> | void;
|
|
37
|
+
[key: string]: unknown;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Describes an endowment factory module. Each module exposes the names of
|
|
41
|
+
* the endowments it provides and a factory function that produces them.
|
|
42
|
+
*/
|
|
6
43
|
export type EndowmentFactory = {
|
|
7
44
|
names: readonly string[];
|
|
8
|
-
factory: (options?: EndowmentFactoryOptions) =>
|
|
9
|
-
[key: string]: unknown;
|
|
10
|
-
};
|
|
45
|
+
factory: (options?: EndowmentFactoryOptions) => EndowmentFactoryResult;
|
|
11
46
|
};
|
|
47
|
+
/**
|
|
48
|
+
* Describes a simple global value that should be hardened and exposed as an
|
|
49
|
+
* endowment without additional attenuation.
|
|
50
|
+
*/
|
|
12
51
|
export type CommonEndowmentSpecification = {
|
|
13
52
|
endowment: unknown;
|
|
14
53
|
name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commonEndowmentFactory.d.mts","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"commonEndowmentFactory.d.mts","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,wBAAwB;AAa3D;;;;GAIG;AACH,MAAM,MAAM,cAAc,GAAG,CAC3B,YAAY,EAAE,IAAI,CAAC,mBAAmB,EAAE,SAAS,CAAC,KAC/C,OAAO,CAAC,IAAI,CAAC,CAAC;AAEnB;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG;IACpC;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACH,MAAM,CAAC,EAAE,cAAc,CAAC;CACzB,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC9C,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,uBAAuB,KAAK,sBAAsB,CAAC;CACxE,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,4BAA4B,GAAG;IACzC,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB,CAAC;AA6BF;;;;;;GAMG;AACH,QAAA,MAAM,qBAAqB,QAAO,gBAAgB,EA+BjD,CAAC;AAEF,eAAe,qBAAqB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commonEndowmentFactory.mjs","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"commonEndowmentFactory.mjs","sourceRoot":"","sources":["../../../src/common/endowments/commonEndowmentFactory.ts"],"names":[],"mappings":"AAEA,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;AAChC,OAAO,EAAE,eAAe,EAAE,4BAAwB;AAgElD,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,UAAU,EAAE;IACzC,EAAE,SAAS,EAAE,YAAY,EAAE,IAAI,EAAE,cAAc,EAAE;IACj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C,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 { JsonRpcNotification } from '@metamask/utils';\n\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';\nimport { rootRealmGlobal } from '../globalObject';\n\n/**\n * A function for sending JSON-RPC notifications from an endowment.\n * Used by endowments that perform outbound operations (e.g., network `fetch`)\n * to signal request lifecycle events.\n */\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\n/**\n * Options passed to endowment factory functions.\n */\nexport type EndowmentFactoryOptions = {\n /**\n * A label identifying the source of endowment interactions, used as a\n * prefix in console output. For example, passing `\"MyApp\"` causes console\n * messages to be prefixed with `[MyApp]`.\n */\n sourceLabel?: string;\n\n /**\n * A notification callback used by endowments that perform outbound\n * operations (e.g., network `fetch`).\n */\n notify?: NotifyFunction;\n};\n\n/**\n * The object returned by an endowment factory. Contains the endowment values\n * keyed by their global name (e.g., `setTimeout`, `Date`) and an optional\n * teardown function for lifecycle management.\n */\nexport type EndowmentFactoryResult = {\n /**\n * An optional function that performs cleanup when active resources (e.g.,\n * pending timers or open network connections) should be released. Must not\n * render endowments unusable — only restore them to their initial state,\n * since they may be reused without reconstruction.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Describes an endowment factory module. Each module exposes the names of\n * the endowments it provides and a factory function that produces them.\n */\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => EndowmentFactoryResult;\n};\n\n/**\n * Describes a simple global value that should be hardened and exposed as an\n * endowment without additional attenuation.\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: Intl, name: 'Intl' },\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: URLSearchParams, name: 'URLSearchParams' },\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"]}
|