@metamask/snaps-execution-environments 0.26.1 → 0.27.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/dist/common/BaseSnapExecutor.js.map +1 -1
- package/dist/common/endowments/index.d.ts +1 -1
- package/dist/common/endowments/index.js +4 -4
- package/dist/common/endowments/index.js.map +1 -1
- package/dist/common/endowments/network.d.ts +11 -11
- package/dist/common/keyring.d.ts +1 -1
- package/dist/common/keyring.js.map +1 -1
- package/dist/common/validation.d.ts +2 -2
- package/dist/common/validation.js.map +1 -1
- package/dist/webpack/iframe/bundle.js +1 -1
- package/dist/webpack/node-process/bundle.js +6 -6
- package/dist/webpack/node-thread/bundle.js +6 -6
- package/package.json +2 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseSnapExecutor.js","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,mDAAqD;AAGrD,uDAI+B;AAC/B,2CAWyB;AACzB,mDAAuE;AACvE,qDAA0D;AAE1D,6CAAuC;AAEvC,mEAAgD;AAChD,yCAGoB;AACpB,6CAAgD;AAChD,iDAAuE;AACvE,uCAAwC;AACxC,6CAA6C;AAC7C,mCAAuD;AACvD,6CAMsB;AAYtB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,2BAAU,CAAC,GAAG,CAAC,QAAQ;IAC7B,OAAO,EAAE,6BAA6B;CACvC,CAAC;AAYF;;;;GAIG;AACH,MAAM,6BAA6B,GAAG;IACpC,IAAI,EAAE;QACJ,MAAM,EAAE,uCAA0B;QAClC,MAAM,EAAE,EAAE;KACX;IACD,WAAW,EAAE;QACX,MAAM,EAAE,8CAAiC;QACzC,MAAM,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,YAAY,CAAC;KACjD;IACD,SAAS,EAAE;QACT,MAAM,EAAE,4CAA+B;QACvC,MAAM,EAAE,EAAE;KAC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CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE;gBACtC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC;gBACvB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;aAC3B;SACF;IACH,CAAC;CACF;AA/YD,4CA+YC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/index.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { SnapExports, SnapsGlobalObject } from '@metamask/snaps-types';\nimport {\n HandlerType,\n SnapExportsParameters,\n SNAP_EXPORT_NAMES,\n} from '@metamask/snaps-utils';\nimport {\n isObject,\n isValidJson,\n JsonRpcNotification,\n assert,\n isJsonRpcRequest,\n JsonRpcId,\n JsonRpcRequest,\n JsonRpcParams,\n Json,\n hasProperty,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport EEOpenRPCDocument from '../openrpc.json';\nimport {\n CommandMethodsMapping,\n getCommandMethodImplementations,\n} from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { wrapKeyring } from './keyring';\nimport { sortParamKeys } from './sortParams';\nimport { constructError, withTeardown } from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n validateExport,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\n// TODO: `KeyringParameters` expects a `chainId` for certain methods, but we're\n// not providing it in `getHandlerArguments`, resulting in type errors.\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapName', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n console.error(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerName, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object before the call\n const handler =\n handlerName === HandlerType.SnapKeyring\n ? wrapKeyring(this.notify.bind(this), data?.exports.keyring)\n : data?.exports[handlerName];\n assert(\n handler !== undefined,\n `No ${handlerName} handler exported for snap \"${target}`,\n );\n // TODO: fix handler args type cast\n let result = await this.executeInSnapContext(target, () =>\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n assert(\n isValidJson(result),\n new TypeError('Received non-JSON-serializable value.'),\n );\n return result;\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const constructedError = constructError(error);\n const serializedError = serializeError(constructedError, {\n fallbackError,\n shouldIncludeStack: false,\n });\n\n // We're setting it this way to avoid sentData.stack = undefined\n const sentData: Json = { ...data, stack: constructedError?.stack ?? null };\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: sentData,\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest<JsonRpcParams>) {\n if (!isJsonRpcRequest(message)) {\n throw new Error('Command stream received a non-JSON-RPC request.');\n }\n\n const { id, method, params } = message;\n if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject =\n EXECUTION_ENVIRONMENT_METHODS[\n method as keyof typeof EXECUTION_ENVIRONMENT_METHODS\n ];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: ethErrors.rpc\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(\n requestObject: Omit<\n JsonRpcNotification<Record<string, Json> | Json[] | undefined>,\n 'jsonrpc'\n >,\n ) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error('JSON-RPC responses must be JSON serializable objects.');\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapName - The name of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapName: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n console.log(`starting snap '${snapName}' in worker`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapName });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapName,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapName, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n window: { ...endowments },\n self: { ...endowments },\n });\n\n await this.executeInSnapContext(snapName, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapName, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapName);\n throw new Error(\n `Error while running snap '${snapName}': ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapName: string, snapModule: any) {\n const data = this.snapData.get(snapName);\n // Somebody deleted the Snap before we could register\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n if (validateExport(exportName, snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assert(\n args.method.startsWith('wallet_') || args.method.startsWith('snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n return { request };\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n provider.request = async (args) => {\n assert(\n !args.method.startsWith('snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n return provider;\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapName - The name of the snap to remove.\n */\n private removeSnap(snapName: string): void {\n this.snapData.delete(snapName);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapName - The name of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapName: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapName);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapName}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n ethErrors.rpc.internal(\n `The snap \"${snapName}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"BaseSnapExecutor.js","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mapp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AAiD,QAAQ,IAAI,CAC9D,CAAC;SACH;QAED,IAAI,IAAgB,CAAC;QACrB,MAAM,WAAW,GAAG,IAAI,OAAO,CAC7B,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CACZ,CAAC,IAAI,GAAG,GAAG,EAAE,CACX,MAAM;QACJ,kEAAkE;QAClE,0BAAS,CAAC,GAAG,CAAC,QAAQ,CACpB,aAAa,QAAQ,yCAAyC,CAC/D,CACF,CAAC,CACP,CAAC;QAEF,oEAAoE;QACpE,MAAM,cAAc,GAAG,EAAE,IAAI,EAAE,IAAK,EAAE,CAAC;QAEvC,IAAI;YACF,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;YAC5C,8CAA8C;YAC9C,oEAAoE;YACpE,uCAAuC;YACvC,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC;SACtD;gBAAS;YACR,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE;gBACtC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC;gBACvB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;aAC3B;SACF;IACH,CAAC;CACF;AA/YD,4CA+YC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/index.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport {\n SnapExports,\n SnapsGlobalObject,\n HandlerType,\n SnapExportsParameters,\n SNAP_EXPORT_NAMES,\n} from '@metamask/snaps-utils';\nimport {\n isObject,\n isValidJson,\n JsonRpcNotification,\n assert,\n isJsonRpcRequest,\n JsonRpcId,\n JsonRpcRequest,\n JsonRpcParams,\n Json,\n hasProperty,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport EEOpenRPCDocument from '../openrpc.json';\nimport {\n CommandMethodsMapping,\n getCommandMethodImplementations,\n} from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { wrapKeyring } from './keyring';\nimport { sortParamKeys } from './sortParams';\nimport { constructError, withTeardown } from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n validateExport,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\n// TODO: `KeyringParameters` expects a `chainId` for certain methods, but we're\n// not providing it in `getHandlerArguments`, resulting in type errors.\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapName', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n console.error(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerName, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object before the call\n const handler =\n handlerName === HandlerType.SnapKeyring\n ? wrapKeyring(this.notify.bind(this), data?.exports.keyring)\n : data?.exports[handlerName];\n assert(\n handler !== undefined,\n `No ${handlerName} handler exported for snap \"${target}`,\n );\n // TODO: fix handler args type cast\n let result = await this.executeInSnapContext(target, () =>\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n assert(\n isValidJson(result),\n new TypeError('Received non-JSON-serializable value.'),\n );\n return result;\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const constructedError = constructError(error);\n const serializedError = serializeError(constructedError, {\n fallbackError,\n shouldIncludeStack: false,\n });\n\n // We're setting it this way to avoid sentData.stack = undefined\n const sentData: Json = { ...data, stack: constructedError?.stack ?? null };\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: sentData,\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest<JsonRpcParams>) {\n if (!isJsonRpcRequest(message)) {\n throw new Error('Command stream received a non-JSON-RPC request.');\n }\n\n const { id, method, params } = message;\n if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject =\n EXECUTION_ENVIRONMENT_METHODS[\n method as keyof typeof EXECUTION_ENVIRONMENT_METHODS\n ];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: ethErrors.rpc\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(\n requestObject: Omit<\n JsonRpcNotification<Record<string, Json> | Json[] | undefined>,\n 'jsonrpc'\n >,\n ) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error('JSON-RPC responses must be JSON serializable objects.');\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapName - The name of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapName: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n console.log(`starting snap '${snapName}' in worker`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapName });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapName,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapName, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n window: { ...endowments },\n self: { ...endowments },\n });\n\n await this.executeInSnapContext(snapName, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapName, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapName);\n throw new Error(\n `Error while running snap '${snapName}': ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapName: string, snapModule: any) {\n const data = this.snapData.get(snapName);\n // Somebody deleted the Snap before we could register\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n if (validateExport(exportName, snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assert(\n args.method.startsWith('wallet_') || args.method.startsWith('snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n return { request };\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n provider.request = async (args) => {\n assert(\n !args.method.startsWith('snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(args), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n return provider;\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapName - The name of the snap to remove.\n */\n private removeSnap(snapName: string): void {\n this.snapData.delete(snapName);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapName - The name of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapName: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapName);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapName}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n ethErrors.rpc.internal(\n `The snap \"${snapName}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StreamProvider } from '@metamask/providers';
|
|
2
|
-
import { SnapsGlobalObject } from '@metamask/snaps-
|
|
2
|
+
import { SnapsGlobalObject } from '@metamask/snaps-utils';
|
|
3
3
|
/**
|
|
4
4
|
* Gets the endowments for a particular Snap. Some endowments, like `setTimeout`
|
|
5
5
|
* and `clearTimeout`, must be attenuated so that they can only affect behavior
|
|
@@ -70,6 +70,10 @@ function createEndowments(snap, ethereum, endowments = []) {
|
|
|
70
70
|
}
|
|
71
71
|
allEndowments[endowmentName] = attenuatedEndowments[endowmentName];
|
|
72
72
|
}
|
|
73
|
+
else if (endowmentName === 'ethereum') {
|
|
74
|
+
// Special case for adding the EIP-1193 provider.
|
|
75
|
+
allEndowments[endowmentName] = ethereum;
|
|
76
|
+
}
|
|
73
77
|
else if (endowmentName in globalObject_1.rootRealmGlobal) {
|
|
74
78
|
// If the endowment doesn't have a factory, just use whatever is on the
|
|
75
79
|
// global object.
|
|
@@ -79,10 +83,6 @@ function createEndowments(snap, ethereum, endowments = []) {
|
|
|
79
83
|
? globalValue.bind(globalObject_1.rootRealmGlobal)
|
|
80
84
|
: globalValue;
|
|
81
85
|
}
|
|
82
|
-
else if (endowmentName === 'ethereum') {
|
|
83
|
-
// Special case for adding the EIP-1193 provider.
|
|
84
|
-
allEndowments[endowmentName] = ethereum;
|
|
85
|
-
}
|
|
86
86
|
else {
|
|
87
87
|
// If we get to this point, we've been passed an endowment that doesn't
|
|
88
88
|
// exist in our current environment.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAEA,2CAA8C;AAE9C,kDAAkD;AAClD,sDAA8B;AAC9B,0DAAkC;AAClC,kDAA0B;AAC1B,wDAAgC;AAChC,wDAAgC;AAehC;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,CAAC,iBAAO,EAAE,kBAAQ,EAAE,iBAAO,EAAE,gBAAM,EAAE,cAAI,CAAC,CAAC,MAAM,CAC1E,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC7B,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC,CAAC,CAAC;IACH,OAAO,SAAS,CAAC;AACnB,CAAC,EACD,IAAI,GAAG,EAAwC,CAChD,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,SAAgB,gBAAgB,CAC9B,IAAuB,EACvB,QAAwB,EACxB,aAAuB,EAAE;IAEzB,MAAM,oBAAoB,GAA4B,EAAE,CAAC;IAEzD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAI9B,CAAC,EAAE,aAAa,EAAE,SAAS,EAAE,EAAE,aAAa,EAAE,EAAE;QAC9C,oEAAoE;QACpE,IAAI,kBAAkB,CAAC,GAAG,CAAC,aAA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esContent":["import { StreamProvider } from '@metamask/providers';\nimport { SnapsGlobalObject } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport crypto from './crypto';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport timeout from './timeout';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = [timeout, interval, network, crypto, math].reduce(\n (factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n },\n new Map<string, () => EndowmentFactoryResult>(),\n);\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n const { teardownFunction, ...endowment } =\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n endowmentFactories.get(endowmentName)!();\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] =\n typeof globalValue === 'function' && !isConstructor(globalValue)\n ? globalValue.bind(rootRealmGlobal)\n : globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw new Error(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n\n/**\n * Checks whether the specified function is a constructor.\n *\n * @param value - Any function value.\n * @returns Whether the specified function is a constructor.\n */\n// `Function` is exactly what we want here.\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isConstructor<T extends Function>(value: T): boolean {\n // In our current usage, the string `prototype.constructor.name` should never\n // be empty, because you can't create a class with no name, and the\n // `prototype.constructor.name` property is configurable but not writable.\n // Nevertheless, that property was the empty string for `Date` in the iframe\n // execution environment during local testing. We have no idea why, but we\n // have to handle that case.\n // TODO: Does the `prototype` object always have a `constructor` property?\n return Boolean(typeof value.prototype?.constructor?.name === 'string');\n}\n"]}
|
|
@@ -26,20 +26,20 @@ declare const endowmentModule: {
|
|
|
26
26
|
removeEventListener<K_1 extends keyof WebSocketEventMap>(type: K_1, listener: (this: WebSocket, ev: WebSocketEventMap[K_1]) => any, options?: boolean | EventListenerOptions): void;
|
|
27
27
|
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
|
|
28
28
|
dispatchEvent(event: Event): boolean;
|
|
29
|
-
"__#
|
|
30
|
-
"__#
|
|
31
|
-
"__#
|
|
32
|
-
"__#
|
|
33
|
-
"__#
|
|
29
|
+
"__#4@#teardownClose"(): Promise<void>;
|
|
30
|
+
"__#4@#createWrapped"(listener: WebSocketCallback): WebSocketCallback;
|
|
31
|
+
"__#4@#createWrapped"(listener: null): null;
|
|
32
|
+
"__#4@#createWrapped"(listener: WebSocketCallback | null): WebSocketCallback | null;
|
|
33
|
+
"__#4@#socket": WebSocket;
|
|
34
34
|
/**
|
|
35
35
|
* After this is set to true, no new event listeners can be added
|
|
36
36
|
*/
|
|
37
|
-
"__#
|
|
38
|
-
"__#
|
|
39
|
-
"__#
|
|
40
|
-
"__#
|
|
41
|
-
"__#
|
|
42
|
-
"__#
|
|
37
|
+
"__#4@#isTornDown": boolean;
|
|
38
|
+
"__#4@#events": Record<string, Map<WebSocketCallback, WebSocketCallback>>;
|
|
39
|
+
"__#4@#onopenOriginal": WebSocketCallback | null;
|
|
40
|
+
"__#4@#onmessageOriginal": WebSocketCallback | null;
|
|
41
|
+
"__#4@#onerrorOriginal": WebSocketCallback | null;
|
|
42
|
+
"__#4@#oncloseOriginal": WebSocketCallback | null;
|
|
43
43
|
};
|
|
44
44
|
};
|
|
45
45
|
teardownFunction: () => Promise<void>;
|
package/dist/common/keyring.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SnapKeyring } from '@metamask/snaps-
|
|
1
|
+
import { SnapKeyring } from '@metamask/snaps-utils';
|
|
2
2
|
import { Json, JsonRpcNotification, JsonRpcRequest } from '@metamask/utils';
|
|
3
3
|
/**
|
|
4
4
|
* Wraps a SnapKeyring class, returning a handler that can route requests to the exposed functions by the class.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyring.js","sourceRoot":"","sources":["../../src/common/keyring.ts"],"names":[],"mappings":";;;AACA,2CAMyB;AAEzB;;;;;;GAMG;AACH,SAAgB,WAAW,CACzB,MAKS,EACT,OAAqB;IAErB,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;KACzC;IAED,MAAM,cAAc,GAAG,CAAC,EAAE,OAAO,EAAuC,EAAE,EAAE;QAC1E,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QACnC,IAAI,CAAC,CAAC,MAAM,IAAI,OAAO,CAAC,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,2BAA2B,MAAM,EAAE,CAAC,CAAC;SACtD;QACD,IAAI,IAAI,GAAG,CAAC,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,EAAE,CAAc,CAAC;QACvC,MAAM,aAAa,GAAG,OAAO,CAAC,MAA2B,CAAC,CAAC;QAC3D,IAAA,cAAM,EAAC,aAAa,KAAK,SAAS,CAAC,CAAC;QACpC,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACzC,sCAAsC;QACtC,IAAI,MAAM,KAAK,IAAI,EAAE;YACnB,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAS,CAAC;YAC7B,MAAM,QAAQ,GAAG,CAAC,GAAG,YAAuB,EAAE,EAAE;gBAC9C,IAAA,cAAM,EACJ,IAAA,mBAAW,EAAC,YAAY,CAAC,EACzB,IAAI,SAAS,CACX,6DAA6D,CAC9D,CACF,CAAC;gBACF,OAAO,MAAM,CAAC;oBACZ,MAAM,EAAE,kBAAkB;oBAC1B,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE;iBACrC,CAAC,CAAC;YACL,CAAC,CAAC;YACF,IAAI,GAAG,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;SACzB;QACD,OAAQ,IAAqC,CAAC,GAAG,IAAI,CAAC,CAAC;IACzD,CAAC,CAAC;IACF,OAAO,cAAc,CAAC;AACxB,CAAC;AA1CD,kCA0CC","sourcesContent":["import { SnapKeyring } from '@metamask/snaps-
|
|
1
|
+
{"version":3,"file":"keyring.js","sourceRoot":"","sources":["../../src/common/keyring.ts"],"names":[],"mappings":";;;AACA,2CAMyB;AAEzB;;;;;;GAMG;AACH,SAAgB,WAAW,CACzB,MAKS,EACT,OAAqB;IAErB,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;KACzC;IAED,MAAM,cAAc,GAAG,CAAC,EAAE,OAAO,EAAuC,EAAE,EAAE;QAC1E,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QACnC,IAAI,CAAC,CAAC,MAAM,IAAI,OAAO,CAAC,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,2BAA2B,MAAM,EAAE,CAAC,CAAC;SACtD;QACD,IAAI,IAAI,GAAG,CAAC,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,EAAE,CAAc,CAAC;QACvC,MAAM,aAAa,GAAG,OAAO,CAAC,MAA2B,CAAC,CAAC;QAC3D,IAAA,cAAM,EAAC,aAAa,KAAK,SAAS,CAAC,CAAC;QACpC,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACzC,sCAAsC;QACtC,IAAI,MAAM,KAAK,IAAI,EAAE;YACnB,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAS,CAAC;YAC7B,MAAM,QAAQ,GAAG,CAAC,GAAG,YAAuB,EAAE,EAAE;gBAC9C,IAAA,cAAM,EACJ,IAAA,mBAAW,EAAC,YAAY,CAAC,EACzB,IAAI,SAAS,CACX,6DAA6D,CAC9D,CACF,CAAC;gBACF,OAAO,MAAM,CAAC;oBACZ,MAAM,EAAE,kBAAkB;oBAC1B,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,YAAY,EAAE;iBACrC,CAAC,CAAC;YACL,CAAC,CAAC;YACF,IAAI,GAAG,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;SACzB;QACD,OAAQ,IAAqC,CAAC,GAAG,IAAI,CAAC,CAAC;IACzD,CAAC,CAAC;IACF,OAAO,cAAc,CAAC;AACxB,CAAC;AA1CD,kCA0CC","sourcesContent":["import { SnapKeyring } from '@metamask/snaps-utils';\nimport {\n assert,\n isValidJson,\n Json,\n JsonRpcNotification,\n JsonRpcRequest,\n} from '@metamask/utils';\n\n/**\n * Wraps a SnapKeyring class, returning a handler that can route requests to the exposed functions by the class.\n *\n * @param notify - The BaseSnapExecutor notify function, used for event communication.\n * @param keyring - The SnapKeyring instance.\n * @returns A handler function.\n */\nexport function wrapKeyring(\n notify: (\n requestObject: Omit<\n JsonRpcNotification<Record<string, Json> | Json[]>,\n 'jsonrpc'\n >,\n ) => void,\n keyring?: SnapKeyring,\n) {\n if (!keyring) {\n throw new Error('Keyring not exported');\n }\n\n const keyringHandler = ({ request }: { request: JsonRpcRequest<Json[]> }) => {\n const { method, params } = request;\n if (!(method in keyring)) {\n throw new Error(`Keyring does not expose ${method}`);\n }\n let args = (params ?? []) as unknown[];\n const keyringMethod = keyring[method as keyof SnapKeyring];\n assert(keyringMethod !== undefined);\n const func = keyringMethod.bind(keyring);\n // Special case for registering events\n if (method === 'on') {\n const data = args[0] as Json;\n const listener = (...listenerArgs: unknown[]) => {\n assert(\n isValidJson(listenerArgs),\n new TypeError(\n 'Keyrings .on listener received non-JSON-serializable value.',\n ),\n );\n return notify({\n method: 'SnapKeyringEvent',\n params: { data, args: listenerArgs },\n });\n };\n args = [data, listener];\n }\n return (func as (..._: unknown[]) => unknown)(...args);\n };\n return keyringHandler;\n}\n"]}
|
|
@@ -13,12 +13,12 @@ export declare const JsonRpcRequestWithoutIdStruct: import("superstruct").Struct
|
|
|
13
13
|
jsonrpc: "2.0";
|
|
14
14
|
method: string;
|
|
15
15
|
id?: string | number | null | undefined;
|
|
16
|
-
params?: Record<string, Json> |
|
|
16
|
+
params?: Json[] | Record<string, Json> | undefined;
|
|
17
17
|
}, {
|
|
18
18
|
id: import("superstruct").Struct<string | number | null | undefined, null>;
|
|
19
19
|
jsonrpc: import("superstruct").Struct<"2.0", "2.0">;
|
|
20
20
|
method: import("superstruct").Struct<string, null>;
|
|
21
|
-
params: import("superstruct").Struct<Record<string, Json> |
|
|
21
|
+
params: import("superstruct").Struct<Json[] | Record<string, Json> | undefined, null>;
|
|
22
22
|
}>;
|
|
23
23
|
export declare type JsonRpcRequestWithoutId = Infer<typeof JsonRpcRequestWithoutIdStruct>;
|
|
24
24
|
export declare const EndowmentStruct: import("superstruct").Struct<string, null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/common/validation.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/common/validation.ts"],"names":[],"mappings":";;;AAAA,uDAAgF;AAChF,2CAQyB;AACzB,6CAeqB;AAErB,MAAM,oBAAoB,GAAG;IAC3B,CAAC,yBAAW,CAAC,YAAY,CAAC,EAAE,sBAAsB;IAClD,CAAC,yBAAW,CAAC,aAAa,CAAC,EAAE,sBAAsB;IACnD,CAAC,yBAAW,CAAC,WAAW,CAAC,EAAE,qBAAqB;IAChD,CAAC,yBAAW,CAAC,SAAS,CAAC,EAAE,sBAAsB;CAChD,CAAC;AAEF;;;;;GAKG;AACH,SAAS,sBAAsB,CAC7B,UAAmB;IAEnB,OAAO,OAAO,UAAU,KAAK,UAAU,CAAC;AAC1C,CAAC;AAED;;;;;GAKG;AACH,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AC,CAAC;AAEU,QAAA,iCAAiC,GAAG,IAAA,mBAAK,EAAC;IACrD,IAAA,oBAAM,GAAE;IACR,IAAA,oBAAM,GAAE;IACR,IAAA,sBAAQ,EAAC,IAAA,mBAAK,EAAC,uBAAe,CAAC,CAAC;CACjC,CAAC,CAAC;AAEU,QAAA,6BAA6B,GAAG,IAAA,mBAAK,EAAC;IACjD,IAAA,oBAAM,GAAE;IACR,IAAA,mBAAK,EAAC,MAAM,CAAC,MAAM,CAAC,yBAAW,CAAC,CAAC;IACjC,IAAA,oBAAM,GAAE;IACR,IAAA,oBAAM,EACJ,qCAA6B,EAC7B,IAAA,oBAAM,EAAC;QACL,MAAM,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,kBAAU,CAAC,CAAC;KAC/C,CAAC,CACH;CACF,CAAC,CAAC;AAqBU,QAAA,mCAAmC,GAAG,IAAA,oBAAM,EAAC;IACxD,oCAAoC;IACpC,WAAW,EAAE,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,kBAAU,CAAC;IACzC,OAAO,EAAE,2BAAa;IACtB,iBAAiB,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,GAAE,CAAC;CACtC,CAAC,CAAC;AAMH;;;;;;;GAOG;AACH,SAAgB,qCAAqC,CACnD,KAAc;IAEd,IAAA,oBAAY,EACV,KAAK,EACL,2CAAmC,EACnC,wBAAwB,CACzB,CAAC;AACJ,CAAC;AARD,sFAQC;AAED,MAAM,gBAAgB,GAAG,IAAA,oBAAM,EAC7B,4BAAoB,EACpB,IAAA,oBAAM,EAAC;IACL,MAAM,EAAE,QAAQ;CACjB,CAAC,CACH,CAAC;AAEF,MAAM,eAAe,GAAG,4BAAoB,CAAC","sourcesContent":["import { SnapKeyring, ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport {\n assertStruct,\n Json,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccess,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport {\n array,\n assign,\n enums,\n Infer,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nconst VALIDATION_FUNCTIONS = {\n [HandlerType.OnRpcRequest]: validateFunctionExport,\n [HandlerType.OnTransaction]: validateFunctionExport,\n [HandlerType.SnapKeyring]: validateKeyringExport,\n [HandlerType.OnCronjob]: validateFunctionExport,\n};\n\n/**\n * Validates a function export.\n *\n * @param snapExport - The export itself.\n * @returns True if the export matches the expected shape, false otherwise.\n */\nfunction validateFunctionExport(\n snapExport: unknown,\n): snapExport is (...args: unknown[]) => unknown {\n return typeof snapExport === 'function';\n}\n\n/**\n * Validates a keyring export.\n *\n * @param snapExport - The export itself.\n * @returns True if the export matches the expected shape, false otherwise.\n */\nfunction validateKeyringExport(snapExport: unknown): snapExport is SnapKeyring {\n // TODO Decide whether we want more validation\n return typeof snapExport === 'object';\n}\n\n/**\n * Validates a given snap export.\n *\n * @param type - The type of export expected.\n * @param snapExport - The export itself.\n * @returns True if the export matches the expected shape, false otherwise.\n */\nexport function validateExport(type: HandlerType, snapExport: unknown) {\n const validationFunction = VALIDATION_FUNCTIONS[type];\n return validationFunction?.(snapExport) ?? false;\n}\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n optional(array(EndowmentStruct)),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n );\n}\n\nconst OkResponseStruct = assign(\n JsonRpcSuccessStruct,\n object({\n result: OkStruct,\n }),\n);\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"]}
|