@metamask/snaps-execution-environments 0.36.0-flask.1 → 0.37.0-flask.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/dist/browserify/iframe/bundle.js +6 -4
  3. package/dist/browserify/node-process/bundle.js +4 -2
  4. package/dist/browserify/node-thread/bundle.js +4 -2
  5. package/dist/browserify/offscreen/bundle.js +5 -3
  6. package/dist/browserify/worker-executor/bundle.js +6 -4
  7. package/dist/browserify/worker-pool/bundle.js +5 -3
  8. package/dist/cjs/common/BaseSnapExecutor.js.map +1 -1
  9. package/dist/cjs/common/commands.js.map +1 -1
  10. package/dist/cjs/common/endowments/commonEndowmentFactory.js.map +1 -1
  11. package/dist/cjs/common/endowments/console.js.map +1 -1
  12. package/dist/cjs/common/endowments/crypto.js +1 -1
  13. package/dist/cjs/common/endowments/crypto.js.map +1 -1
  14. package/dist/cjs/common/endowments/index.js.map +1 -1
  15. package/dist/cjs/common/sortParams.js.map +1 -1
  16. package/dist/cjs/common/utils.js.map +1 -1
  17. package/dist/cjs/common/validation.js.map +1 -1
  18. package/dist/cjs/iframe/IFrameSnapExecutor.js.map +1 -1
  19. package/dist/cjs/offscreen/OffscreenSnapExecutor.js.map +1 -1
  20. package/dist/cjs/webworker/executor/WebWorkerSnapExecutor.js.map +1 -1
  21. package/dist/cjs/webworker/pool/WebWorkerPool.js.map +1 -1
  22. package/dist/esm/common/BaseSnapExecutor.js.map +1 -1
  23. package/dist/esm/common/commands.js.map +1 -1
  24. package/dist/esm/common/endowments/commonEndowmentFactory.js.map +1 -1
  25. package/dist/esm/common/endowments/console.js.map +1 -1
  26. package/dist/esm/common/endowments/crypto.js +1 -1
  27. package/dist/esm/common/endowments/crypto.js.map +1 -1
  28. package/dist/esm/common/endowments/index.js.map +1 -1
  29. package/dist/esm/common/sortParams.js.map +1 -1
  30. package/dist/esm/common/utils.js.map +1 -1
  31. package/dist/esm/common/validation.js.map +1 -1
  32. package/dist/esm/iframe/IFrameSnapExecutor.js.map +1 -1
  33. package/dist/esm/offscreen/OffscreenSnapExecutor.js.map +1 -1
  34. package/dist/esm/webworker/executor/WebWorkerSnapExecutor.js.map +1 -1
  35. package/dist/esm/webworker/pool/WebWorkerPool.js.map +1 -1
  36. package/dist/types/common/BaseSnapExecutor.d.ts +3 -3
  37. package/dist/types/common/commands.d.ts +2 -2
  38. package/dist/types/common/endowments/commonEndowmentFactory.d.ts +1 -1
  39. package/dist/types/common/endowments/console.d.ts +1 -1
  40. package/dist/types/common/endowments/index.d.ts +3 -3
  41. package/dist/types/common/sortParams.d.ts +1 -1
  42. package/dist/types/common/utils.d.ts +4 -4
  43. package/dist/types/common/validation.d.ts +2 -2
  44. package/dist/types/iframe/IFrameSnapExecutor.d.ts +1 -1
  45. package/dist/types/offscreen/OffscreenSnapExecutor.d.ts +2 -1
  46. package/dist/types/webworker/executor/WebWorkerSnapExecutor.d.ts +1 -1
  47. package/dist/types/webworker/pool/WebWorkerPool.d.ts +2 -1
  48. package/package.json +9 -8
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/index.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n SNAP_EXPORT_NAMES,\n logError,\n} from '@metamask/snaps-utils';\nimport {\n isObject,\n isValidJson,\n JsonRpcNotification,\n assert,\n isJsonRpcRequest,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n hasProperty,\n getSafeJson,\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 { log } from '../logging';\nimport EEOpenRPCDocument from '../openrpc.json';\nimport {\n CommandMethodsMapping,\n getCommandMethodImplementations,\n} from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n constructError,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n 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\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, 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 = 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 // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw new TypeError(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const constructedError = constructError(error);\n const serializedError = serializeError(constructedError, {\n fallbackError,\n shouldIncludeStack: false,\n });\n\n // We're setting it this way to avoid sentData.stack = undefined\n const sentData: Json = { ...data, stack: constructedError?.stack ?? null };\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: sentData,\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw new Error('Command stream received a non-JSON-RPC request.');\n }\n\n const { id, method, params } = message;\n if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: ethErrors.rpc\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error('JSON-RPC responses must be JSON serializable objects.');\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n snapId,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n throw new Error(\n `Error while running snap '${snapId}': ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the Snap before we could register\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n 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 assertSnapOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assertEthereumOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n ethErrors.rpc.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","constructedError","constructError","serializedError","serializeError","shouldIncludeStack","sentData","stack","notify","method","onCommandRequest","isJsonRpcRequest","Error","id","respond","result","EEOpenRPCDocument","hasProperty","ethErrors","methodNotFound","serialize","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","methods","rpcError","requestObject","isValidJson","isObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validateExport","originalRequest","request","bind","args","assertSnapOutboundRequest","sanitizedArgs","getSafeJson","withTeardown","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","logError","getCommandMethodImplementations","target","handlerName","handler","assert","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BAqGnDA;;;eAAAA;;;2BApGkB;4BASxB;uBAYA;8BAC+C;+BACd;6BAEf;yBAEL;oEACU;0BAIvB;4BAC0B;8BACqB;4BACxB;wBAOvB;4BAOA;;;;;;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;IACpBC,MAAMC,wBAAU,CAACC,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAUA;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQC,sCAA0B;QAClCC,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXH,QAAQI,6CAAiC;QACzCF,QAAQ;YAAC;YAAU;YAAc;SAAa;IAChD;IACAG,WAAW;QACTL,QAAQM,2CAA+B;QACvCJ,QAAQ,EAAE;IACZ;IACAK,SAAS;QACPP,QAAQQ,yCAA6B;QACrCN,QAAQ;YAAC;YAAU;YAAW;YAAU;SAAU;IACpD;AACF;AAIO,MAA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,EAAC3H;YACX;QACF;QACA,IAAI,CAAC8C,SAAS,GAAGA;QAEjB,IAAI,CAACnB,OAAO,GAAGiG,IAAAA,yCAA+B,EAC5C,IAAI,CAACzF,SAAS,CAACyD,IAAI,CAAC,IAAI,GACxB,OAAOiC,QAAQC,aAAajC;YAC1B,MAAM5F,OAAO,IAAI,CAAC4D,QAAQ,CAACsB,GAAG,CAAC0C;YAC/B,uFAAuF;YACvF,MAAME,UAAU9H,MAAMuD,OAAO,CAACsE,YAAY;YAC1CE,IAAAA,aAAM,EACJD,YAAYvB,WACZ,CAAC,GAAG,EAAEsB,YAAY,4BAA4B,EAAED,OAAO,CAAC;YAE1D,mCAAmC;YACnC,IAAI7G,SAAS,MAAM,IAAI,CAAC0D,oBAAoB,CAACmD,QAAQ,IACnDE,QAAQlC;YAGV,0EAA0E;YAC1E,IAAI7E,WAAWwF,WAAW;gBACxBxF,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOgF,IAAAA,kBAAW,EAAChF;YACrB,EAAE,OAAOhB,OAAO;gBACd,MAAM,IAAIiI,UACR,CAAC,sCAAsC,EAAEjI,MAAMb,OAAO,CAAC+I,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAACpD,WAAW,CAACc,IAAI,CAAC,IAAI;IAE9B;AAuWF"}
1
+ {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/index.d.ts\" />\nimport { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport type { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport { SNAP_EXPORT_NAMES, logError } from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';\nimport { createIdRemapMiddleware } from 'json-rpc-engine';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\n\nimport { log } from '../logging';\nimport EEOpenRPCDocument from '../openrpc.json';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n constructError,\n proxyStreamProvider,\n withTeardown,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n 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\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, 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 = 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 // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw new TypeError(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const constructedError = constructError(error);\n const serializedError = serializeError(constructedError, {\n fallbackError,\n shouldIncludeStack: false,\n });\n\n // We're setting it this way to avoid sentData.stack = undefined\n const sentData: Json = { ...data, stack: constructedError?.stack ?? null };\n\n this.notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: sentData,\n },\n },\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw new Error('Command stream received a non-JSON-RPC request.');\n }\n\n const { id, method, params } = message;\n if (method === 'rpc.discover') {\n this.respond(id, {\n result: EEOpenRPCDocument,\n });\n return;\n }\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n this.respond(id, {\n error: ethErrors.rpc\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n this.respond(id, {\n error: ethErrors.rpc\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw new Error('JSON-RPC responses must be JSON serializable objects.');\n }\n\n this.commandStream.write({\n ...requestObject,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments?: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments(\n snap,\n ethereum,\n snapId,\n _endowments,\n );\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n throw new Error(\n `Error while running snap '${snapId}': ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the Snap before we could register\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n 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 assertSnapOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n assertEthereumOutboundRequest(args);\n const sanitizedArgs = getSafeJson(args);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(\n originalRequest(sanitizedArgs as unknown as RequestArguments),\n this as any,\n );\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw new Error(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n ethErrors.rpc.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","constructedError","constructError","serializedError","serializeError","shouldIncludeStack","sentData","stack","notify","method","onCommandRequest","isJsonRpcRequest","Error","id","respond","result","EEOpenRPCDocument","hasProperty","ethErrors","methodNotFound","serialize","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","methods","rpcError","requestObject","isValidJson","isObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validateExport","originalRequest","request","bind","args","assertSnapOutboundRequest","sanitizedArgs","getSafeJson","withTeardown","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","size","lastTeardown","Map","on","catch","logError","getCommandMethodImplementations","target","handlerName","handler","assert","TypeError","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BAoGnDA;;;eAAAA;;;2BAnGkB;4BAQa;uBAcrC;8BAC+C;+BACd;6BAEf;yBAEL;oEACU;0BAEkB;4BACf;8BACqB;4BACxB;wBAOvB;4BAOA;;;;;;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;IACpBC,MAAMC,wBAAU,CAACC,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAUA;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQC,sCAA0B;QAClCC,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXH,QAAQI,6CAAiC;QACzCF,QAAQ;Y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pB,IAAI,CAACxF,aAAa,GAAGA;QACrB,IAAI,CAACA,aAAa,CAACyF,EAAE,CAAC,QAAQ,CAACxH;YAC7B,IAAI,CAACU,gBAAgB,CAACV,MAAMyH,KAAK,CAAC,CAAC1H;gBACjC,qCAAqC;gBACrC2H,IAAAA,oBAAQ,EAAC3H;YACX;QACF;QACA,IAAI,CAAC8C,SAAS,GAAGA;QAEjB,IAAI,CAACnB,OAAO,GAAGiG,IAAAA,yCAA+B,EAC5C,IAAI,CAACzF,SAAS,CAACyD,IAAI,CAAC,IAAI,GACxB,OAAOiC,QAAQC,aAAajC;YAC1B,MAAM5F,OAAO,IAAI,CAAC4D,QAAQ,CAACsB,GAAG,CAAC0C;YAC/B,uFAAuF;YACvF,MAAME,UAAU9H,MAAMuD,OAAO,CAACsE,YAAY;YAC1CE,IAAAA,aAAM,EACJD,YAAYvB,WACZ,CAAC,GAAG,EAAEsB,YAAY,4BAA4B,EAAED,OAAO,CAAC;YAE1D,mCAAmC;YACnC,IAAI7G,SAAS,MAAM,IAAI,CAAC0D,oBAAoB,CAACmD,QAAQ,IACnDE,QAAQlC;YAGV,0EAA0E;YAC1E,IAAI7E,WAAWwF,WAAW;gBACxBxF,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAOgF,IAAAA,kBAAW,EAAChF;YACrB,EAAE,OAAOhB,OAAO;gBACd,MAAM,IAAIiI,UACR,CAAC,sCAAsC,EAAEjI,MAAMb,OAAO,CAAC+I,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAACpD,WAAW,CAACc,IAAI,CAAC,IAAI;IAE9B;AAuWF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport {\n assertIsOnTransactionRequestArguments,\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n SnapRpc,\n Terminate,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n\n case HandlerType.OnRpcRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n return { request };\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnRpcRequest","OnCronjob","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IA4BgBA,mBAAmB;eAAnBA;;IAyCAC,+BAA+B;eAA/BA;;;4BArEY;uBACK;4BAU1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QAEA,KAAKN,uBAAW,CAACO,YAAY;YAC3B,OAAO;gBAAEV;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACQ,SAAS;YACxB,OAAO;gBAAET;YAAQ;QAEnB;YACE,OAAOU,IAAAA,uBAAgB,EAACX;IAC5B;AACF;AAaO,SAASF,gCACdc,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQxB,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMY,WACLW,QACAxB,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n SnapRpc,\n Terminate,\n} from './validation';\nimport { assertIsOnTransactionRequestArguments } from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n\n case HandlerType.OnRpcRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n return { request };\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnRpcRequest","OnCronjob","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IA4BgBA,mBAAmB;eAAnBA;;IAyCAC,+BAA+B;eAA/BA;;;4BArEY;uBACK;4BAUqB;AAiB/C,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QAEA,KAAKN,uBAAW,CAACO,YAAY;YAC3B,OAAO;gBAAEV;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACQ,SAAS;YACxB,OAAO;gBAAET;YAAQ;QAEnB;YACE,OAAOU,IAAAA,uBAAgB,EAACX;IAC5B;AACF;AAaO,SAASF,gCACdc,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQxB,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMY,WACLW,QACAxB,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/commonEndowmentFactory.ts"],"sourcesContent":["import { SnapId } from '@metamask/snaps-utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactoryOptions = {\n snapId?: SnapId;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n consoleEndowment,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"],"names":["commonEndowments","endowment","AbortController","name","AbortSignal","ArrayBuffer","atob","bind","BigInt","BigInt64Array","BigUint64Array","btoa","DataView","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","URL","WebAssembly","buildCommonEndowments","endowmentFactories","crypto","interval","math","network","timeout","textDecoder","textEncoder","date","consoleEndowment","forEach","endowmentSpecification","names","factory","boundEndowment","rootRealmGlobal","harden","push"],"mappings":";;;;+BA4FA;;;eAAA;;;8BA1FgC;gEACH;+DACV;6DACF;iEACI;6DACJ;gEACG;oEACI;oEACA;gEACJ;;;;;;AAiBpB,6BAA6B;AAC7B,MAAMA,mBAAmD;IACvD;QAAEC,WAAWC;QAAiBC,MAAM;IAAkB;IACtD;QAAEF,WAAWG;QAAaD,MAAM;IAAc;IAC9C;QAAEF,WAAWI;QAAaF,MAAM;IAAc;IAC9C;QAAEF,WAAWK;QAAMH,MAAM;QAAQI,MAAM;IAAK;IAC5C;QAAEN,WAAWO;QAAQL,MAAM;IAAS;IACpC;QAAEF,WAAWQ;QAAeN,MAAM;IAAgB;IAClD;QAAEF,WAAWS;QAAgBP,MAAM;IAAiB;IACpD;QAAEF,WAAWU;QAAMR,MAAM;QAAQI,MAAM;IAAK;IAC5C;QAAEN,WAAWW;QAAUT,MAAM;IAAW;IACxC;QAAEF,WAAWY;QAAcV,MAAM;IAAe;IAChD;QAAEF,WAAWa;QAAcX,MAAM;IAAe;IAChD;QAAEF,WAAWc;QAAWZ,MAAM;IAAY;IAC1C;QAAEF,WAAWe;QAAYb,MAAM;IAAa;IAC5C;QAAEF,WAAWgB;QAAYd,MAAM;IAAa;IAC5C;QAAEF,WAAWiB;QAAYf,MAAM;IAAa;IAC5C;QAAEF,WAAWkB;QAAmBhB,MAAM;IAAoB;IAC1D;QAAEF,WAAWmB;QAAajB,MAAM;IAAc;IAC9C;QAAEF,WAAWoB;QAAalB,MAAM;IAAc;IAC9C;QAAEF,WAAWqB;QAAKnB,MAAM;IAAM;IAC9B;QAAEF,WAAWsB;QAAapB,MAAM;IAAc;CAC/C;AAED;;;;;;CAMC,GACD,MAAMqB,wBAAwB;IAC5B,MAAMC,qBAAyC;QAC7CC,eAAM;QACNC,iBAAQ;QACRC,aAAI;QACJC,gBAAO;QACPC,gBAAO;QACPC,oBAAW;QACXC,oBAAW;QACXC,aAAI;QACJC,gBAAgB;KACjB;IAEDlC,iBAAiBmC,OAAO,CAAC,CAACC;QACxB,MAAMnC,YAAY;YAChBoC,OAAO;gBAACD,uBAAuBjC,IAAI;aAAC;YACpCmC,SAAS;gBACP,MAAMC,iBACJ,OAAOH,uBAAuBnC,SAAS,KAAK,cAC5CmC,uBAAuB7B,IAAI,GACvB6B,uBAAuBnC,SAAS,CAACM,IAAI,CAACiC,6BAAe,IACrDJ,uBAAuBnC,SAAS;gBACtC,OAAO;oBACL,CAACmC,uBAAuBjC,IAAI,CAAC,EAAEsC,OAAOF;gBACxC;YACF;QACF;QACAd,mBAAmBiB,IAAI,CAACzC;IAC1B;IAEA,OAAOwB;AACT;MAEA,WAAeD"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/commonEndowmentFactory.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactoryOptions = {\n snapId?: SnapId;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n consoleEndowment,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"],"names":["commonEndowments","endowment","AbortController","name","AbortSignal","ArrayBuffer","atob","bind","BigInt","BigInt64Array","BigUint64Array","btoa","DataView","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","URL","WebAssembly","buildCommonEndowments","endowmentFactories","crypto","interval","math","network","timeout","textDecoder","textEncoder","date","consoleEndowment","forEach","endowmentSpecification","names","factory","boundEndowment","rootRealmGlobal","harden","push"],"mappings":";;;;+BA4FA;;;eAAA;;;8BA1FgC;gEACH;+DACV;6DACF;iEACI;6DACJ;gEACG;oEACI;oEACA;gEACJ;;;;;;AAiBpB,6BAA6B;AAC7B,MAAMA,mBAAmD;IACvD;QAAEC,WAAWC;QAAiBC,MAAM;IAAkB;IACtD;QAAEF,WAAWG;QAAaD,MAAM;IAAc;IAC9C;QAAEF,WAAWI;QAAaF,MAAM;IAAc;IAC9C;QAAEF,WAAWK;QAAMH,MAAM;QAAQI,MAAM;IAAK;IAC5C;QAAEN,WAAWO;QAAQL,MAAM;IAAS;IACpC;QAAEF,WAAWQ;QAAeN,MAAM;IAAgB;IAClD;QAAEF,WAAWS;QAAgBP,MAAM;IAAiB;IACpD;QAAEF,WAAWU;QAAMR,MAAM;QAAQI,MAAM;IAAK;IAC5C;QAAEN,WAAWW;QAAUT,MAAM;IAAW;IACxC;QAAEF,WAAWY;QAAcV,MAAM;IAAe;IAChD;QAAEF,WAAWa;QAAcX,MAAM;IAAe;IAChD;QAAEF,WAAWc;QAAWZ,MAAM;IAAY;IAC1C;QAAEF,WAAWe;QAAYb,MAAM;IAAa;IAC5C;QAAEF,WAAWgB;QAAYd,MAAM;IAAa;IAC5C;QAAEF,WAAWiB;QAAYf,MAAM;IAAa;IAC5C;QAAEF,WAAWkB;QAAmBhB,MAAM;IAAoB;IAC1D;QAAEF,WAAWmB;QAAajB,MAAM;IAAc;IAC9C;QAAEF,WAAWoB;QAAalB,MAAM;IAAc;IAC9C;QAAEF,WAAWqB;QAAKnB,MAAM;IAAM;IAC9B;QAAEF,WAAWsB;QAAapB,MAAM;IAAc;CAC/C;AAED;;;;;;CAMC,GACD,MAAMqB,wBAAwB;IAC5B,MAAMC,qBAAyC;QAC7CC,eAAM;QACNC,iBAAQ;QACRC,aAAI;QACJC,gBAAO;QACPC,gBAAO;QACPC,oBAAW;QACXC,oBAAW;QACXC,aAAI;QACJC,gBAAgB;KACjB;IAEDlC,iBAAiBmC,OAAO,CAAC,CAACC;QACxB,MAAMnC,YAAY;YAChBoC,OAAO;gBAACD,uBAAuBjC,IAAI;aAAC;YACpCmC,SAAS;gBACP,MAAMC,iBACJ,OAAOH,uBAAuBnC,SAAS,KAAK,cAC5CmC,uBAAuB7B,IAAI,GACvB6B,uBAAuBnC,SAAS,CAACM,IAAI,CAACiC,6BAAe,IACrDJ,uBAAuBnC,SAAS;gBACtC,OAAO;oBACL,CAACmC,uBAAuBjC,IAAI,CAAC,EAAEsC,OAAOF;gBACxC;YACF;QACF;QACAd,mBAAmBiB,IAAI,CAACzC;IAC1B;IAEA,OAAOwB;AACT;MAEA,WAAeD"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/console.ts"],"sourcesContent":["import { SnapId } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\nexport const consoleAttenuatedMethods = new Set([\n 'log',\n 'assert',\n 'error',\n 'debug',\n 'info',\n 'warn',\n]);\n\n/**\n * A set of all the `console` values that will be passed to the snap. This has\n * all the values that are available in both the browser and Node.js.\n */\nexport const consoleMethods = new Set([\n 'debug',\n 'error',\n 'info',\n 'log',\n 'warn',\n 'dir',\n 'dirxml',\n 'table',\n 'trace',\n 'group',\n 'groupCollapsed',\n 'groupEnd',\n 'clear',\n 'count',\n 'countReset',\n 'assert',\n 'profile',\n 'profileEnd',\n 'time',\n 'timeLog',\n 'timeEnd',\n 'timeStamp',\n 'context',\n]);\n\nconst consoleFunctions = ['log', 'error', 'debug', 'info', 'warn'] as const;\n\ntype ConsoleFunctions = {\n [Key in typeof consoleFunctions[number]]: typeof rootRealmGlobal.console[Key];\n};\n\n/**\n * Gets the appropriate (prepended) message to pass to one of the attenuated\n * method calls.\n *\n * @param snapId - Id of the snap that we're getting a message for.\n * @param message - The id of the snap that will interact with the endowment.\n * @param args - The array of additional arguments.\n * @returns An array of arguments to be passed into an attenuated console method call.\n */\nfunction getMessage(snapId: SnapId, message: unknown, ...args: unknown[]) {\n const prefix = `[Snap: ${snapId}]`;\n\n // If the first argument is a string, prepend the prefix to the message, and keep the\n // rest of the arguments as-is.\n if (typeof message === 'string') {\n return [`${prefix} ${message}`, ...args];\n }\n\n // Otherwise, the `message` is an object, array, etc., so add the prefix as a separate\n // message to the arguments.\n return [prefix, message, ...args];\n}\n\n/**\n * Create a a {@link console} object, with the same properties as the global\n * {@link console} object, but with some methods replaced.\n *\n * @param options - Factory options used in construction of the endowment.\n * @param options.snapId - The id of the snap that will interact with the endowment.\n * @returns The {@link console} object with the replaced methods.\n */\nfunction createConsole({ snapId }: EndowmentFactoryOptions = {}) {\n assert(snapId !== undefined);\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.console,\n ) as (keyof typeof console)[];\n\n const attenuatedConsole = keys.reduce((target, key) => {\n if (consoleMethods.has(key) && !consoleAttenuatedMethods.has(key)) {\n return { ...target, [key]: rootRealmGlobal.console[key] };\n }\n\n return target;\n }, {});\n\n return harden({\n console: {\n ...attenuatedConsole,\n assert: (\n value: any,\n message?: string | undefined,\n ...optionalParams: any[]\n ) => {\n rootRealmGlobal.console.assert(\n value,\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n ...consoleFunctions.reduce<ConsoleFunctions>((target, key) => {\n return {\n ...target,\n [key]: (message?: unknown, ...optionalParams: any[]) => {\n rootRealmGlobal.console[key](\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n };\n }, {} as ConsoleFunctions),\n },\n });\n}\n\nconst endowmentModule = {\n names: ['console'] as const,\n factory: createConsole,\n};\n\nexport default endowmentModule;\n"],"names":["consoleAttenuatedMethods","consoleMethods","Set","consoleFunctions","getMessage","snapId","message","args","prefix","createConsole","assert","undefined","keys","Object","getOwnPropertyNames","rootRealmGlobal","console","attenuatedConsole","reduce","target","key","has","harden","value","optionalParams","endowmentModule","names","factory"],"mappings":";;;;;;;;;;;IAMaA,wBAAwB;eAAxBA;;IAaAC,cAAc;eAAdA;;IA6Gb,OAA+B;eAA/B;;;uBA/HuB;8BAES;AAGzB,MAAMD,2BAA2B,IAAIE,IAAI;IAC9C;IACA;IACA;IACA;IACA;IACA;CACD;AAMM,MAAMD,iBAAiB,IAAIC,IAAI;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAMC,mBAAmB;IAAC;IAAO;IAAS;IAAS;IAAQ;CAAO;AAMlE;;;;;;;;CAQC,GACD,SAASC,WAAWC,MAAc,EAAEC,OAAgB,EAAE,GAAGC,IAAe;IACtE,MAAMC,SAAS,CAAC,OAAO,EAAEH,OAAO,CAAC,CAAC;IAElC,qFAAqF;IACrF,+BAA+B;IAC/B,IAAI,OAAOC,YAAY,UAAU;QAC/B,OAAO;YAAC,CAAC,EAAEE,OAAO,CAAC,EAAEF,QAAQ,CAAC;eAAKC;SAAK;IAC1C;IAEA,sFAAsF;IACtF,4BAA4B;IAC5B,OAAO;QAACC;QAAQF;WAAYC;KAAK;AACnC;AAEA;;;;;;;CAOC,GACD,SAASE,cAAc,EAAEJ,MAAM,EAA2B,GAAG,CAAC,CAAC;IAC7DK,IAAAA,aAAM,EAACL,WAAWM;IAClB,MAAMC,OAAOC,OAAOC,mBAAmB,CACrCC,6BAAe,CAACC,OAAO;IAGzB,MAAMC,oBAAoBL,KAAKM,MAAM,CAAC,CAACC,QAAQC;QAC7C,IAAInB,eAAeoB,GAAG,CAACD,QAAQ,CAACpB,yBAAyBqB,GAAG,CAACD,MAAM;YACjE,OAAO;gBAAE,GAAGD,MAAM;gBAAE,CAACC,IAAI,EAAEL,6BAAe,CAACC,OAAO,CAACI,IAAI;YAAC;QAC1D;QAEA,OAAOD;IACT,GAAG,CAAC;IAEJ,OAAOG,OAAO;QACZN,SAAS;YACP,GAAGC,iBAAiB;YACpBP,QAAQ,CACNa,OACAjB,SACA,GAAGkB;gBAEHT,6BAAe,CAACC,OAAO,CAACN,MAAM,CAC5Ba,UACGnB,WAAWC,QAAQC,YAAYkB;YAEtC;YACA,GAAGrB,iBAAiBe,MAAM,CAAmB,CAACC,QAAQC;gBACpD,OAAO;oBACL,GAAGD,MAAM;oBACT,CAACC,IAAI,EAAE,CAACd,SAAmB,GAAGkB;wBAC5BT,6BAAe,CAACC,OAAO,CAACI,IAAI,IACvBhB,WAAWC,QAAQC,YAAYkB;oBAEtC;gBACF;YACF,GAAG,CAAC,EAAsB;QAC5B;IACF;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAASlB;AACX;MAEA,WAAegB"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/console.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\nexport const consoleAttenuatedMethods = new Set([\n 'log',\n 'assert',\n 'error',\n 'debug',\n 'info',\n 'warn',\n]);\n\n/**\n * A set of all the `console` values that will be passed to the snap. This has\n * all the values that are available in both the browser and Node.js.\n */\nexport const consoleMethods = new Set([\n 'debug',\n 'error',\n 'info',\n 'log',\n 'warn',\n 'dir',\n 'dirxml',\n 'table',\n 'trace',\n 'group',\n 'groupCollapsed',\n 'groupEnd',\n 'clear',\n 'count',\n 'countReset',\n 'assert',\n 'profile',\n 'profileEnd',\n 'time',\n 'timeLog',\n 'timeEnd',\n 'timeStamp',\n 'context',\n]);\n\nconst consoleFunctions = ['log', 'error', 'debug', 'info', 'warn'] as const;\n\ntype ConsoleFunctions = {\n [Key in typeof consoleFunctions[number]]: typeof rootRealmGlobal.console[Key];\n};\n\n/**\n * Gets the appropriate (prepended) message to pass to one of the attenuated\n * method calls.\n *\n * @param snapId - Id of the snap that we're getting a message for.\n * @param message - The id of the snap that will interact with the endowment.\n * @param args - The array of additional arguments.\n * @returns An array of arguments to be passed into an attenuated console method call.\n */\nfunction getMessage(snapId: SnapId, message: unknown, ...args: unknown[]) {\n const prefix = `[Snap: ${snapId}]`;\n\n // If the first argument is a string, prepend the prefix to the message, and keep the\n // rest of the arguments as-is.\n if (typeof message === 'string') {\n return [`${prefix} ${message}`, ...args];\n }\n\n // Otherwise, the `message` is an object, array, etc., so add the prefix as a separate\n // message to the arguments.\n return [prefix, message, ...args];\n}\n\n/**\n * Create a a {@link console} object, with the same properties as the global\n * {@link console} object, but with some methods replaced.\n *\n * @param options - Factory options used in construction of the endowment.\n * @param options.snapId - The id of the snap that will interact with the endowment.\n * @returns The {@link console} object with the replaced methods.\n */\nfunction createConsole({ snapId }: EndowmentFactoryOptions = {}) {\n assert(snapId !== undefined);\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.console,\n ) as (keyof typeof console)[];\n\n const attenuatedConsole = keys.reduce((target, key) => {\n if (consoleMethods.has(key) && !consoleAttenuatedMethods.has(key)) {\n return { ...target, [key]: rootRealmGlobal.console[key] };\n }\n\n return target;\n }, {});\n\n return harden({\n console: {\n ...attenuatedConsole,\n assert: (\n value: any,\n message?: string | undefined,\n ...optionalParams: any[]\n ) => {\n rootRealmGlobal.console.assert(\n value,\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n ...consoleFunctions.reduce<ConsoleFunctions>((target, key) => {\n return {\n ...target,\n [key]: (message?: unknown, ...optionalParams: any[]) => {\n rootRealmGlobal.console[key](\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n };\n }, {} as ConsoleFunctions),\n },\n });\n}\n\nconst endowmentModule = {\n names: ['console'] as const,\n factory: createConsole,\n};\n\nexport default endowmentModule;\n"],"names":["consoleAttenuatedMethods","consoleMethods","Set","consoleFunctions","getMessage","snapId","message","args","prefix","createConsole","assert","undefined","keys","Object","getOwnPropertyNames","rootRealmGlobal","console","attenuatedConsole","reduce","target","key","has","harden","value","optionalParams","endowmentModule","names","factory"],"mappings":";;;;;;;;;;;IAMaA,wBAAwB;eAAxBA;;IAaAC,cAAc;eAAdA;;IA6Gb,OAA+B;eAA/B;;;uBA/HuB;8BAES;AAGzB,MAAMD,2BAA2B,IAAIE,IAAI;IAC9C;IACA;IACA;IACA;IACA;IACA;CACD;AAMM,MAAMD,iBAAiB,IAAIC,IAAI;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAMC,mBAAmB;IAAC;IAAO;IAAS;IAAS;IAAQ;CAAO;AAMlE;;;;;;;;CAQC,GACD,SAASC,WAAWC,MAAc,EAAEC,OAAgB,EAAE,GAAGC,IAAe;IACtE,MAAMC,SAAS,CAAC,OAAO,EAAEH,OAAO,CAAC,CAAC;IAElC,qFAAqF;IACrF,+BAA+B;IAC/B,IAAI,OAAOC,YAAY,UAAU;QAC/B,OAAO;YAAC,CAAC,EAAEE,OAAO,CAAC,EAAEF,QAAQ,CAAC;eAAKC;SAAK;IAC1C;IAEA,sFAAsF;IACtF,4BAA4B;IAC5B,OAAO;QAACC;QAAQF;WAAYC;KAAK;AACnC;AAEA;;;;;;;CAOC,GACD,SAASE,cAAc,EAAEJ,MAAM,EAA2B,GAAG,CAAC,CAAC;IAC7DK,IAAAA,aAAM,EAACL,WAAWM;IAClB,MAAMC,OAAOC,OAAOC,mBAAmB,CACrCC,6BAAe,CAACC,OAAO;IAGzB,MAAMC,oBAAoBL,KAAKM,MAAM,CAAC,CAACC,QAAQC;QAC7C,IAAInB,eAAeoB,GAAG,CAACD,QAAQ,CAACpB,yBAAyBqB,GAAG,CAACD,MAAM;YACjE,OAAO;gBAAE,GAAGD,MAAM;gBAAE,CAACC,IAAI,EAAEL,6BAAe,CAACC,OAAO,CAACI,IAAI;YAAC;QAC1D;QAEA,OAAOD;IACT,GAAG,CAAC;IAEJ,OAAOG,OAAO;QACZN,SAAS;YACP,GAAGC,iBAAiB;YACpBP,QAAQ,CACNa,OACAjB,SACA,GAAGkB;gBAEHT,6BAAe,CAACC,OAAO,CAACN,MAAM,CAC5Ba,UACGnB,WAAWC,QAAQC,YAAYkB;YAEtC;YACA,GAAGrB,iBAAiBe,MAAM,CAAmB,CAACC,QAAQC;gBACpD,OAAO;oBACL,GAAGD,MAAM;oBACT,CAACC,IAAI,EAAE,CAACd,SAAmB,GAAGkB;wBAC5BT,6BAAe,CAACC,OAAO,CAACI,IAAI,IACvBhB,WAAWC,QAAQC,YAAYkB;oBAEtC;gBACF;YACF,GAAG,CAAC,EAAsB;QAC5B;IACF;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAASlB;AACX;MAEA,WAAegB"}
@@ -26,7 +26,7 @@ const createCrypto = ()=>{
26
26
  }
27
27
  // For now, we expose the experimental webcrypto API for Node.js execution environments
28
28
  // TODO: Figure out if this is enough long-term or if we should use a polyfill.
29
- /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */ const crypto = require('crypto').webcrypto;
29
+ /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, n/global-require */ const crypto = require('crypto').webcrypto;
30
30
  return {
31
31
  crypto: harden(crypto),
32
32
  SubtleCrypto: harden(crypto.subtle.constructor)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/crypto.ts"],"sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\nexport const createCrypto = () => {\n if (\n 'crypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.crypto === 'object' &&\n 'SubtleCrypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.SubtleCrypto === 'function'\n ) {\n return {\n crypto: harden(rootRealmGlobal.crypto),\n SubtleCrypto: harden(rootRealmGlobal.SubtleCrypto),\n };\n }\n // For now, we expose the experimental webcrypto API for Node.js execution environments\n // TODO: Figure out if this is enough long-term or if we should use a polyfill.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */\n const crypto = require('crypto').webcrypto;\n return {\n crypto: harden(crypto),\n SubtleCrypto: harden(crypto.subtle.constructor),\n } as const;\n};\n\nconst endowmentModule = {\n names: ['crypto', 'SubtleCrypto'] as const,\n factory: createCrypto,\n};\nexport default endowmentModule;\n"],"names":["createCrypto","rootRealmGlobal","crypto","SubtleCrypto","harden","require","webcrypto","subtle","constructor","endowmentModule","names","factory"],"mappings":";;;;;;;;;;;IAEaA,YAAY;eAAZA;;IA0Bb,OAA+B;eAA/B;;;8BA5BgC;AAEzB,MAAMA,eAAe;IAC1B,IACE,YAAYC,6BAAe,IAC3B,OAAOA,6BAAe,CAACC,MAAM,KAAK,YAClC,kBAAkBD,6BAAe,IACjC,OAAOA,6BAAe,CAACE,YAAY,KAAK,YACxC;QACA,OAAO;YACLD,QAAQE,OAAOH,6BAAe,CAACC,MAAM;YACrCC,cAAcC,OAAOH,6BAAe,CAACE,YAAY;QACnD;IACF;IACA,uFAAuF;IACvF,+EAA+E;IAC/E,2HAA2H,GAC3H,MAAMD,SAASG,QAAQ,UAAUC,SAAS;IAC1C,OAAO;QACLJ,QAAQE,OAAOF;QACfC,cAAcC,OAAOF,OAAOK,MAAM,CAACC,WAAW;IAChD;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;QAAU;KAAe;IACjCC,SAASX;AACX;MACA,WAAeS"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/crypto.ts"],"sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\nexport const createCrypto = () => {\n if (\n 'crypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.crypto === 'object' &&\n 'SubtleCrypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.SubtleCrypto === 'function'\n ) {\n return {\n crypto: harden(rootRealmGlobal.crypto),\n SubtleCrypto: harden(rootRealmGlobal.SubtleCrypto),\n };\n }\n // For now, we expose the experimental webcrypto API for Node.js execution environments\n // TODO: Figure out if this is enough long-term or if we should use a polyfill.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, n/global-require */\n const crypto = require('crypto').webcrypto;\n return {\n crypto: harden(crypto),\n SubtleCrypto: harden(crypto.subtle.constructor),\n } as const;\n};\n\nconst endowmentModule = {\n names: ['crypto', 'SubtleCrypto'] as const,\n factory: createCrypto,\n};\nexport default endowmentModule;\n"],"names":["createCrypto","rootRealmGlobal","crypto","SubtleCrypto","harden","require","webcrypto","subtle","constructor","endowmentModule","names","factory"],"mappings":";;;;;;;;;;;IAEaA,YAAY;eAAZA;;IA0Bb,OAA+B;eAA/B;;;8BA5BgC;AAEzB,MAAMA,eAAe;IAC1B,IACE,YAAYC,6BAAe,IAC3B,OAAOA,6BAAe,CAACC,MAAM,KAAK,YAClC,kBAAkBD,6BAAe,IACjC,OAAOA,6BAAe,CAACE,YAAY,KAAK,YACxC;QACA,OAAO;YACLD,QAAQE,OAAOH,6BAAe,CAACC,MAAM;YACrCC,cAAcC,OAAOH,6BAAe,CAACE,YAAY;QACnD;IACF;IACA,uFAAuF;IACvF,+EAA+E;IAC/E,wHAAwH,GACxH,MAAMD,SAASG,QAAQ,UAAUC,SAAS;IAC1C,OAAO;QACLJ,QAAQE,OAAOF;QACfC,cAAcC,OAAOF,OAAOK,MAAM,CAACC,WAAW;IAChD;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;QAAU;KAAe;IACjCC,SAASX;AACX;MACA,WAAeS"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import { StreamProvider } from '@metamask/providers';\nimport { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport { SnapId, logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport buildCommonEndowments, {\n EndowmentFactoryOptions,\n} from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n snapId: SnapId,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw 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"],"names":["createEndowments","registeredEndowments","buildCommonEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","snap","ethereum","snapId","endowments","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","hasProperty","teardownFunction","endowment","get","Object","assign","push","rootRealmGlobal","logWarning","globalValue","Error","teardown","Promise","all","map"],"mappings":";;;;+BAqDgBA;;;eAAAA;;;4BAnDmB;uBACP;8BAEI;+EAGzB;;;;;;AAeP;;CAEC,GACD,MAAMC,uBAAuBC,IAAAA,+BAAqB;AAElD;;;;CAIC,GACD,MAAMC,qBAAqBF,qBAAqBG,MAAM,CAAC,CAACC,WAAWC;IACjEA,QAAQC,KAAK,CAACC,OAAO,CAAC,CAACC;QACrBJ,UAAUK,GAAG,CAACD,MAAMH,QAAQK,OAAO;IACrC;IACA,OAAON;AACT,GAAG,IAAIO;AAeA,SAASZ,iBACda,IAAuB,EACvBC,QAAwB,EACxBC,MAAc,EACdC,aAAuB,EAAE;IAEzB,MAAMC,uBAAgD,CAAC;IAEvD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAMC,SAASF,WAAWZ,MAAM,CAI9B,CAAC,EAAEe,aAAa,EAAEC,SAAS,EAAE,EAAEC;QAC7B,oEAAoE;QACpE,IAAIlB,mBAAmBmB,GAAG,CAACD,gBAAgB;YACzC,IAAI,CAACE,IAAAA,kBAAW,EAACN,sBAAsBI,gBAAgB;gBACrD,uEAAuE;gBACvE,gEAAgE;gBAChE,wEAAwE;gBACxE,4CAA4C;gBAC5C,2DAA2D;gBAE3D,mEAAmE;gBACnE,oEAAoE;gBACpE,MAAM,EAAEG,gBAAgB,EAAE,GAAGC,WAAW,GAAGtB,mBAAmBuB,GAAG,CAC/DL,eACC;oBAAEN;gBAAO;gBACZY,OAAOC,MAAM,CAACX,sBAAsBQ;gBACpC,IAAID,kBAAkB;oBACpBJ,UAAUS,IAAI,CAACL;gBACjB;YACF;YACAL,aAAa,CAACE,cAAc,GAAGJ,oBAAoB,CAACI,cAAc;QACpE,OAAO,IAAIA,kBAAkB,YAAY;YACvC,iDAAiD;YACjDF,aAAa,CAACE,cAAc,GAAGP;QACjC,OAAO,IAAIO,iBAAiBS,6BAAe,EAAE;YAC3CC,IAAAA,sBAAU,EAAC,CAAC,4BAA4B,EAAEV,cAAc,CAAC,CAAC;YAC1D,uEAAuE;YACvE,iBAAiB;YACjB,MAAMW,cAAc,AAACF,6BAAe,AAA4B,CAC9DT,cACD;YACDF,aAAa,CAACE,cAAc,GAAGW;QACjC,OAAO;YACL,uEAAuE;YACvE,oCAAoC;YACpC,MAAM,IAAIC,MAAM,CAAC,oBAAoB,EAAEZ,cAAc,EAAE,CAAC;QAC1D;QACA,OAAO;YAAEF;YAAeC;QAAU;IACpC,GACA;QACED,eAAe;YAAEN;QAAK;QACtBO,WAAW,EAAE;IACf;IAGF,MAAMc,WAAW;QACf,MAAMC,QAAQC,GAAG,CACflB,OAAOE,SAAS,CAACiB,GAAG,CAAC,CAACb,mBAAqBA;IAE/C;IACA,OAAO;QAAER,YAAYE,OAAOC,aAAa;QAAEe;IAAS;AACtD"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { SnapsGlobalObject } from '@metamask/rpc-methods';\nimport type { SnapId } from '@metamask/snaps-utils';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n snapId: SnapId,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw 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"],"names":["createEndowments","registeredEndowments","buildCommonEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","snap","ethereum","snapId","endowments","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","hasProperty","teardownFunction","endowment","get","Object","assign","push","rootRealmGlobal","logWarning","globalValue","Error","teardown","Promise","all","map"],"mappings":";;;;+BAqDgBA;;;eAAAA;;;4BAlDW;uBACC;8BAEI;+EAEE;;;;;;AAelC;;CAEC,GACD,MAAMC,uBAAuBC,IAAAA,+BAAqB;AAElD;;;;CAIC,GACD,MAAMC,qBAAqBF,qBAAqBG,MAAM,CAAC,CAACC,WAAWC;IACjEA,QAAQC,KAAK,CAACC,OAAO,CAAC,CAACC;QACrBJ,UAAUK,GAAG,CAACD,MAAMH,QAAQK,OAAO;IACrC;IACA,OAAON;AACT,GAAG,IAAIO;AAeA,SAASZ,iBACda,IAAuB,EACvBC,QAAwB,EACxBC,MAAc,EACdC,aAAuB,EAAE;IAEzB,MAAMC,uBAAgD,CAAC;IAEvD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAMC,SAASF,WAAWZ,MAAM,CAI9B,CAAC,EAAEe,aAAa,EAAEC,SAAS,EAAE,EAAEC;QAC7B,oEAAoE;QACpE,IAAIlB,mBAAmBmB,GAAG,CAACD,gBAAgB;YACzC,IAAI,CAACE,IAAAA,kBAAW,EAACN,sBAAsBI,gBAAgB;gBACrD,uEAAuE;gBACvE,gEAAgE;gBAChE,wEAAwE;gBACxE,4CAA4C;gBAC5C,2DAA2D;gBAE3D,mEAAmE;gBACnE,oEAAoE;gBACpE,MAAM,EAAEG,gBAAgB,EAAE,GAAGC,WAAW,GAAGtB,mBAAmBuB,GAAG,CAC/DL,eACC;oBAAEN;gBAAO;gBACZY,OAAOC,MAAM,CAACX,sBAAsBQ;gBACpC,IAAID,kBAAkB;oBACpBJ,UAAUS,IAAI,CAACL;gBACjB;YACF;YACAL,aAAa,CAACE,cAAc,GAAGJ,oBAAoB,CAACI,cAAc;QACpE,OAAO,IAAIA,kBAAkB,YAAY;YACvC,iDAAiD;YACjDF,aAAa,CAACE,cAAc,GAAGP;QACjC,OAAO,IAAIO,iBAAiBS,6BAAe,EAAE;YAC3CC,IAAAA,sBAAU,EAAC,CAAC,4BAA4B,EAAEV,cAAc,CAAC,CAAC;YAC1D,uEAAuE;YACvE,iBAAiB;YACjB,MAAMW,cAAc,AAACF,6BAAe,AAA4B,CAC9DT,cACD;YACDF,aAAa,CAACE,cAAc,GAAGW;QACjC,OAAO;YACL,uEAAuE;YACvE,oCAAoC;YACpC,MAAM,IAAIC,MAAM,CAAC,oBAAoB,EAAEZ,cAAc,EAAE,CAAC;QAC1D;QACA,OAAO;YAAEF;YAAeC;QAAU;IACpC,GACA;QACED,eAAe;YAAEN;QAAK;QACtBO,WAAW,EAAE;IACf;IAGF,MAAMc,WAAW;QACf,MAAMC,QAAQC,GAAG,CACflB,OAAOE,SAAS,CAACiB,GAAG,CAAC,CAACb,mBAAqBA;IAE/C;IACA,OAAO;QAAER,YAAYE,OAAOC,aAAa;QAAEe;IAAS;AACtD"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/sortParams.ts"],"sourcesContent":["// original source sortParamKeys from: https://github.com/etclabscore/sig.tools/blob/master/src/postMessageServer/postMessageServer.ts#L75-L77\n\nimport { JsonRpcParams } from '@metamask/utils';\n\n/**\n * Deterministically sort JSON-RPC parameter keys. This makes it possible to\n * support both arrays and objects as parameters. Objects are sorted and turned\n * into arrays, for easier consumption by the snap.\n *\n * The order is defined by the `method` parameter.\n *\n * @param methodParams - The parameters of the JSON-RPC method, which\n * determines the ordering for the parameters.\n * @param params - JSON-RPC parameters as object or array.\n * @returns The values for the sorted keys. If `params` is not provided, this\n * returns an empty array. If `params` is an array, this returns the same\n * `params`.\n */\nexport const sortParamKeys = (\n methodParams: string[],\n params?: JsonRpcParams,\n) => {\n if (!params) {\n return [];\n }\n\n if (params instanceof Array) {\n return params;\n }\n\n const methodParamsOrder: { [k: string]: number } = methodParams.reduce(\n (paramsOrderObj, paramsName, i) => ({\n ...paramsOrderObj,\n [paramsName]: i,\n }),\n {},\n );\n\n return Object.entries(params)\n .sort(\n ([name1, _1], [name2, _2]) =>\n methodParamsOrder[name1] - methodParamsOrder[name2],\n )\n .map(([_, val]) => val);\n};\n"],"names":["sortParamKeys","methodParams","params","Array","methodParamsOrder","reduce","paramsOrderObj","paramsName","i","Object","entries","sort","name1","_1","name2","_2","map","_","val"],"mappings":"AAAA,8IAA8I;;;;;+BAkBjIA;;;eAAAA;;;AAAN,MAAMA,gBAAgB,CAC3BC,cACAC;IAEA,IAAI,CAACA,QAAQ;QACX,OAAO,EAAE;IACX;IAEA,IAAIA,kBAAkBC,OAAO;QAC3B,OAAOD;IACT;IAEA,MAAME,oBAA6CH,aAAaI,MAAM,CACpE,CAACC,gBAAgBC,YAAYC,IAAO,CAAA;YAClC,GAAGF,cAAc;YACjB,CAACC,WAAW,EAAEC;QAChB,CAAA,GACA,CAAC;IAGH,OAAOC,OAAOC,OAAO,CAACR,QACnBS,IAAI,CACH,CAAC,CAACC,OAAOC,GAAG,EAAE,CAACC,OAAOC,GAAG,GACvBX,iBAAiB,CAACQ,MAAM,GAAGR,iBAAiB,CAACU,MAAM,EAEtDE,GAAG,CAAC,CAAC,CAACC,GAAGC,IAAI,GAAKA;AACvB"}
1
+ {"version":3,"sources":["../../../src/common/sortParams.ts"],"sourcesContent":["// original source sortParamKeys from: https://github.com/etclabscore/sig.tools/blob/master/src/postMessageServer/postMessageServer.ts#L75-L77\n\nimport type { JsonRpcParams } from '@metamask/utils';\n\n/**\n * Deterministically sort JSON-RPC parameter keys. This makes it possible to\n * support both arrays and objects as parameters. Objects are sorted and turned\n * into arrays, for easier consumption by the snap.\n *\n * The order is defined by the `method` parameter.\n *\n * @param methodParams - The parameters of the JSON-RPC method, which\n * determines the ordering for the parameters.\n * @param params - JSON-RPC parameters as object or array.\n * @returns The values for the sorted keys. If `params` is not provided, this\n * returns an empty array. If `params` is an array, this returns the same\n * `params`.\n */\nexport const sortParamKeys = (\n methodParams: string[],\n params?: JsonRpcParams,\n) => {\n if (!params) {\n return [];\n }\n\n if (params instanceof Array) {\n return params;\n }\n\n const methodParamsOrder: { [k: string]: number } = methodParams.reduce(\n (paramsOrderObj, paramsName, i) => ({\n ...paramsOrderObj,\n [paramsName]: i,\n }),\n {},\n );\n\n return Object.entries(params)\n .sort(\n ([name1, _1], [name2, _2]) =>\n methodParamsOrder[name1] - methodParamsOrder[name2],\n )\n .map(([_, val]) => val);\n};\n"],"names":["sortParamKeys","methodParams","params","Array","methodParamsOrder","reduce","paramsOrderObj","paramsName","i","Object","entries","sort","name1","_1","name2","_2","map","_","val"],"mappings":"AAAA,8IAA8I;;;;;+BAkBjIA;;;eAAAA;;;AAAN,MAAMA,gBAAgB,CAC3BC,cACAC;IAEA,IAAI,CAACA,QAAQ;QACX,OAAO,EAAE;IACX;IAEA,IAAIA,kBAAkBC,OAAO;QAC3B,OAAOD;IACT;IAEA,MAAME,oBAA6CH,aAAaI,MAAM,CACpE,CAACC,gBAAgBC,YAAYC,IAAO,CAAA;YAClC,GAAGF,cAAc;YACjB,CAACC,WAAW,EAAEC;QAChB,CAAA,GACA,CAAC;IAGH,OAAOC,OAAOC,OAAO,CAACR,QACnBS,IAAI,CACH,CAAC,CAACC,OAAOC,GAAG,EAAE,CAACC,OAAOC,GAAG,GACvBX,iBAAiB,CAACQ,MAAM,GAAGR,iBAAiB,CAACU,MAAM,EAEtDE,GAAG,CAAC,CAAC,CAACC,GAAGC,IAAI,GAAKA;AACvB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/utils.ts"],"sourcesContent":["import { StreamProvider } from '@metamask/providers';\nimport { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { assert, assertStruct, JsonStruct } from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { log } from '../logging';\n\n/**\n * Takes an error that was thrown, determines if it is\n * an error object. If it is then it will return that. Otherwise,\n * an error object is created with the original error message.\n *\n * @param originalError - The error that was originally thrown.\n * @returns An error object.\n */\nexport function constructError(originalError: unknown) {\n let _originalError: Error | undefined;\n if (originalError instanceof Error) {\n _originalError = originalError;\n } else if (typeof originalError === 'string') {\n _originalError = new Error(originalError);\n // The stack is useless in this case.\n delete _originalError.stack;\n }\n return _originalError;\n}\n\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<T>(\n originalPromise: Promise<T>,\n teardownRef: { lastTeardown: number },\n): Promise<T> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<T>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that narrows down (attenuates) the fields available on\n * the StreamProvider and replaces the request implementation.\n *\n * @param provider - Instance of a StreamProvider to be limited.\n * @param request - Custom attenuated request object.\n * @returns Proxy to the StreamProvider instance.\n */\nexport function proxyStreamProvider(\n provider: StreamProvider,\n request: unknown,\n): StreamProvider {\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return (\n typeof prop === 'string' &&\n ['request', 'on', 'removeListener'].includes(prop)\n );\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return provider[prop];\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendRawTransaction',\n 'eth_sendTransaction',\n 'personal_sign',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n"],"names":["constructError","withTeardown","proxyStreamProvider","BLOCKED_RPC_METHODS","assertSnapOutboundRequest","assertEthereumOutboundRequest","originalError","_originalError","Error","stack","originalPromise","teardownRef","myTeardown","lastTeardown","Promise","resolve","reject","then","value","log","catch","reason","provider","request","proxy","Proxy","has","_target","prop","includes","get","undefined","Object","freeze","args","assert","String","prototype","startsWith","call","method","ethErrors","rpc","methodNotFound","data","assertStruct","JsonStruct"],"mappings":";;;;;;;;;;;IAegBA,cAAc;eAAdA;;IAsBMC,YAAY;eAAZA;;IAoCNC,mBAAmB;eAAnBA;;IA+BHC,mBAAmB;eAAnBA;;IA0BGC,yBAAyB;eAAzBA;;IAuBAC,6BAA6B;eAA7BA;;;uBAvJiC;8BACvB;yBAEN;AAUb,SAASL,eAAeM,aAAsB;IACnD,IAAIC;IACJ,IAAID,yBAAyBE,OAAO;QAClCD,iBAAiBD;IACnB,OAAO,IAAI,OAAOA,kBAAkB,UAAU;QAC5CC,iBAAiB,IAAIC,MAAMF;QAC3B,qCAAqC;QACrC,OAAOC,eAAeE,KAAK;IAC7B;IACA,OAAOF;AACT;AAYO,eAAeN,aACpBS,eAA2B,EAC3BC,WAAqC;IAErC,MAAMC,aAAaD,YAAYE,YAAY;IAC3C,OAAO,IAAIC,QAAW,CAACC,SAASC;QAC9BN,gBACGO,I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AM;QACrB;IACF;IAEFK,IAAAA,mBAAY,EAACX,MAAMY,iBAAU,EAAE;AACjC;AAOO,SAASzC,8BAA8B6B,IAAsB;IAClE,qDAAqD;IACrDC,IAAAA,aAAM,EACJ,CAACC,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACL,KAAKM,MAAM,EAAE,UAC/CC,uBAAS,CAACC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFL,IAAAA,aAAM,EACJ,CAAChC,oBAAoB0B,QAAQ,CAACK,KAAKM,MAAM,GACzCC,uBAAS,CAACC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFK,IAAAA,mBAAY,EAACX,MAAMY,iBAAU,EAAE;AACjC"}
1
+ {"version":3,"sources":["../../../src/common/utils.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { assert, assertStruct, JsonStruct } from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { log } from '../logging';\n\n/**\n * Takes an error that was thrown, determines if it is\n * an error object. If it is then it will return that. Otherwise,\n * an error object is created with the original error message.\n *\n * @param originalError - The error that was originally thrown.\n * @returns An error object.\n */\nexport function constructError(originalError: unknown) {\n let _originalError: Error | undefined;\n if (originalError instanceof Error) {\n _originalError = originalError;\n } else if (typeof originalError === 'string') {\n _originalError = new Error(originalError);\n // The stack is useless in this case.\n delete _originalError.stack;\n }\n return _originalError;\n}\n\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<Type>(\n originalPromise: Promise<Type>,\n teardownRef: { lastTeardown: number },\n): Promise<Type> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<Type>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that narrows down (attenuates) the fields available on\n * the StreamProvider and replaces the request implementation.\n *\n * @param provider - Instance of a StreamProvider to be limited.\n * @param request - Custom attenuated request object.\n * @returns Proxy to the StreamProvider instance.\n */\nexport function proxyStreamProvider(\n provider: StreamProvider,\n request: unknown,\n): StreamProvider {\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return (\n typeof prop === 'string' &&\n ['request', 'on', 'removeListener'].includes(prop)\n );\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return provider[prop];\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendRawTransaction',\n 'eth_sendTransaction',\n 'personal_sign',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n"],"names":["constructError","withTeardown","proxyStreamProvider","BLOCKED_RPC_METHODS","assertSnapOutboundRequest","assertEthereumOutboundRequest","originalError","_originalError","Error","stack","originalPromise","teardownRef","myTeardown","lastTeardown","Promise","resolve","reject","then","value","log","catch","reason","provider","request","proxy","Proxy","has","_target","prop","includes","get","undefined","Object","freeze","args","assert","String","prototype","startsWith","call","method","ethErrors","rpc","methodNotFound","data","assertStruct","JsonStruct"],"mappings":";;;;;;;;;;;IAegBA,cAAc;eAAdA;;IAsBMC,YAAY;eAAZA;;IAoCNC,mBAAmB;eAAnBA;;IA+BHC,mBAAmB;eAAnBA;;IA0BGC,yBAAyB;eAAzBA;;IAuBAC,6BAA6B;eAA7BA;;;uBAvJiC;8BACvB;yBAEN;AAUb,SAASL,eAAeM,aAAsB;IACn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IAC5EC,IAAAA,aAAM,EACJC,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACL,KAAKM,MAAM,EAAE,cAC5CJ,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACL,KAAKM,MAAM,EAAE,UAChD;IAEFL,IAAAA,aAAM,EACJ,CAAChC,oBAAoB0B,QAAQ,CAACK,KAAKM,MAAM,GACzCC,uBAAS,CAACC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFK,IAAAA,mBAAY,EAACX,MAAMY,iBAAU,EAAE;AACjC;AAOO,SAASzC,8BAA8B6B,IAAsB;IAClE,qDAAqD;IACrDC,IAAAA,aAAM,EACJ,CAACC,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACL,KAAKM,MAAM,EAAE,UAC/CC,uBAAS,CAACC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFL,IAAAA,aAAM,EACJ,CAAChC,oBAAoB0B,QAAQ,CAACK,KAAKM,MAAM,GACzCC,uBAAS,CAACC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFK,IAAAA,mBAAY,EAACX,MAAMY,iBAAU,EAAE;AACjC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { 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.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 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"],"names":["validateExport","JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","VALIDATION_FUNCTIONS","HandlerType","OnRpcRequest","validateFunctionExport","OnTransaction","OnCronjob","snapExport","type","validationFunction","assign","omit","JsonRpcRequestStruct","object","id","optional","JsonRpcIdStruct","string","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","params","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","OkResponseStruct","JsonRpcSuccessStruct","result","SnapRpcResponse"],"mappings":";;;;;;;;;;;IAoDgBA,cAAc;eAAdA;;IAKHC,6BAA6B;eAA7BA;;IAWAC,eAAe;eAAfA;;IASGC,WAAW;eAAXA;;IAUAC,iBAAiB;eAAjBA;;IAMHC,0BAA0B;eAA1BA;;IAIAC,+BAA+B;eAA/BA;;IAKAC,iCAAiC;eAAjCA;;IAMAC,6BAA6B;eAA7BA;;IA+BAC,mCAAmC;eAAnCA;;IAmBGC,qCAAqC;eAArCA;;;4BA9J2B;uBASpC;6BAgBA;AAEP,MAAMC,uBAAuB;IAC3B,CAACC,uBAAW,CAACC,YAAY,CAAC,EAAEC;IAC5B,CAACF,uBAAW,CAACG,aAAa,CAAC,EAAED;IAC7B,CAACF,uBAAW,CAACI,SAAS,CAAC,EAAEF;AAC3B;AAEA;;;;;CAKC,GACD,SAASA,uBACPG,UAAmB;IAEnB,OAAO,OAAOA,eAAe;AAC/B;AASO,SAASjB,eAAekB,IAAiB,EAAED,UAAmB;IACnE,MAAME,qBAAqBR,oBAAoB,CAACO,KAAK;IACrD,OAAOC,qBAAqBF,eAAe;AAC7C;AAEO,MAAMhB,gCAAgCmB,IAAAA,mBAAM,EACjDC,IAAAA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AAAA,mBAAM;AACpC;AAcO,SAASjB,sCACdkB,KAAc;IAEdsB,IAAAA,mBAAY,EACVtB,OACAnB,qCACA;AAEJ;AAEA,MAAM0C,mBAAmB/B,IAAAA,mBAAM,EAC7BgC,2BAAoB,EACpB7B,IAAAA,mBAAM,EAAC;IACL8B,QAAQpB;AACV;AAGF,MAAMqB,kBAAkBF,2BAAoB"}
1
+ {"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\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.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 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"],"names":["validateExport","JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","VALIDATION_FUNCTIONS","HandlerType","OnRpcRequest","validateFunctionExport","OnTransaction","OnCronjob","snapExport","type","validationFunction","assign","omit","JsonRpcRequestStruct","object","id","optional","JsonRpcIdStruct","string","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","params","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","OkResponseStruct","JsonRpcSuccessStruct","result","SnapRpcResponse"],"mappings":";;;;;;;;;;;IAmDgBA,cAAc;eAAdA;;IAKHC,6BAA6B;eAA7BA;;IAWAC,eAAe;eAAfA;;IASGC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M,MAAM9B,oCAAoC+B,IAAAA,kBAAK,EAAC;IACrDX,IAAAA,mBAAM;IACNA,IAAAA,mBAAM;IACNF,IAAAA,qBAAQ,EAACY,IAAAA,kBAAK,EAACnC;CAChB;AAEM,MAAMM,gCAAgC8B,IAAAA,kBAAK,EAAC;IACjDX,IAAAA,mBAAM;IACNY,IAAAA,kBAAK,EAACC,OAAOC,MAAM,CAAC7B,uBAAW;IAC/Be,IAAAA,mBAAM;IACNP,IAAAA,mBAAM,EACJnB,+BACAsB,IAAAA,mBAAM,EAAC;QACLmB,QAAQjB,IAAAA,qBAAQ,EAACkB,IAAAA,mBAAM,EAAChB,IAAAA,mBAAM,KAAIiB,iBAAU;IAC9C;CAEH;AAqBM,MAAMnC,sCAAsCc,IAAAA,mBAAM,EAAC;IACxD,oCAAoC;IACpCsB,aAAaF,IAAAA,mBAAM,EAAChB,IAAAA,mBAAM,KAAIiB,iBAAU;IACxCE,SAASC,yBAAa;IACtBC,mBAAmBC,IAAAA,qBAAQ,EAACtB,IAAAA,mBAAM;AACpC;AAcO,SAASjB,sCACdkB,KAAc;IAEdsB,IAAAA,mBAAY,EACVtB,OACAnB,qCACA;AAEJ;AAEA,MAAM0C,mBAAmB/B,IAAAA,mBAAM,EAC7BgC,2BAAoB,EACpB7B,IAAAA,mBAAM,EAAC;IACL8B,QAAQpB;AACV;AAGF,MAAMqB,kBAAkBF,2BAAoB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/iframe/IFrameSnapExecutor.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport {\n BasePostMessageStream,\n WindowPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { logError, SNAP_STREAM_NAMES } from '@metamask/snaps-utils';\nimport pump from 'pump';\n\nimport { BaseSnapExecutor } from '../common/BaseSnapExecutor';\nimport { log } from '../logging';\n\nexport class IFrameSnapExecutor extends BaseSnapExecutor {\n /**\n * Initialize the IFrameSnapExecutor. This creates a post message stream from\n * and to the parent window, for two-way communication with the iframe.\n *\n * @param stream - The stream to use for communication.\n * @returns An instance of `IFrameSnapExecutor`, with the initialized post\n * message streams.\n */\n static initialize(\n stream: BasePostMessageStream = new WindowPostMessageStream({\n name: 'child',\n target: 'parent',\n targetWindow: self.parent,\n targetOrigin: '*',\n }),\n ) {\n log('Worker: Connecting to parent.');\n\n const mux = new ObjectMultiplex();\n pump(stream, mux, stream, (error) => {\n if (error) {\n logError(`Parent stream failure, closing worker.`, error);\n }\n self.close();\n });\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n return new IFrameSnapExecutor(commandStream, rpcStream);\n }\n}\n"],"names":["IFrameSnapExecutor","BaseSnapExecutor","initialize","stream","WindowPostMessageStream","name","target","targetWindow","self","parent","targetOrigin","log","mux","ObjectMultiplex","pump","error","logError","close","commandStream","createStream","SNAP_STREAM_NAMES","COMMAND","rpcStream","JSON_RPC"],"mappings":";;;;+BAWaA;;;eAAAA;;;wEAXe;mCAIrB;4BACqC;6DAC3B;kCAEgB;yBACb;;;;;;AAEb,MAAMA,2BAA2BC,kCAAgB;IACtD;;;;;;;GAOC,GACD,OAAOC,WACLC,SAAgC,IAAIC,0CAAuB,CAAC;QAC1DC,MAAM;QACNC,QAAQ;QACRC,cAAcC,KAAKC,MAAM;QACzBC,cAAc;IAChB,EAAE,EACF;QACAC,IAAAA,YAAG,EAAC;QAEJ,MAAMC,MAAM,IAAIC,wBAAe;QAC/BC,IAAAA,aAAI,EAACX,QAAQS,KAAKT,QAAQ,CAACY;YACzB,IAAIA,OAAO;gBACTC,IAAAA,oBAAQ,EAAC,CAAC,sCAAsC,CAAC,EAAED;YACrD;YACAP,KAAKS,KAAK;QACZ;QAEA,MAAMC,gBAAgBN,IAAIO,YAAY,CAACC,6BAAiB,CAACC,OAAO;QAChE,MAAMC,YAAYV,IAAIO,YAAY,CAACC,6BAAiB,CAACG,QAAQ;QAE7D,OAAO,IAAIvB,mBAAmBkB,eAAeI;IAC/C;AACF"}
1
+ {"version":3,"sources":["../../../src/iframe/IFrameSnapExecutor.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { WindowPostMessageStream } from '@metamask/post-message-stream';\nimport { logError, SNAP_STREAM_NAMES } from '@metamask/snaps-utils';\nimport pump from 'pump';\n\nimport { BaseSnapExecutor } from '../common/BaseSnapExecutor';\nimport { log } from '../logging';\n\nexport class IFrameSnapExecutor extends BaseSnapExecutor {\n /**\n * Initialize the IFrameSnapExecutor. This creates a post message stream from\n * and to the parent window, for two-way communication with the iframe.\n *\n * @param stream - The stream to use for communication.\n * @returns An instance of `IFrameSnapExecutor`, with the initialized post\n * message streams.\n */\n static initialize(\n stream: BasePostMessageStream = new WindowPostMessageStream({\n name: 'child',\n target: 'parent',\n targetWindow: self.parent,\n targetOrigin: '*',\n }),\n ) {\n log('Worker: Connecting to parent.');\n\n const mux = new ObjectMultiplex();\n pump(stream, mux, stream, (error) => {\n if (error) {\n logError(`Parent stream failure, closing worker.`, error);\n }\n self.close();\n });\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n return new IFrameSnapExecutor(commandStream, rpcStream);\n }\n}\n"],"names":["IFrameSnapExecutor","BaseSnapExecutor","initialize","stream","WindowPostMessageStream","name","target","targetWindow","self","parent","targetOrigin","log","mux","ObjectMultiplex","pump","error","logError","close","commandStream","createStream","SNAP_STREAM_NAMES","COMMAND","rpcStream","JSON_RPC"],"mappings":";;;;+BASaA;;;eAAAA;;;wEATe;mCAEY;4BACI;6DAC3B;kCAEgB;yBACb;;;;;;AAEb,MAAMA,2BAA2BC,kCAAgB;IACtD;;;;;;;GAOC,GACD,OAAOC,WACLC,SAAgC,IAAIC,0CAAuB,CAAC;QAC1DC,MAAM;QACNC,QAAQ;QACRC,cAAcC,KAAKC,MAAM;QACzBC,cAAc;IAChB,EAAE,EACF;QACAC,IAAAA,YAAG,EAAC;QAEJ,MAAMC,MAAM,IAAIC,wBAAe;QAC/BC,IAAAA,aAAI,EAACX,QAAQS,KAAKT,QAAQ,CAACY;YACzB,IAAIA,OAAO;gBACTC,IAAAA,oBAAQ,EAAC,CAAC,sCAAsC,CAAC,EAAED;YACrD;YACAP,KAAKS,KAAK;QACZ;QAEA,MAAMC,gBAAgBN,IAAIO,YAAY,CAACC,6BAAiB,CAACC,OAAO;QAChE,MAAMC,YAAYV,IAAIO,YAAY,CAACC,6BAAiB,CAACG,QAAQ;QAE7D,OAAO,IAAIvB,mBAAmBkB,eAAeI;IAC/C;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/offscreen/OffscreenSnapExecutor.ts"],"sourcesContent":["import {\n BasePostMessageStream,\n WindowPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { createWindow, logError } from '@metamask/snaps-utils';\nimport { JsonRpcRequest, assert } from '@metamask/utils';\n\ntype ExecutorJob = {\n id: string;\n window: Window;\n stream: WindowPostMessageStream;\n};\n\n/**\n * A snap executor using the Offscreen Documents API.\n *\n * This is not a traditional snap executor, as it does not execute snaps itself.\n * Instead, it creates an iframe window for each snap execution, and sends the\n * snap execution request to the iframe window. The iframe window is responsible\n * for executing the snap.\n *\n * Extensions can only have a single offscreen document, so this executor is\n * persisted between snap executions. The offscreen snap executor essentially\n * acts as a proxy between the extension and the iframe execution environment.\n *\n * @see https://developer.chrome.com/docs/extensions/reference/offscreen/\n */\nexport class OffscreenSnapExecutor {\n readonly #stream: BasePostMessageStream;\n\n readonly jobs: Record<string, ExecutorJob> = {};\n\n /**\n * Initialize the executor with the given stream. This is a wrapper around the\n * constructor.\n *\n * @param stream - The stream to use for communication.\n * @returns The initialized executor.\n */\n static initialize(stream: BasePostMessageStream) {\n return new OffscreenSnapExecutor(stream);\n }\n\n constructor(stream: BasePostMessageStream) {\n this.#stream = stream;\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle an incoming message from the `OffscreenExecutionService`. This\n * assumes that the message contains a `jobId` property, and a JSON-RPC\n * request in the `data` property.\n *\n * @param data - The message data.\n * @param data.data - The JSON-RPC request.\n * @param data.jobId - The job ID.\n * @param data.extra - Extra data.\n * @param data.extra.frameUrl - The URL to load in the iframe.\n */\n #onData(data: {\n data: JsonRpcRequest;\n jobId: string;\n extra: { frameUrl: string };\n }) {\n const {\n jobId,\n extra: { frameUrl },\n data: request,\n } = data;\n\n if (!this.jobs[jobId]) {\n // This ensures that a job is initialized before it is used. To avoid\n // code duplication, we call the `#onData` method again, which will\n // run the rest of the logic after initialization.\n this.#initializeJob(jobId, frameUrl)\n .then(() => {\n this.#onData(data);\n })\n .catch((error) => {\n logError('[Worker] Error initializing job:', error);\n });\n\n return;\n }\n\n // This is a method specific to the `OffscreenSnapExecutor`, as the service\n // itself does not have access to the iframes directly.\n if (request.method === 'terminateJob') {\n this.#terminateJob(jobId);\n return;\n }\n\n this.jobs[jobId].stream.write(request);\n }\n\n /**\n * Create a new iframe and set up a stream to communicate with it.\n *\n * @param jobId - The job ID.\n * @param frameUrl - The URL to load in the iframe.\n */\n async #initializeJob(jobId: string, frameUrl: string): Promise<ExecutorJob> {\n const window = await createWindow(frameUrl, jobId);\n const jobStream = new WindowPostMessageStream({\n name: 'parent',\n target: 'child',\n targetWindow: window,\n targetOrigin: '*',\n });\n\n // Write messages from the iframe to the parent, wrapped with the job ID.\n jobStream.on('data', (data) => {\n this.#stream.write({ data, jobId });\n });\n\n this.jobs[jobId] = { id: jobId, window, stream: jobStream };\n return this.jobs[jobId];\n }\n\n /**\n * Terminate the job with the given ID. This will close the iframe and delete\n * the job from the internal job map.\n *\n * @param jobId - The job ID.\n */\n #terminateJob(jobId: string) {\n assert(this.jobs[jobId], `Job \"${jobId}\" not found.`);\n\n const iframe = document.getElementById(jobId);\n assert(iframe, `Iframe with ID \"${jobId}\" not found.`);\n\n iframe.remove();\n this.jobs[jobId].stream.destroy();\n delete this.jobs[jobId];\n }\n}\n"],"names":["OffscreenSnapExecutor","initialize","stream","constructor","jobs","on","onData","bind","data","jobId","extra","frameUrl","request","initializeJob","then","catch","error","logError","method","terminateJob","write","window","createWindow","jobStream","WindowPostMessageStream","name","target","targetWindow","targetOrigin","id","assert","iframe","document","getElementById","remove","destroy"],"mappings":";;;;+BA2BaA;;;eAAAA;;;mCAxBN;4BACgC;uBACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAuB5B,uCAoBT;;;;;;;;;;GAUC,GACD,uCA0CM,8CAkBN;;;;;GAKC,GACD;AAlGK,MAAMA;IAKX;;;;;;GAMC,GACD,OAAOC,WAAWC,MAA6B,EAAE;QAC/C,OAAO,IAAIF,sBAAsBE;IACnC;IAEAC,YAAYD,MAA6B,CAAE;QAgB3C,iCAAA;QAoCA;;;;;GAKC,GACD,iCAAM;QAwBN,iCAAA;QAjGA,gCAAS;;mBAAT,KAAA;;QAEA,uBAASE,QAAoC,CAAC;uCActCF,SAASA;QACf,yBAAA,IAAI,EAAEA,SAAOG,EAAE,CAAC,QAAQ,0BAAA,IAAI,EAAEC,SAAAA,QAAOC,IAAI,CAAC,IAAI;IAChD;AAyFF;AA5EE,SAAA,OAAQC,IAIP;IACC,MAAM,EACJC,KAAK,EACLC,OAAO,EAAEC,QAAQ,EAAE,EACnBH,MAAMI,OAAO,EACd,GAAGJ;IAEJ,IAAI,CAAC,IAAI,CAACJ,IAAI,CAACK,MAAM,EAAE;QACrB,qEAAqE;QACrE,mEAAmE;QACnE,kDAAkD;QAClD,0BAAA,IAAI,EAAEI,gBAAAA,oBAAN,IAAI,EAAgBJ,OAAOE,UACxBG,IAAI,CAAC;YACJ,0BAAA,IAAI,EAAER,SAAAA,aAAN,IAAI,EAASE;QACf,GACCO,KAAK,CAAC,CAACC;YACNC,IAAAA,oBAAQ,EAAC,oCAAoCD;QAC/C;QAEF;IACF;IAEA,2EAA2E;IAC3E,uDAAuD;IACvD,IAAIJ,QAAQM,MAAM,KAAK,gBAAgB;QACrC,0BAAA,IAAI,EAAEC,eAAAA,mBAAN,IAAI,EAAeV;QACnB;IACF;IAEA,IAAI,CAACL,IAAI,CAACK,MAAM,CAACP,MAAM,CAACkB,KAAK,CAACR;AAChC;AAQA,eAAA,cAAqBH,KAAa,EAAEE,QAAgB;IAClD,MAAMU,SAAS,MAAMC,IAAAA,wBAAY,EAACX,UAAUF;IAC5C,MAAMc,YAAY,IAAIC,0CAAuB,CAAC;QAC5CC,MAAM;QACNC,QAAQ;QACRC,cAAcN;QACdO,cAAc;IAChB;IAEA,yEAAyE;IACzEL,UAAUlB,EAAE,CAAC,QAAQ,CAACG;QACpB,yBAAA,IAAI,EAAEN,SAAOkB,KAAK,CAAC;YAAEZ;YAAMC;QAAM;IACnC;IAEA,IAAI,CAACL,IAAI,CAACK,MAAM,GAAG;QAAEoB,IAAIpB;QAAOY;QAAQnB,QAAQqB;IAAU;IAC1D,OAAO,IAAI,CAACnB,IAAI,CAACK,MAAM;AACzB;AAQA,SAAA,aAAcA,KAAa;IACzBqB,IAAAA,aAAM,EAAC,IAAI,CAAC1B,IAAI,CAACK,MAAM,EAAE,CAAC,KAAK,EAAEA,MAAM,YAAY,CAAC;IAEpD,MAAMsB,SAASC,SAASC,cAAc,CAACxB;IACvCqB,IAAAA,aAAM,EAACC,QAAQ,CAAC,gBAAgB,EAAEtB,MAAM,YAAY,CAAC;IAErDsB,OAAOG,MAAM;IACb,IAAI,CAAC9B,IAAI,CAACK,MAAM,CAACP,MAAM,CAACiC,OAAO;IAC/B,OAAO,IAAI,CAAC/B,IAAI,CAACK,MAAM;AACzB"}
1
+ {"version":3,"sources":["../../../src/offscreen/OffscreenSnapExecutor.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { WindowPostMessageStream } from '@metamask/post-message-stream';\nimport { createWindow, logError } from '@metamask/snaps-utils';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\n\ntype ExecutorJob = {\n id: string;\n window: Window;\n stream: WindowPostMessageStream;\n};\n\n/**\n * A snap executor using the Offscreen Documents API.\n *\n * This is not a traditional snap executor, as it does not execute snaps itself.\n * Instead, it creates an iframe window for each snap execution, and sends the\n * snap execution request to the iframe window. The iframe window is responsible\n * for executing the snap.\n *\n * Extensions can only have a single offscreen document, so this executor is\n * persisted between snap executions. The offscreen snap executor essentially\n * acts as a proxy between the extension and the iframe execution environment.\n *\n * @see https://developer.chrome.com/docs/extensions/reference/offscreen/\n */\nexport class OffscreenSnapExecutor {\n readonly #stream: BasePostMessageStream;\n\n readonly jobs: Record<string, ExecutorJob> = {};\n\n /**\n * Initialize the executor with the given stream. This is a wrapper around the\n * constructor.\n *\n * @param stream - The stream to use for communication.\n * @returns The initialized executor.\n */\n static initialize(stream: BasePostMessageStream) {\n return new OffscreenSnapExecutor(stream);\n }\n\n constructor(stream: BasePostMessageStream) {\n this.#stream = stream;\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle an incoming message from the `OffscreenExecutionService`. This\n * assumes that the message contains a `jobId` property, and a JSON-RPC\n * request in the `data` property.\n *\n * @param data - The message data.\n * @param data.data - The JSON-RPC request.\n * @param data.jobId - The job ID.\n * @param data.extra - Extra data.\n * @param data.extra.frameUrl - The URL to load in the iframe.\n */\n #onData(data: {\n data: JsonRpcRequest;\n jobId: string;\n extra: { frameUrl: string };\n }) {\n const {\n jobId,\n extra: { frameUrl },\n data: request,\n } = data;\n\n if (!this.jobs[jobId]) {\n // This ensures that a job is initialized before it is used. To avoid\n // code duplication, we call the `#onData` method again, which will\n // run the rest of the logic after initialization.\n this.#initializeJob(jobId, frameUrl)\n .then(() => {\n this.#onData(data);\n })\n .catch((error) => {\n logError('[Worker] Error initializing job:', error);\n });\n\n return;\n }\n\n // This is a method specific to the `OffscreenSnapExecutor`, as the service\n // itself does not have access to the iframes directly.\n if (request.method === 'terminateJob') {\n this.#terminateJob(jobId);\n return;\n }\n\n this.jobs[jobId].stream.write(request);\n }\n\n /**\n * Create a new iframe and set up a stream to communicate with it.\n *\n * @param jobId - The job ID.\n * @param frameUrl - The URL to load in the iframe.\n */\n async #initializeJob(jobId: string, frameUrl: string): Promise<ExecutorJob> {\n const window = await createWindow(frameUrl, jobId);\n const jobStream = new WindowPostMessageStream({\n name: 'parent',\n target: 'child',\n targetWindow: window,\n targetOrigin: '*',\n });\n\n // Write messages from the iframe to the parent, wrapped with the job ID.\n jobStream.on('data', (data) => {\n this.#stream.write({ data, jobId });\n });\n\n this.jobs[jobId] = { id: jobId, window, stream: jobStream };\n return this.jobs[jobId];\n }\n\n /**\n * Terminate the job with the given ID. This will close the iframe and delete\n * the job from the internal job map.\n *\n * @param jobId - The job ID.\n */\n #terminateJob(jobId: string) {\n assert(this.jobs[jobId], `Job \"${jobId}\" not found.`);\n\n const iframe = document.getElementById(jobId);\n assert(iframe, `Iframe with ID \"${jobId}\" not found.`);\n\n iframe.remove();\n this.jobs[jobId].stream.destroy();\n delete this.jobs[jobId];\n }\n}\n"],"names":["OffscreenSnapExecutor","initialize","stream","constructor","jobs","on","onData","bind","data","jobId","extra","frameUrl","request","initializeJob","then","catch","error","logError","method","terminateJob","write","window","createWindow","jobStream","WindowPostMessageStream","name","target","targetWindow","targetOrigin","id","assert","iframe","document","getElementById","remove","destroy"],"mappings":";;;;+BA0BaA;;;eAAAA;;;mCAzB2B;4BACD;uBAEhB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAuBZ,uCAoBT;;;;;;;;;;GAUC,GACD,uCA0CM,8CAkBN;;;;;GAKC,GACD;AAlGK,MAAMA;IAKX;;;;;;GAMC,GACD,OAAOC,WAAWC,MAA6B,EAAE;QAC/C,OAAO,IAAIF,sBAAsBE;IACnC;IAEAC,YAAYD,MAA6B,CAAE;QAgB3C,iCAAA;QAoCA;;;;;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;QAAEoB,IAAIpB;QAAOY;QAAQnB,QAAQqB;IAAU;IAC1D,OAAO,IAAI,CAACnB,IAAI,CAACK,MAAM;AACzB;AAQA,SAAA,aAAcA,KAAa;IACzBqB,IAAAA,aAAM,EAAC,IAAI,CAAC1B,IAAI,CAACK,MAAM,EAAE,CAAC,KAAK,EAAEA,MAAM,YAAY,CAAC;IAEpD,MAAMsB,SAASC,SAASC,cAAc,CAACxB;IACvCqB,IAAAA,aAAM,EAACC,QAAQ,CAAC,gBAAgB,EAAEtB,MAAM,YAAY,CAAC;IAErDsB,OAAOG,MAAM;IACb,IAAI,CAAC9B,IAAI,CAACK,MAAM,CAACP,MAAM,CAACiC,OAAO;IAC/B,OAAO,IAAI,CAAC/B,IAAI,CAACK,MAAM;AACzB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/webworker/executor/WebWorkerSnapExecutor.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport {\n BasePostMessageStream,\n WebWorkerPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { logError, SNAP_STREAM_NAMES } from '@metamask/snaps-utils';\nimport pump from 'pump';\n\nimport { BaseSnapExecutor } from '../../common/BaseSnapExecutor';\nimport { log } from '../../logging';\n\nexport class WebWorkerSnapExecutor extends BaseSnapExecutor {\n /**\n * Initialize the WebWorkerSnapExecutor. This creates a post message stream\n * from and to the parent window, for two-way communication with the iframe.\n *\n * @param stream - The stream to use for communication.\n * @returns An instance of `WebWorkerSnapExecutor`, with the initialized post\n * message streams.\n */\n static initialize(\n stream: BasePostMessageStream = new WebWorkerPostMessageStream(),\n ) {\n log('Worker: Connecting to parent.');\n\n const mux = new ObjectMultiplex();\n pump(stream, mux, stream, (error) => {\n if (error) {\n logError(`Parent stream failure, closing worker.`, error);\n }\n self.close();\n });\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n return new WebWorkerSnapExecutor(commandStream, rpcStream);\n }\n}\n"],"names":["WebWorkerSnapExecutor","BaseSnapExecutor","initialize","stream","WebWorkerPostMessageStream","log","mux","ObjectMultiplex","pump","error","logError","self","close","commandStream","createStream","SNAP_STREAM_NAMES","COMMAND","rpcStream","JSON_RPC"],"mappings":";;;;+BAWaA;;;eAAAA;;;wEAXe;mCAIrB;4BACqC;6DAC3B;kCAEgB;yBACb;;;;;;AAEb,MAAMA,8BAA8BC,kCAAgB;IACzD;;;;;;;GAOC,GACD,OAAOC,WACLC,SAAgC,IAAIC,6CAA0B,EAAE,EAChE;QACAC,IAAAA,YAAG,EAAC;QAEJ,MAAMC,MAAM,IAAIC,wBAAe;QAC/BC,IAAAA,aAAI,EAACL,QAAQG,KAAKH,QAAQ,CAACM;YACzB,IAAIA,OAAO;gBACTC,IAAAA,oBAAQ,EAAC,CAAC,sCAAsC,CAAC,EAAED;YACrD;YACAE,KAAKC,KAAK;QACZ;QAEA,MAAMC,gBAAgBP,IAAIQ,YAAY,CAACC,6BAAiB,CAACC,OAAO;QAChE,MAAMC,YAAYX,IAAIQ,YAAY,CAACC,6BAAiB,CAACG,QAAQ;QAE7D,OAAO,IAAIlB,sBAAsBa,eAAeI;IAClD;AACF"}
1
+ {"version":3,"sources":["../../../../src/webworker/executor/WebWorkerSnapExecutor.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { WebWorkerPostMessageStream } from '@metamask/post-message-stream';\nimport { logError, SNAP_STREAM_NAMES } from '@metamask/snaps-utils';\nimport pump from 'pump';\n\nimport { BaseSnapExecutor } from '../../common/BaseSnapExecutor';\nimport { log } from '../../logging';\n\nexport class WebWorkerSnapExecutor extends BaseSnapExecutor {\n /**\n * Initialize the WebWorkerSnapExecutor. This creates a post message stream\n * from and to the parent window, for two-way communication with the iframe.\n *\n * @param stream - The stream to use for communication.\n * @returns An instance of `WebWorkerSnapExecutor`, with the initialized post\n * message streams.\n */\n static initialize(\n stream: BasePostMessageStream = new WebWorkerPostMessageStream(),\n ) {\n log('Worker: Connecting to parent.');\n\n const mux = new ObjectMultiplex();\n pump(stream, mux, stream, (error) => {\n if (error) {\n logError(`Parent stream failure, closing worker.`, error);\n }\n self.close();\n });\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n return new WebWorkerSnapExecutor(commandStream, rpcStream);\n }\n}\n"],"names":["WebWorkerSnapExecutor","BaseSnapExecutor","initialize","stream","WebWorkerPostMessageStream","log","mux","ObjectMultiplex","pump","error","logError","self","close","commandStream","createStream","SNAP_STREAM_NAMES","COMMAND","rpcStream","JSON_RPC"],"mappings":";;;;+BASaA;;;eAAAA;;;wEATe;mCAEe;4BACC;6DAC3B;kCAEgB;yBACb;;;;;;AAEb,MAAMA,8BAA8BC,kCAAgB;IACzD;;;;;;;GAOC,GACD,OAAOC,WACLC,SAAgC,IAAIC,6CAA0B,EAAE,EAChE;QACAC,IAAAA,YAAG,EAAC;QAEJ,MAAMC,MAAM,IAAIC,wBAAe;QAC/BC,IAAAA,aAAI,EAACL,QAAQG,KAAKH,QAAQ,CAACM;YACzB,IAAIA,OAAO;gBACTC,IAAAA,oBAAQ,EAAC,CAAC,sCAAsC,CAAC,EAAED;YACrD;YACAE,KAAKC,KAAK;QACZ;QAEA,MAAMC,gBAAgBP,IAAIQ,YAAY,CAACC,6BAAiB,CAACC,OAAO;QAChE,MAAMC,YAAYX,IAAIQ,YAAY,CAACC,6BAAiB,CAACG,QAAQ;QAE7D,OAAO,IAAIlB,sBAAsBa,eAAeI;IAClD;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/webworker/pool/WebWorkerPool.ts"],"sourcesContent":["import {\n BasePostMessageStream,\n WebWorkerParentPostMessageStream,\n WindowPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { logError } from '@metamask/snaps-utils';\nimport { JsonRpcRequest, assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid/non-secure';\n\ntype ExecutorJob = {\n id: string;\n worker: Worker;\n stream: WebWorkerParentPostMessageStream;\n};\n\n/**\n * A snap executor using the WebWorker API.\n *\n * This is not a traditional snap executor, as it does not execute snaps itself.\n * Instead, it creates a pool of webworkers for each snap execution, and sends\n * the snap execution request to the webworker. The webworker is responsible for\n * executing the snap.\n */\nexport class WebWorkerPool {\n readonly #poolSize;\n\n readonly #stream: BasePostMessageStream;\n\n readonly #url: string;\n\n readonly pool: Worker[] = [];\n\n readonly jobs: Map<string, ExecutorJob> = new Map();\n\n #workerSourceURL?: string;\n\n /* istanbul ignore next - Constructor arguments. */\n static initialize(\n stream: BasePostMessageStream = new WindowPostMessageStream({\n name: 'child',\n target: 'parent',\n targetWindow: self.parent,\n targetOrigin: '*',\n }),\n url = '../executor/bundle.js',\n poolSize?: number,\n ) {\n return new WebWorkerPool(stream, url, poolSize);\n }\n\n constructor(stream: BasePostMessageStream, url: string, poolSize = 3) {\n this.#stream = stream;\n this.#url = url;\n this.#poolSize = poolSize;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle an incoming message from the `WebWorkerExecutionService`. This\n * assumes that the message contains a `jobId` property, and a JSON-RPC\n * request in the `data` property.\n *\n * @param data - The message data.\n * @param data.data - The JSON-RPC request.\n * @param data.jobId - The job ID.\n */\n #onData(data: { data: JsonRpcRequest; jobId: string }) {\n const { jobId, data: request } = data;\n\n const job = this.jobs.get(jobId);\n if (!job) {\n // This ensures that a job is initialized before it is used. To avoid\n // code duplication, we call the `#onData` method again, which will\n // run the rest of the logic after initialization.\n this.#initializeJob(jobId)\n .then(() => {\n this.#onData(data);\n })\n .catch((error) => {\n logError('[Worker] Error initializing job:', error.toString());\n\n this.#stream.write({\n jobId,\n data: {\n name: 'command',\n data: {\n jsonrpc: '2.0',\n id: request.id ?? null,\n error: {\n code: -32000,\n message: 'Internal error',\n },\n },\n },\n });\n });\n\n return;\n }\n\n // This is a method specific to the `WebWorkerPool`, as the service itself\n // does not have access to the workers directly.\n if (request.method === 'terminateJob') {\n this.#terminateJob(jobId);\n return;\n }\n\n job.stream.write(request);\n }\n\n /**\n * Create a new worker and set up a stream to communicate with it.\n *\n * @param jobId - The job ID.\n * @returns The job.\n */\n async #initializeJob(jobId: string): Promise<ExecutorJob> {\n const worker = await this.#getWorker();\n const jobStream = new WebWorkerParentPostMessageStream({\n worker,\n });\n\n // Write messages from the worker to the parent, wrapped with the job ID.\n jobStream.on('data', (data) => {\n this.#stream.write({ data, jobId });\n });\n\n const job = { id: jobId, worker, stream: jobStream };\n this.jobs.set(jobId, job);\n return job;\n }\n\n /**\n * Terminate the job with the given ID. This will close the worker and delete\n * the job from the internal job map.\n *\n * @param jobId - The job ID.\n */\n #terminateJob(jobId: string) {\n const job = this.jobs.get(jobId);\n assert(job, `Job \"${jobId}\" not found.`);\n\n job.stream.destroy();\n job.worker.terminate();\n\n this.jobs.delete(jobId);\n }\n\n /**\n * Get a worker from the pool. A new worker will be created automatically.\n *\n * @returns The worker.\n */\n async #getWorker() {\n // Lazily create the pool of workers.\n if (this.pool.length === 0) {\n await this.#updatePool();\n }\n\n const worker = this.pool.shift();\n assert(worker, 'Worker not found.');\n\n await this.#updatePool();\n\n return worker;\n }\n\n /**\n * Update the pool of workers. This will create new workers if the pool is\n * below the minimum size.\n */\n async #updatePool() {\n while (this.pool.length < this.#poolSize) {\n const worker = await this.#createWorker();\n this.pool.push(worker);\n }\n }\n\n /**\n * Create a new worker. This will fetch the worker source if it has not\n * already been fetched.\n *\n * @returns The worker.\n */\n async #createWorker() {\n return new Worker(await this.#getWorkerURL(), {\n name: `worker-${nanoid()}`,\n });\n }\n\n /**\n * Get the URL of the worker source. This will fetch the worker source if it\n * has not already been fetched.\n *\n * @returns The worker source URL, as a `blob:` URL.\n */\n async #getWorkerURL() {\n if (this.#workerSourceURL) {\n return this.#workerSourceURL;\n }\n\n const blob = await fetch(this.#url)\n .then(async (response) => response.blob())\n .then(URL.createObjectURL.bind(URL));\n\n this.#workerSourceURL = blob;\n return blob;\n }\n}\n"],"names":["WebWorkerPool","initialize","stream","WindowPostMessageStream","name","target","targetWindow","self","parent","targetOrigin","url","poolSize","constructor","pool","jobs","Map","on","onData","bind","data","jobId","request","job","get","initializeJob","then","catch","error","logError","toString","write","jsonrpc","id","code","message","method","terminateJob","worker","getWorker","jobStream","WebWorkerParentPostMessageStream","set","assert","destroy","terminate","delete","length","updatePool","shift","createWorker","push","Worker","getWorkerURL","nanoid","workerSourceURL","blob","fetch","response","URL","createObjectURL"],"mappings":";;;;+BAuBaA;;;eAAAA;;;mCAnBN;4BACkB;uBACc;2BAChB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAiBZ,yCAEA,uCAEA,oCAMT,gDAwBA;;;;;;;;GAQC,GACD,uCAkDM,8CAgBN;;;;;GAKC,GACD,6CAeM,0CAkBA,2CAaA,6CAYA;AA9KD,MAAMA;IAaX,iDAAiD,GACjD,OAAOC,WACLC,SAAgC,IAAIC,0CAAuB,CAAC;QAC1DC,MAAM;QACNC,QAAQ;QACRC,cAAcC,KAAKC,MAAM;QACzBC,cAAc;IAChB,EAAE,EACFC,MAAM,uBAAuB,EAC7BC,QAAiB,EACjB;QACA,OAAO,IAAIX,cAAcE,QAAQQ,KAAKC;IACxC;IAEAC,YAAYV,MAA6B,EAAEQ,GAAW,EAAEC,WAAW,CAAC,CAAE;QAiBtE,iCAAA;QA4CA;;;;;GAKC,GACD,iCAAM;QAsBN,iCAAA;QAUA;;;;GAIC,GACD,iCAAM;QAcN;;;GAGC,GACD,iCAAM;QAON;;;;;GAKC,GACD,iCAAM;QAMN;;;;;GAKC,GACD,iCAAM;QA7KN,gCAAS;;mBAAT,KAAA;;QAEA,gCAAS;;mBAAT,KAAA;;QAEA,gCAAS;;mBAAT,KAAA;;QAEA,uBAASE,QAAiB,EAAE;QAE5B,uBAASC,QAAiC,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IACf;IAEA,MAAMC,OAAO,MAAMC,+BAAM,IAAI,EAAE9C,OAC5Be,IAAI,CAAC,OAAOgC,WAAaA,SAASF,IAAI,IACtC9B,IAAI,CAACiC,IAAIC,eAAe,CAACzC,IAAI,CAACwC;mCAE3BJ,kBAAkBC;IACxB,OAAOA;AACT"}
1
+ {"version":3,"sources":["../../../../src/webworker/pool/WebWorkerPool.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport {\n WebWorkerParentPostMessageStream,\n WindowPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { logError } from '@metamask/snaps-utils';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid/non-secure';\n\ntype ExecutorJob = {\n id: string;\n worker: Worker;\n stream: WebWorkerParentPostMessageStream;\n};\n\n/**\n * A snap executor using the WebWorker API.\n *\n * This is not a traditional snap executor, as it does not execute snaps itself.\n * Instead, it creates a pool of webworkers for each snap execution, and sends\n * the snap execution request to the webworker. The webworker is responsible for\n * executing the snap.\n */\nexport class WebWorkerPool {\n readonly #poolSize;\n\n readonly #stream: BasePostMessageStream;\n\n readonly #url: string;\n\n readonly pool: Worker[] = [];\n\n readonly jobs: Map<string, ExecutorJob> = new Map();\n\n #workerSourceURL?: string;\n\n /* istanbul ignore next - Constructor arguments. */\n static initialize(\n stream: BasePostMessageStream = new WindowPostMessageStream({\n name: 'child',\n target: 'parent',\n targetWindow: self.parent,\n targetOrigin: '*',\n }),\n url = '../executor/bundle.js',\n poolSize?: number,\n ) {\n return new WebWorkerPool(stream, url, poolSize);\n }\n\n constructor(stream: BasePostMessageStream, url: string, poolSize = 3) {\n this.#stream = stream;\n this.#url = url;\n this.#poolSize = poolSize;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle an incoming message from the `WebWorkerExecutionService`. This\n * assumes that the message contains a `jobId` property, and a JSON-RPC\n * request in the `data` property.\n *\n * @param data - The message data.\n * @param data.data - The JSON-RPC request.\n * @param data.jobId - The job ID.\n */\n #onData(data: { data: JsonRpcRequest; jobId: string }) {\n const { jobId, data: request } = data;\n\n const job = this.jobs.get(jobId);\n if (!job) {\n // This ensures that a job is initialized before it is used. To avoid\n // code duplication, we call the `#onData` method again, which will\n // run the rest of the logic after initialization.\n this.#initializeJob(jobId)\n .then(() => {\n this.#onData(data);\n })\n .catch((error) => {\n logError('[Worker] Error initializing job:', error.toString());\n\n this.#stream.write({\n jobId,\n data: {\n name: 'command',\n data: {\n jsonrpc: '2.0',\n id: request.id ?? null,\n error: {\n code: -32000,\n message: 'Internal error',\n },\n },\n },\n });\n });\n\n return;\n }\n\n // This is a method specific to the `WebWorkerPool`, as the service itself\n // does not have access to the workers directly.\n if (request.method === 'terminateJob') {\n this.#terminateJob(jobId);\n return;\n }\n\n job.stream.write(request);\n }\n\n /**\n * Create a new worker and set up a stream to communicate with it.\n *\n * @param jobId - The job ID.\n * @returns The job.\n */\n async #initializeJob(jobId: string): Promise<ExecutorJob> {\n const worker = await this.#getWorker();\n const jobStream = new WebWorkerParentPostMessageStream({\n worker,\n });\n\n // Write messages from the worker to the parent, wrapped with the job ID.\n jobStream.on('data', (data) => {\n this.#stream.write({ data, jobId });\n });\n\n const job = { id: jobId, worker, stream: jobStream };\n this.jobs.set(jobId, job);\n return job;\n }\n\n /**\n * Terminate the job with the given ID. This will close the worker and delete\n * the job from the internal job map.\n *\n * @param jobId - The job ID.\n */\n #terminateJob(jobId: string) {\n const job = this.jobs.get(jobId);\n assert(job, `Job \"${jobId}\" not found.`);\n\n job.stream.destroy();\n job.worker.terminate();\n\n this.jobs.delete(jobId);\n }\n\n /**\n * Get a worker from the pool. A new worker will be created automatically.\n *\n * @returns The worker.\n */\n async #getWorker() {\n // Lazily create the pool of workers.\n if (this.pool.length === 0) {\n await this.#updatePool();\n }\n\n const worker = this.pool.shift();\n assert(worker, 'Worker not found.');\n\n await this.#updatePool();\n\n return worker;\n }\n\n /**\n * Update the pool of workers. This will create new workers if the pool is\n * below the minimum size.\n */\n async #updatePool() {\n while (this.pool.length < this.#poolSize) {\n const worker = await this.#createWorker();\n this.pool.push(worker);\n }\n }\n\n /**\n * Create a new worker. This will fetch the worker source if it has not\n * already been fetched.\n *\n * @returns The worker.\n */\n async #createWorker() {\n return new Worker(await this.#getWorkerURL(), {\n name: `worker-${nanoid()}`,\n });\n }\n\n /**\n * Get the URL of the worker source. This will fetch the worker source if it\n * has not already been fetched.\n *\n * @returns The worker source URL, as a `blob:` URL.\n */\n async #getWorkerURL() {\n if (this.#workerSourceURL) {\n return this.#workerSourceURL;\n }\n\n const blob = await fetch(this.#url)\n .then(async (response) => response.blob())\n .then(URL.createObjectURL.bind(URL));\n\n this.#workerSourceURL = blob;\n return blob;\n }\n}\n"],"names":["WebWorkerPool","initialize","stream","WindowPostMessageStream","name","target","targetWindow","self","parent","targetOrigin","url","poolSize","constructor","pool","jobs","Map","on","onData","bind","data","jobId","request","job","get","initializeJob","then","catch","error","logError","toString","write","jsonrpc","id","code","message","method","terminateJob","worker","getWorker","jobStream","WebWorkerParentPostMessageStream","set","assert","destroy","terminate","delete","length","updatePool","shift","createWorker","push","Worker","getWorkerURL","nanoid","workerSourceURL","blob","fetch","response","URL","createObjectURL"],"mappings":";;;;+BAwBaA;;;eAAAA;;;mCApBN;4BACkB;uBAEF;2BACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAiBZ,yCAEA,uCAEA,oCAMT,gDAwBA;;;;;;;;GAQC,GACD,uCAkDM,8CAgBN;;;;;GAKC,GACD,6CAeM,0CAkBA,2CAaA,6CAYA;AA9KD,MAAMA;IAaX,iDAAiD,GACjD,OAAOC,WACLC,SAAgC,IAAIC,0CAAuB,CAAC;QAC1DC,MAAM;QACNC,QAAQ;QACRC,cAAcC,KAAKC,MAAM;QACzBC,cAAc;IAChB,EAAE,EACFC,MAAM,uBAAuB,EAC7BC,QAAiB,EACjB;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