@metamask/snaps-controllers 3.0.0 → 3.1.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 (57) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/dist/cjs/cronjob/CronjobController.js +1 -1
  3. package/dist/cjs/cronjob/CronjobController.js.map +1 -1
  4. package/dist/cjs/services/AbstractExecutionService.js +6 -7
  5. package/dist/cjs/services/AbstractExecutionService.js.map +1 -1
  6. package/dist/cjs/snaps/SnapController.js +72 -82
  7. package/dist/cjs/snaps/SnapController.js.map +1 -1
  8. package/dist/cjs/snaps/endowments/cronjob.js +4 -4
  9. package/dist/cjs/snaps/endowments/cronjob.js.map +1 -1
  10. package/dist/cjs/snaps/endowments/keyring.js +4 -4
  11. package/dist/cjs/snaps/endowments/keyring.js.map +1 -1
  12. package/dist/cjs/snaps/endowments/name-lookup.js +3 -3
  13. package/dist/cjs/snaps/endowments/name-lookup.js.map +1 -1
  14. package/dist/cjs/snaps/endowments/rpc.js +4 -4
  15. package/dist/cjs/snaps/endowments/rpc.js.map +1 -1
  16. package/dist/cjs/snaps/endowments/transaction-insight.js +3 -3
  17. package/dist/cjs/snaps/endowments/transaction-insight.js.map +1 -1
  18. package/dist/cjs/snaps/location/location.js.map +1 -1
  19. package/dist/cjs/snaps/location/npm.js +47 -16
  20. package/dist/cjs/snaps/location/npm.js.map +1 -1
  21. package/dist/cjs/snaps/permissions.js +5 -5
  22. package/dist/cjs/snaps/permissions.js.map +1 -1
  23. package/dist/cjs/snaps/registry/json.js +30 -1
  24. package/dist/cjs/snaps/registry/json.js.map +1 -1
  25. package/dist/cjs/snaps/registry/registry.js.map +1 -1
  26. package/dist/esm/cronjob/CronjobController.js +1 -1
  27. package/dist/esm/cronjob/CronjobController.js.map +1 -1
  28. package/dist/esm/services/AbstractExecutionService.js +6 -7
  29. package/dist/esm/services/AbstractExecutionService.js.map +1 -1
  30. package/dist/esm/snaps/SnapController.js +69 -79
  31. package/dist/esm/snaps/SnapController.js.map +1 -1
  32. package/dist/esm/snaps/endowments/cronjob.js +4 -4
  33. package/dist/esm/snaps/endowments/cronjob.js.map +1 -1
  34. package/dist/esm/snaps/endowments/keyring.js +4 -4
  35. package/dist/esm/snaps/endowments/keyring.js.map +1 -1
  36. package/dist/esm/snaps/endowments/name-lookup.js +3 -3
  37. package/dist/esm/snaps/endowments/name-lookup.js.map +1 -1
  38. package/dist/esm/snaps/endowments/rpc.js +4 -4
  39. package/dist/esm/snaps/endowments/rpc.js.map +1 -1
  40. package/dist/esm/snaps/endowments/transaction-insight.js +3 -3
  41. package/dist/esm/snaps/endowments/transaction-insight.js.map +1 -1
  42. package/dist/esm/snaps/location/location.js.map +1 -1
  43. package/dist/esm/snaps/location/npm.js +48 -17
  44. package/dist/esm/snaps/location/npm.js.map +1 -1
  45. package/dist/esm/snaps/permissions.js +1 -1
  46. package/dist/esm/snaps/permissions.js.map +1 -1
  47. package/dist/esm/snaps/registry/json.js +31 -2
  48. package/dist/esm/snaps/registry/json.js.map +1 -1
  49. package/dist/esm/snaps/registry/registry.js.map +1 -1
  50. package/dist/types/cronjob/CronjobController.d.ts +1 -1
  51. package/dist/types/services/AbstractExecutionService.d.ts +1 -1
  52. package/dist/types/snaps/SnapController.d.ts +20 -32
  53. package/dist/types/snaps/location/location.d.ts +2 -0
  54. package/dist/types/snaps/location/npm.d.ts +1 -1
  55. package/dist/types/snaps/registry/json.d.ts +5 -1
  56. package/dist/types/snaps/registry/registry.d.ts +11 -1
  57. package/package.json +29 -22
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/services/AbstractExecutionService.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcNotification } from '@metamask/utils';\nimport { Duration, isJsonRpcNotification, isObject } from '@metamask/utils';\nimport type {\n // TODO: Replace with @metamask/utils version after bumping json-rpc-engine\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from 'json-rpc-engine';\nimport { JsonRpcEngine } from 'json-rpc-engine';\nimport { createStreamMiddleware } from 'json-rpc-middleware-stream';\nimport { nanoid } from 'nanoid';\nimport { pipeline } from 'stream';\nimport type { Duplex } from 'stream';\n\nimport { log } from '../logging';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\n\nconst controllerName = 'ExecutionService';\n\nexport type SetupSnapProvider = (snapId: string, stream: Duplex) => void;\n\nexport type ExecutionServiceArgs = {\n setupSnapProvider: SetupSnapProvider;\n messenger: ExecutionServiceMessenger;\n terminationTimeout?: number;\n};\n\nexport type JobStreams = {\n command: Duplex;\n rpc: Duplex;\n _connection: BasePostMessageStream;\n};\n\nexport type Job<WorkerType> = {\n id: string;\n streams: JobStreams;\n rpcEngine: JsonRpcEngine;\n worker: WorkerType;\n};\n\nexport abstract class AbstractExecutionService<WorkerType>\n implements ExecutionService\n{\n #snapRpcHooks: Map<string, SnapRpcHook>;\n\n // Cannot be hash private yet because of tests.\n protected jobs: Map<string, Job<WorkerType>>;\n\n // Cannot be hash private yet because of tests.\n private readonly setupSnapProvider: SetupSnapProvider;\n\n #snapToJobMap: Map<string, string>;\n\n #jobToSnapMap: Map<string, string>;\n\n #messenger: ExecutionServiceMessenger;\n\n #terminationTimeout: number;\n\n constructor({\n setupSnapProvider,\n messenger,\n terminationTimeout = Duration.Second,\n }: ExecutionServiceArgs) {\n this.#snapRpcHooks = new Map();\n this.jobs = new Map();\n this.setupSnapProvider = setupSnapProvider;\n this.#snapToJobMap = new Map();\n this.#jobToSnapMap = new Map();\n this.#messenger = messenger;\n this.#terminationTimeout = terminationTimeout;\n\n this.registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.#messenger.registerActionHandler(\n `${controllerName}:handleRpcRequest`,\n async (snapId: string, options: SnapRpcHookArgs) =>\n this.handleRpcRequest(snapId, options),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:executeSnap`,\n async (snapData: SnapExecutionData) => this.executeSnap(snapData),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateSnap`,\n async (snapId: string) => this.terminateSnap(snapId),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateAllSnaps`,\n async () => this.terminateAllSnaps(),\n );\n }\n\n /**\n * Performs additional necessary work during job termination. **MUST** be\n * implemented by concrete implementations. See\n * {@link AbstractExecutionService.terminate} for details.\n *\n * @param job - The object corresponding to the job to be terminated.\n */\n protected abstract terminateJob(job: Job<WorkerType>): void;\n\n /**\n * Terminates the job with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the job will fail with an error.\n * Throws an error if the specified job does not exist, or if termination\n * fails unexpectedly.\n *\n * @param jobId - The id of the job to be terminated.\n */\n public async terminate(jobId: string): Promise<void> {\n const jobWrapper = this.jobs.get(jobId);\n if (!jobWrapper) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n // Ping worker and tell it to run teardown, continue with termination if it takes too long\n const result = await withTimeout(\n this.command(jobId, {\n jsonrpc: '2.0',\n method: 'terminate',\n params: [],\n id: nanoid(),\n }),\n this.#terminationTimeout,\n );\n\n if (result === hasTimedOut || result !== 'OK') {\n // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and\n // hogging down the whole JS process.\n // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour\n // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same\n // JS process.\n logError(`Job \"${jobId}\" failed to terminate gracefully.`, result);\n }\n\n Object.values(jobWrapper.streams).forEach((stream) => {\n try {\n !stream.destroyed && stream.destroy();\n stream.removeAllListeners();\n } catch (error) {\n logError('Error while destroying stream', error);\n }\n });\n\n this.terminateJob(jobWrapper);\n\n this.#removeSnapAndJobMapping(jobId);\n this.jobs.delete(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @returns Information regarding the created job.\n */\n protected async initJob(): Promise<Job<WorkerType>> {\n const jobId = nanoid();\n const { streams, worker } = await this.initStreams(jobId);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pipeline(\n jsonRpcConnection.stream,\n streams.command,\n jsonRpcConnection.stream,\n (error) => {\n if (error) {\n logError(`Command stream failure.`, error);\n }\n },\n );\n\n rpcEngine.push(jsonRpcConnection.middleware);\n\n const envMetadata = {\n id: jobId,\n streams,\n rpcEngine,\n worker,\n };\n this.jobs.set(jobId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param jobId - The id of the job.\n * @returns The streams to communicate with the worker and the worker itself.\n */\n protected async initStreams(\n jobId: string,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const { worker, stream: envStream } = await this.initEnvStream(jobId);\n // Typecast justification: stream type mismatch\n const mux = setupMultiplex(\n envStream as unknown as Duplex,\n `Job: \"${jobId}\"`,\n );\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n\n // Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.\n // Also keep track of outbound request/responses\n const notificationHandler = (\n message:\n | JsonRpcRequest<unknown>\n | JsonRpcNotification<Json[] | Record<string, Json>>,\n ) => {\n if (!isJsonRpcNotification(message)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const snapId = this.#jobToSnapMap.get(jobId)!;\n if (message.method === 'OutboundRequest') {\n this.#messenger.publish('ExecutionService:outboundRequest', snapId);\n } else if (message.method === 'OutboundResponse') {\n this.#messenger.publish('ExecutionService:outboundResponse', snapId);\n } else if (message.method === 'UnhandledError') {\n if (isObject(message.params) && message.params.error) {\n this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n message.params.error as SnapErrorJson,\n );\n commandStream.removeListener('data', notificationHandler);\n } else {\n logError(\n new Error(\n `Received malformed \"${message.method}\" command stream notification.`,\n ),\n );\n }\n } else {\n logError(\n new Error(\n `Received unexpected command stream notification \"${message.method}\".`,\n ),\n );\n }\n };\n\n commandStream.on('data', notificationHandler);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n // Typecast: stream type mismatch\n return {\n streams: {\n command: commandStream as unknown as Duplex,\n rpc: rpcStream,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n _connection: envStream,\n },\n worker,\n };\n }\n\n /**\n * Abstract function implemented by implementing class that spins up a new worker for a job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n */\n protected abstract initEnvStream(jobId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n /**\n * Terminates the Snap with the specified ID. May throw an error if\n * termination unexpectedly fails, but will not fail if no job for the snap\n * with the specified ID is found.\n *\n * @param snapId - The ID of the snap to terminate.\n */\n async terminateSnap(snapId: string) {\n const jobId = this.#snapToJobMap.get(snapId);\n if (jobId) {\n await this.terminate(jobId);\n }\n }\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)),\n );\n this.#snapRpcHooks.clear();\n }\n\n /**\n * Gets the RPC request handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC request handler for the snap.\n */\n private getRpcRequestHandler(snapId: string) {\n return this.#snapRpcHooks.get(snapId);\n }\n\n /**\n * Initializes and executes a snap, setting up the communication channels to the snap etc.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param snapData - Data needed for Snap execution.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error.\n */\n async executeSnap(snapData: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapData.snapId)) {\n throw new Error(`Snap \"${snapData.snapId}\" is already being executed.`);\n }\n\n const job = await this.initJob();\n this.#mapSnapAndJob(snapData.snapId, job.id);\n\n // Ping the worker to ensure that it started up\n await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n });\n\n const rpcStream = job.streams.rpc as unknown as Duplex;\n\n this.setupSnapProvider(snapData.snapId, rpcStream);\n\n const result = await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: snapData,\n id: nanoid(),\n });\n this.#createSnapHooks(snapData.snapId, job.id);\n return result as string;\n }\n\n // Cannot be hash private yet because of tests.\n private async command(\n jobId: string,\n message: JsonRpcRequest<unknown>,\n ): Promise<unknown> {\n if (typeof message !== 'object') {\n throw new Error('Must send object.');\n }\n\n const job = this.jobs.get(jobId);\n if (!job) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n log('Parent: Sending Command', message);\n const response: PendingJsonRpcResponse<unknown> =\n await job.rpcEngine.handle(message);\n if (response.error) {\n throw new Error(response.error.message);\n }\n return response.result;\n }\n\n #removeSnapHooks(snapId: string) {\n this.#snapRpcHooks.delete(snapId);\n }\n\n #createSnapHooks(snapId: string, workerId: string) {\n const rpcHook = async ({ origin, handler, request }: SnapRpcHookArgs) => {\n return await this.command(workerId, {\n id: nanoid(),\n jsonrpc: '2.0',\n method: 'snapRpc',\n params: {\n origin,\n handler,\n request,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n #mapSnapAndJob(snapId: string, jobId: string): void {\n this.#snapToJobMap.set(snapId, jobId);\n this.#jobToSnapMap.set(jobId, snapId);\n }\n\n #removeSnapAndJobMapping(jobId: string): void {\n const snapId = this.#jobToSnapMap.get(jobId);\n if (!snapId) {\n throw new Error(`job: \"${jobId}\" has no mapped snap.`);\n }\n\n this.#jobToSnapMap.delete(jobId);\n this.#snapToJobMap.delete(snapId);\n this.#removeSnapHooks(snapId);\n }\n\n /**\n * Handle RPC request.\n *\n * @param snapId - The ID of the recipient snap.\n * @param options - Bag of options to pass to the RPC handler.\n * @returns Promise that can handle the request.\n */\n public async handleRpcRequest(\n snapId: string,\n options: SnapRpcHookArgs,\n ): Promise<unknown> {\n const rpcRequestHandler = await this.getRpcRequestHandler(snapId);\n\n if (!rpcRequestHandler) {\n throw new Error(\n `Snap execution service returned no RPC handler for running snap \"${snapId}\".`,\n );\n }\n\n return rpcRequestHandler(options);\n }\n}\n\n/**\n * Sets up stream multiplexing for the given stream.\n *\n * @param connectionStream - The stream to mux.\n * @param streamName - The name of the stream, for identification in errors.\n * @returns The multiplexed stream.\n */\nexport function setupMultiplex(\n connectionStream: Duplex,\n streamName: string,\n): ObjectMultiplex {\n const mux = new ObjectMultiplex();\n pipeline(\n connectionStream,\n // Typecast: stream type mismatch\n mux as unknown as Duplex,\n connectionStream,\n (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n },\n );\n return mux;\n}\n"],"names":["ObjectMultiplex","SNAP_STREAM_NAMES","logError","Duration","isJsonRpcNotification","isObject","JsonRpcEngine","createStreamMiddleware","nanoid","pipeline","log","hasTimedOut","withTimeout","controllerName","AbstractExecutionService","registerMessageHandlers","messenger","registerActionHandler","snapId","options","handleRpcRequest","snapData","executeSnap","terminateSnap","terminateAllSnaps","terminate","jobId","jobWrapper","jobs","get","Error","result","command","jsonrpc","method","params","id","terminationTimeout","Object","values","streams","forEach","stream","destroyed","destroy","removeAllListeners","error","terminateJob","removeSnapAndJobMapping","delete","initJob","worker","initStreams","rpcEngine","jsonRpcConnection","push","middleware","envMetadata","set","envStream","initEnvStream","mux","setupMultiplex","commandStream","createStream","COMMAND","notificationHandler","message","jobToSnapMap","publish","removeListener","on","rpcStream","JSON_RPC","rpc","_connection","snapToJobMap","Promise","all","keys","map","snapRpcHooks","clear","getRpcRequestHandler","has","job","mapSnapAndJob","setupSnapProvider","createSnapHooks","response","handle","rpcRequestHandler","constructor","Second","Map","workerId","rpcHook","origin","handler","request","target","removeSnapHooks","connectionStream","streamName"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,qBAAqB,6BAA6B;AAGzD,SAASC,iBAAiB,EAAEC,QAAQ,QAAQ,wBAAwB;AAEpE,SAASC,QAAQ,EAAEC,qBAAqB,EAAEC,QAAQ,QAAQ,kBAAkB;AAM5E,SAASC,aAAa,QAAQ,kBAAkB;AAChD,SAASC,sBAAsB,QAAQ,6BAA6B;AACpE,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,QAAQ,QAAQ,SAAS;AAGlC,SAASC,GAAG,QAAQ,aAAa;AACjC,SAASC,WAAW,EAAEC,WAAW,QAAQ,WAAW;AAQpD,MAAMC,iBAAiB;IA0BrB,6CAQA,6CAEA,6CAEA,0CAEA,mDAgUA,gDAIA,gDAkBA,8CAKA;AA5WF,OAAO,MAAeC;IAmCpB;;;GAGC,GACD,AAAQC,0BAAgC;QACtC,yBAAA,IAAI,EAAEC,YAAUC,qBAAqB,CACnC,CAAC,EAAEJ,eAAe,iBAAiB,CAAC,EACpC,OAAOK,QAAgBC,UACrB,IAAI,CAACC,gBAAgB,CAACF,QAAQC;QAGlC,yBAAA,IAAI,EAAEH,YAAUC,qBAAqB,CACnC,CAAC,EAAEJ,eAAe,YAAY,CAAC,EAC/B,OAAOQ,WAAgC,IAAI,CAACC,WAAW,CAACD;QAG1D,yBAAA,IAAI,EAAEL,YAAUC,qBAAqB,CACnC,CAAC,EAAEJ,eAAe,cAAc,CAAC,EACjC,OAAOK,SAAmB,IAAI,CAACK,aAAa,CAACL;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AAI,EAAEkD,eAAalB,GAAG,CAACxC,QAAQQ;IAC/B,yBAAA,IAAI,EAAE0C,eAAaV,GAAG,CAAChC,OAAOR;AAChC;AAEA,SAAA,wBAAyBQ,KAAa;IACpC,MAAMR,SAAS,yBAAA,IAAI,EAAEkD,eAAavC,GAAG,CAACH;IACtC,IAAI,CAACR,QAAQ;QACX,MAAM,IAAIY,MAAM,CAAC,MAAM,EAAEJ,MAAM,qBAAqB,CAAC;IACvD;IAEA,yBAAA,IAAI,EAAE0C,eAAanB,MAAM,CAACvB;IAC1B,yBAAA,IAAI,EAAEkD,eAAa3B,MAAM,CAAC/B;IAC1B,0BAAA,IAAI,EAAEmF,kBAAAA,sBAAN,IAAI,EAAkBnF;AACxB;AAyBF;;;;;;CAMC,GACD,OAAO,SAAS4C,eACdwC,gBAAwB,EACxBC,UAAkB;IAElB,MAAM1C,MAAM,IAAI7D;IAChBS,SACE6F,kBACA,iCAAiC;IACjCzC,KACAyC,kBACA,CAACxD;QACC,IAAIA,OAAO;YACTyD,aACIrG,SAAS,CAAC,CAAC,EAAEqG,WAAW,iBAAiB,CAAC,EAAEzD,SAC5C5C,SAAS4C;QACf;IACF;IAEF,OAAOe;AACT"}
1
+ {"version":3,"sources":["../../../src/services/AbstractExecutionService.ts"],"sourcesContent":["import { JsonRpcEngine } from '@metamask/json-rpc-engine';\nimport ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { JsonRpcError } from '@metamask/rpc-errors';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type {\n Json,\n JsonRpcNotification,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\nimport { Duration, isJsonRpcNotification, isObject } from '@metamask/utils';\nimport { createStreamMiddleware } from 'json-rpc-middleware-stream';\nimport { nanoid } from 'nanoid';\nimport { pipeline } from 'stream';\nimport type { Duplex } from 'stream';\n\nimport { log } from '../logging';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\n\nconst controllerName = 'ExecutionService';\n\nexport type SetupSnapProvider = (snapId: string, stream: Duplex) => void;\n\nexport type ExecutionServiceArgs = {\n setupSnapProvider: SetupSnapProvider;\n messenger: ExecutionServiceMessenger;\n terminationTimeout?: number;\n};\n\nexport type JobStreams = {\n command: Duplex;\n rpc: Duplex;\n _connection: BasePostMessageStream;\n};\n\nexport type Job<WorkerType> = {\n id: string;\n streams: JobStreams;\n rpcEngine: JsonRpcEngine;\n worker: WorkerType;\n};\n\nexport abstract class AbstractExecutionService<WorkerType>\n implements ExecutionService\n{\n #snapRpcHooks: Map<string, SnapRpcHook>;\n\n // Cannot be hash private yet because of tests.\n protected jobs: Map<string, Job<WorkerType>>;\n\n // Cannot be hash private yet because of tests.\n private readonly setupSnapProvider: SetupSnapProvider;\n\n #snapToJobMap: Map<string, string>;\n\n #jobToSnapMap: Map<string, string>;\n\n #messenger: ExecutionServiceMessenger;\n\n #terminationTimeout: number;\n\n constructor({\n setupSnapProvider,\n messenger,\n terminationTimeout = Duration.Second,\n }: ExecutionServiceArgs) {\n this.#snapRpcHooks = new Map();\n this.jobs = new Map();\n this.setupSnapProvider = setupSnapProvider;\n this.#snapToJobMap = new Map();\n this.#jobToSnapMap = new Map();\n this.#messenger = messenger;\n this.#terminationTimeout = terminationTimeout;\n\n this.registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.#messenger.registerActionHandler(\n `${controllerName}:handleRpcRequest`,\n async (snapId: string, options: SnapRpcHookArgs) =>\n this.handleRpcRequest(snapId, options),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:executeSnap`,\n async (snapData: SnapExecutionData) => this.executeSnap(snapData),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateSnap`,\n async (snapId: string) => this.terminateSnap(snapId),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateAllSnaps`,\n async () => this.terminateAllSnaps(),\n );\n }\n\n /**\n * Performs additional necessary work during job termination. **MUST** be\n * implemented by concrete implementations. See\n * {@link AbstractExecutionService.terminate} for details.\n *\n * @param job - The object corresponding to the job to be terminated.\n */\n protected abstract terminateJob(job: Job<WorkerType>): void;\n\n /**\n * Terminates the job with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the job will fail with an error.\n * Throws an error if the specified job does not exist, or if termination\n * fails unexpectedly.\n *\n * @param jobId - The id of the job to be terminated.\n */\n public async terminate(jobId: string): Promise<void> {\n const jobWrapper = this.jobs.get(jobId);\n if (!jobWrapper) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n // Ping worker and tell it to run teardown, continue with termination if it takes too long\n const result = await withTimeout(\n this.command(jobId, {\n jsonrpc: '2.0',\n method: 'terminate',\n params: [],\n id: nanoid(),\n }),\n this.#terminationTimeout,\n );\n\n if (result === hasTimedOut || result !== 'OK') {\n // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and\n // hogging down the whole JS process.\n // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour\n // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same\n // JS process.\n logError(`Job \"${jobId}\" failed to terminate gracefully.`, result);\n }\n\n Object.values(jobWrapper.streams).forEach((stream) => {\n try {\n !stream.destroyed && stream.destroy();\n stream.removeAllListeners();\n } catch (error) {\n logError('Error while destroying stream', error);\n }\n });\n\n this.terminateJob(jobWrapper);\n\n this.#removeSnapAndJobMapping(jobId);\n this.jobs.delete(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @returns Information regarding the created job.\n */\n protected async initJob(): Promise<Job<WorkerType>> {\n const jobId = nanoid();\n const { streams, worker } = await this.initStreams(jobId);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pipeline(\n jsonRpcConnection.stream,\n streams.command,\n jsonRpcConnection.stream,\n (error) => {\n if (error) {\n logError(`Command stream failure.`, error);\n }\n },\n );\n\n rpcEngine.push(jsonRpcConnection.middleware);\n\n const envMetadata = {\n id: jobId,\n streams,\n rpcEngine,\n worker,\n };\n this.jobs.set(jobId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param jobId - The id of the job.\n * @returns The streams to communicate with the worker and the worker itself.\n */\n protected async initStreams(\n jobId: string,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const { worker, stream: envStream } = await this.initEnvStream(jobId);\n const mux = setupMultiplex(envStream, `Job: \"${jobId}\"`);\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n\n // Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.\n // Also keep track of outbound request/responses\n const notificationHandler = (\n message:\n | JsonRpcRequest\n | JsonRpcNotification<Json[] | Record<string, Json>>,\n ) => {\n if (!isJsonRpcNotification(message)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const snapId = this.#jobToSnapMap.get(jobId)!;\n if (message.method === 'OutboundRequest') {\n this.#messenger.publish('ExecutionService:outboundRequest', snapId);\n } else if (message.method === 'OutboundResponse') {\n this.#messenger.publish('ExecutionService:outboundResponse', snapId);\n } else if (message.method === 'UnhandledError') {\n if (isObject(message.params) && message.params.error) {\n this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n message.params.error as SnapErrorJson,\n );\n commandStream.removeListener('data', notificationHandler);\n } else {\n logError(\n new Error(\n `Received malformed \"${message.method}\" command stream notification.`,\n ),\n );\n }\n } else {\n logError(\n new Error(\n `Received unexpected command stream notification \"${message.method}\".`,\n ),\n );\n }\n };\n\n commandStream.on('data', notificationHandler);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n // Typecast: stream type mismatch\n return {\n streams: {\n command: commandStream,\n rpc: rpcStream,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n _connection: envStream,\n },\n worker,\n };\n }\n\n /**\n * Abstract function implemented by implementing class that spins up a new worker for a job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n */\n protected abstract initEnvStream(jobId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n /**\n * Terminates the Snap with the specified ID. May throw an error if\n * termination unexpectedly fails, but will not fail if no job for the snap\n * with the specified ID is found.\n *\n * @param snapId - The ID of the snap to terminate.\n */\n async terminateSnap(snapId: string) {\n const jobId = this.#snapToJobMap.get(snapId);\n if (jobId) {\n await this.terminate(jobId);\n }\n }\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)),\n );\n this.#snapRpcHooks.clear();\n }\n\n /**\n * Gets the RPC request handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC request handler for the snap.\n */\n private getRpcRequestHandler(snapId: string) {\n return this.#snapRpcHooks.get(snapId);\n }\n\n /**\n * Initializes and executes a snap, setting up the communication channels to the snap etc.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param snapData - Data needed for Snap execution.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error.\n */\n async executeSnap(snapData: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapData.snapId)) {\n throw new Error(`Snap \"${snapData.snapId}\" is already being executed.`);\n }\n\n const job = await this.initJob();\n this.#mapSnapAndJob(snapData.snapId, job.id);\n\n // Ping the worker to ensure that it started up\n await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n });\n\n const rpcStream = job.streams.rpc;\n\n this.setupSnapProvider(snapData.snapId, rpcStream);\n\n const result = await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: snapData,\n id: nanoid(),\n });\n this.#createSnapHooks(snapData.snapId, job.id);\n return result as string;\n }\n\n // Cannot be hash private yet because of tests.\n private async command(\n jobId: string,\n message: JsonRpcRequest,\n ): Promise<Json | undefined> {\n if (typeof message !== 'object') {\n throw new Error('Must send object.');\n }\n\n const job = this.jobs.get(jobId);\n if (!job) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n log('Parent: Sending Command', message);\n const response: PendingJsonRpcResponse<Json> = await job.rpcEngine.handle(\n message,\n );\n\n if (response.error) {\n throw new JsonRpcError(\n response.error.code,\n response.error.message,\n response.error.data,\n );\n }\n\n return response.result;\n }\n\n #removeSnapHooks(snapId: string) {\n this.#snapRpcHooks.delete(snapId);\n }\n\n #createSnapHooks(snapId: string, workerId: string) {\n const rpcHook = async ({ origin, handler, request }: SnapRpcHookArgs) => {\n return await this.command(workerId, {\n id: nanoid(),\n jsonrpc: '2.0',\n method: 'snapRpc',\n params: {\n origin,\n handler,\n request: request as JsonRpcRequest,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n #mapSnapAndJob(snapId: string, jobId: string): void {\n this.#snapToJobMap.set(snapId, jobId);\n this.#jobToSnapMap.set(jobId, snapId);\n }\n\n #removeSnapAndJobMapping(jobId: string): void {\n const snapId = this.#jobToSnapMap.get(jobId);\n if (!snapId) {\n throw new Error(`job: \"${jobId}\" has no mapped snap.`);\n }\n\n this.#jobToSnapMap.delete(jobId);\n this.#snapToJobMap.delete(snapId);\n this.#removeSnapHooks(snapId);\n }\n\n /**\n * Handle RPC request.\n *\n * @param snapId - The ID of the recipient snap.\n * @param options - Bag of options to pass to the RPC handler.\n * @returns Promise that can handle the request.\n */\n public async handleRpcRequest(\n snapId: string,\n options: SnapRpcHookArgs,\n ): Promise<unknown> {\n const rpcRequestHandler = this.getRpcRequestHandler(snapId);\n\n if (!rpcRequestHandler) {\n throw new Error(\n `Snap execution service returned no RPC handler for running snap \"${snapId}\".`,\n );\n }\n\n return rpcRequestHandler(options);\n }\n}\n\n/**\n * Sets up stream multiplexing for the given stream.\n *\n * @param connectionStream - The stream to mux.\n * @param streamName - The name of the stream, for identification in errors.\n * @returns The multiplexed stream.\n */\nexport function setupMultiplex(\n connectionStream: Duplex,\n streamName: string,\n): ObjectMultiplex {\n const mux = new ObjectMultiplex();\n pipeline(connectionStream, mux, connectionStream, (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n });\n return mux;\n}\n"],"names":["JsonRpcEngine","ObjectMultiplex","JsonRpcError","SNAP_STREAM_NAMES","logError","Duration","isJsonRpcNotification","isObject","createStreamMiddleware","nanoid","pipeline","log","hasTimedOut","withTimeout","controllerName","AbstractExecutionService","registerMessageHandlers","messenger","registerActionHandler","snapId","options","handleRpcRequest","snapData","executeSnap","terminateSnap","terminateAllSnaps","terminate","jobId","jobWrapper","jobs","get","Error","result","command","jsonrpc","method","params","id","terminationTimeout","Object","values","streams","forEach","stream","destroyed","destroy","removeAllListeners","error","terminateJob","removeSnapAndJobMapping","delete","initJob","worker","initStreams","rpcEngine","jsonRpcConnection","push","middleware","envMetadata","set","envStream","initEnvStream","mux","setupMultiplex","commandStream","createStream","COMMAND","notificationHandler","message","jobToSnapMap","publish","removeListener","on","rpcStream","JSON_RPC","rpc","_connection","snapToJobMap","Promise","all","keys","map","snapRpcHooks","clear","getRpcRequestHandler","has","job","mapSnapAndJob","setupSnapProvider","createSnapHooks","response","handle","code","data","rpcRequestHandler","constructor","Second","Map","workerId","rpcHook","origin","handler","request","target","removeSnapHooks","connectionStream","streamName"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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tC,IAAI,CAACR,QAAQ;QACX,MAAM,IAAIY,MAAM,CAAC,MAAM,EAAEJ,MAAM,qBAAqB,CAAC;IACvD;IAEA,yBAAA,IAAI,EAAE0C,eAAanB,MAAM,CAACvB;IAC1B,yBAAA,IAAI,EAAEkD,eAAa3B,MAAM,CAAC/B;IAC1B,0BAAA,IAAI,EAAEqF,kBAAAA,sBAAN,IAAI,EAAkBrF;AACxB;AAyBF;;;;;;CAMC,GACD,OAAO,SAAS4C,eACd0C,gBAAwB,EACxBC,UAAkB;IAElB,MAAM5C,MAAM,IAAI7D;IAChBS,SAAS+F,kBAAkB3C,KAAK2C,kBAAkB,CAAC1D;QACjD,IAAIA,OAAO;YACT2D,aACItG,SAAS,CAAC,CAAC,EAAEsG,WAAW,iBAAiB,CAAC,EAAE3D,SAC5C3C,SAAS2C;QACf;IACF;IACA,OAAOe;AACT"}
@@ -63,11 +63,11 @@ function _define_property(obj, key, value) {
63
63
  }
64
64
  import { BaseControllerV2 as BaseController } from '@metamask/base-controller';
65
65
  import { SubjectType } from '@metamask/permission-controller';
66
- import { WALLET_SNAP_PERMISSION_KEY } from '@metamask/rpc-methods';
67
- import { assertIsSnapManifest, assertIsValidSnapId, DEFAULT_ENDOWMENTS, DEFAULT_REQUESTED_SNAP_VERSION, getErrorMessage, HandlerType, isOriginAllowed, logError, normalizeRelative, resolveVersionRange, SnapCaveatType, SnapStatus, SnapStatusEvents, validateFetchedSnap } from '@metamask/snaps-utils';
66
+ import { rpcErrors } from '@metamask/rpc-errors';
67
+ import { WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-rpc-methods';
68
+ import { assertIsSnapManifest, assertIsValidSnapId, AuxiliaryFileEncoding, DEFAULT_ENDOWMENTS, DEFAULT_REQUESTED_SNAP_VERSION, encodeAuxiliaryFile, getErrorMessage, HandlerType, isOriginAllowed, logError, normalizeRelative, resolveVersionRange, SnapCaveatType, SnapStatus, SnapStatusEvents, validateFetchedSnap, unwrapError } from '@metamask/snaps-utils';
68
69
  import { assert, assertIsJsonRpcRequest, Duration, gtRange, gtVersion, hasProperty, inMilliseconds, isNonEmptyArray, isValidSemVerRange, satisfiesVersionRange, timeSince } from '@metamask/utils';
69
70
  import { createMachine, interpret } from '@xstate/fsm';
70
- import { ethErrors } from 'eth-rpc-errors';
71
71
  import { nanoid } from 'nanoid';
72
72
  import { forceStrict, validateMachine } from '../fsm';
73
73
  import { log } from '../logging';
@@ -93,7 +93,6 @@ const TRUNCATED_SNAP_PROPERTIES = new Set([
93
93
  'blocked'
94
94
  ]);
95
95
  const defaultState = {
96
- snapErrors: {},
97
96
  snaps: {},
98
97
  snapStates: {}
99
98
  };
@@ -149,7 +148,7 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
149
148
  * Safely revokes all permissions granted to a Snap.
150
149
  *
151
150
  * @param snapId - The snap ID.
152
- */ _revokeAllSnapPermissions = /*#__PURE__*/ new WeakSet(), _createApproval = /*#__PURE__*/ new WeakSet(), _updateApproval = /*#__PURE__*/ new WeakSet(), _add = /*#__PURE__*/ new WeakSet(), _startSnap = /*#__PURE__*/ new WeakSet(), _getEndowments = /*#__PURE__*/ new WeakSet(), /**
151
+ */ _revokeAllSnapPermissions = /*#__PURE__*/ new WeakSet(), _createApproval = /*#__PURE__*/ new WeakSet(), _updateApproval = /*#__PURE__*/ new WeakSet(), _resolveAllowlistVersion = /*#__PURE__*/ new WeakSet(), _add = /*#__PURE__*/ new WeakSet(), _startSnap = /*#__PURE__*/ new WeakSet(), _getEndowments = /*#__PURE__*/ new WeakSet(), /**
153
152
  * Sets a snap in state. Called when a snap is installed or updated. Performs
154
153
  * various validation checks on the received arguments, and will throw if
155
154
  * validation fails.
@@ -220,8 +219,8 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
220
219
  return _class_private_method_get(this, _unblockSnap, unblockSnap).call(this, snapId);
221
220
  }));
222
221
  }
223
- _onUnhandledSnapError(snapId, error) {
224
- this.stopSnap(snapId, SnapStatusEvents.Crash).then(()=>this.addSnapError(error)).catch((stopSnapError)=>{
222
+ _onUnhandledSnapError(snapId, _error) {
223
+ this.stopSnap(snapId, SnapStatusEvents.Crash).catch((stopSnapError)=>{
225
224
  // TODO: Decide how to handle errors.
226
225
  logError(stopSnapError);
227
226
  });
@@ -397,35 +396,6 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
397
396
  });
398
397
  }
399
398
  /**
400
- * Adds error from a snap to the SnapController state.
401
- *
402
- * @param snapError - The error to store on the SnapController.
403
- */ addSnapError(snapError) {
404
- this.update((state)=>{
405
- const id = nanoid();
406
- state.snapErrors[id] = {
407
- ...snapError,
408
- internalID: id
409
- };
410
- });
411
- }
412
- /**
413
- * Removes an error by internalID from the SnapControllers state.
414
- *
415
- * @param internalID - The internal error ID to remove on the SnapController.
416
- */ removeSnapError(internalID) {
417
- this.update((state)=>{
418
- delete state.snapErrors[internalID];
419
- });
420
- }
421
- /**
422
- * Clears all errors from the SnapControllers state.
423
- */ clearSnapErrors() {
424
- this.update((state)=>{
425
- state.snapErrors = {};
426
- });
427
- }
428
- /**
429
399
  * Gets the own state of the snap with the given id.
430
400
  * This is distinct from the state MetaMask uses to manage snaps.
431
401
  *
@@ -437,6 +407,22 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
437
407
  return state ?? null;
438
408
  }
439
409
  /**
410
+ * Gets a static auxiliary snap file in a chosen file encoding.
411
+ *
412
+ * @param snapId - The id of the Snap whose state to get.
413
+ * @param path - The path to the requested file.
414
+ * @param encoding - An optional requested file encoding.
415
+ * @returns The file requested in the chosen file encoding or null if the file is not found.
416
+ */ getSnapFile(snapId, path, encoding = AuxiliaryFileEncoding.Base64) {
417
+ const snap = this.getExpect(snapId);
418
+ const normalizedPath = normalizeRelative(path);
419
+ const value = snap.auxiliaryFiles?.find((file)=>file.path === normalizedPath)?.value;
420
+ if (!value) {
421
+ return null;
422
+ }
423
+ return encodeAuxiliaryFile(value, encoding);
424
+ }
425
+ /**
440
426
  * Completely clear the controller's state: delete all associated data,
441
427
  * handlers, event listeners, and permissions; tear down all snap providers.
442
428
  */ async clearState() {
@@ -592,12 +578,13 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
592
578
  assertIsValidSnapId(snapId);
593
579
  const [error, version] = resolveVersionRange(rawVersion);
594
580
  if (error) {
595
- throw ethErrors.rpc.invalidParams(`The "version" field must be a valid SemVer version range if specified. Received: "${rawVersion}".`);
581
+ throw rpcErrors.invalidParams(`The "version" field must be a valid SemVer version range if specified. Received: "${rawVersion}".`);
596
582
  }
597
583
  const location = _class_private_field_get(this, _detectSnapLocation).call(this, snapId, {
598
584
  versionRange: version,
599
585
  fetch: _class_private_field_get(this, _fetchFunction),
600
- allowLocal: _class_private_field_get(this, _featureFlags).allowLocalSnaps
586
+ allowLocal: _class_private_field_get(this, _featureFlags).allowLocalSnaps,
587
+ resolveVersion: async (range)=>_class_private_field_get(this, _featureFlags).requireAllowlist ? await _class_private_method_get(this, _resolveAllowlistVersion, resolveAllowlistVersion).call(this, snapId, range) : range
601
588
  });
602
589
  // Existing snaps may need to be updated, unless they should be re-installed (e.g. local snaps)
603
590
  // Everything else is treated as an install
@@ -621,8 +608,8 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
621
608
  result[snapId] = await this.processRequestedSnap(origin, snapId, location, version);
622
609
  }
623
610
  // Once we finish all installs / updates, emit events.
624
- pendingInstalls.forEach((snapId)=>this.messagingSystem.publish(`SnapController:snapInstalled`, this.getTruncatedExpect(snapId)));
625
- pendingUpdates.forEach(({ snapId, oldVersion })=>this.messagingSystem.publish(`SnapController:snapUpdated`, this.getTruncatedExpect(snapId), oldVersion));
611
+ pendingInstalls.forEach((snapId)=>this.messagingSystem.publish(`SnapController:snapInstalled`, this.getTruncatedExpect(snapId), origin));
612
+ pendingUpdates.forEach(({ snapId, oldVersion })=>this.messagingSystem.publish(`SnapController:snapUpdated`, this.getTruncatedExpect(snapId), oldVersion, origin));
626
613
  snapIds.forEach((snapId)=>_class_private_field_get(this, _rollbackSnapshots).delete(snapId));
627
614
  } catch (error) {
628
615
  const installed = pendingInstalls.filter((snapId)=>this.has(snapId));
@@ -655,7 +642,7 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
655
642
  return await this.updateSnap(origin, snapId, location, versionRange, // Since we are requesting an update from within processRequestedSnap,
656
643
  // we disable the emitting of the snapUpdated event and rely on the caller
657
644
  // to publish this event after the update is complete.
658
- // This is necesary as installSnaps may be installing multiple snaps
645
+ // This is necessary as installSnaps may be installing multiple snaps
659
646
  // and we don't want to emit events prematurely.
660
647
  false);
661
648
  }
@@ -735,23 +722,25 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
735
722
  try {
736
723
  const snap = this.getExpect(snapId);
737
724
  const newSnap = await _class_private_method_get(this, _fetchSnap, fetchSnap).call(this, snapId, location);
738
- const newVersion = newSnap.manifest.result.version;
725
+ const { sourceCode: sourceCodeFile, manifest: manifestFile } = newSnap.files;
726
+ const manifest = manifestFile.result;
727
+ const newVersion = manifest.version;
739
728
  if (!gtVersion(newVersion, snap.version)) {
740
- throw ethErrors.rpc.invalidParams(`Snap "${snapId}@${snap.version}" is already installed. Couldn't update to a version inside requested "${newVersionRange}" range.`);
729
+ throw rpcErrors.invalidParams(`Snap "${snapId}@${snap.version}" is already installed. Couldn't update to a version inside requested "${newVersionRange}" range.`);
741
730
  }
742
731
  if (!satisfiesVersionRange(newVersion, newVersionRange)) {
743
732
  throw new Error(`Version mismatch. Manifest for "${snapId}" specifies version "${newVersion}" which doesn't satisfy requested version range "${newVersionRange}".`);
744
733
  }
745
734
  await _class_private_method_get(this, _assertIsInstallAllowed, assertIsInstallAllowed).call(this, snapId, {
746
735
  version: newVersion,
747
- checksum: newSnap.manifest.result.source.shasum
736
+ checksum: manifest.source.shasum
748
737
  });
749
- const processedPermissions = processSnapPermissions(newSnap.manifest.result.initialPermissions);
738
+ const processedPermissions = processSnapPermissions(manifest.initialPermissions);
750
739
  _class_private_method_get(this, _validateSnapPermissions, validateSnapPermissions).call(this, processedPermissions);
751
740
  const { newPermissions, unusedPermissions, approvedPermissions } = _class_private_method_get(this, _calculatePermissionsChange, calculatePermissionsChange).call(this, snapId, processedPermissions);
752
741
  _class_private_method_get(this, _updateApproval, updateApproval).call(this, pendingApproval.id, {
753
742
  permissions: newPermissions,
754
- newVersion: newSnap.manifest.result.version,
743
+ newVersion: manifest.version,
755
744
  newPermissions,
756
745
  approvedPermissions,
757
746
  unusedPermissions,
@@ -770,7 +759,6 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
770
759
  _class_private_method_get(this, _set, set).call(this, {
771
760
  origin,
772
761
  id: snapId,
773
- manifest: newSnap.manifest,
774
762
  files: newSnap.files,
775
763
  isUpdate: true
776
764
  });
@@ -795,8 +783,7 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
795
783
  rollbackSnapshot.permissions.granted = Object.keys(approvedNewPermissions);
796
784
  rollbackSnapshot.permissions.requestData = requestData;
797
785
  }
798
- const normalizedSourcePath = normalizeRelative(newSnap.manifest.result.source.location.npm.filePath);
799
- const sourceCode = newSnap.files.find((file)=>file.path === normalizedSourcePath)?.toString();
786
+ const sourceCode = sourceCodeFile.toString();
800
787
  assert(typeof sourceCode === 'string' && sourceCode.length > 0, `Invalid source code for snap "${snapId}".`);
801
788
  try {
802
789
  await _class_private_method_get(this, _startSnap, startSnap).call(this, {
@@ -808,7 +795,7 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
808
795
  }
809
796
  const truncatedSnap = this.getTruncatedExpect(snapId);
810
797
  if (emitEvent) {
811
- this.messagingSystem.publish('SnapController:snapUpdated', truncatedSnap, snap.version);
798
+ this.messagingSystem.publish('SnapController:snapUpdated', truncatedSnap, snap.version, origin);
812
799
  }
813
800
  _class_private_method_get(this, _updateApproval, updateApproval).call(this, pendingApproval.id, {
814
801
  loading: false,
@@ -878,6 +865,8 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
878
865
  /* eslint-disable @typescript-eslint/unbound-method */ this.messagingSystem.unsubscribe('ExecutionService:unhandledError', this._onUnhandledSnapError);
879
866
  this.messagingSystem.unsubscribe('ExecutionService:outboundRequest', this._onOutboundRequest);
880
867
  this.messagingSystem.unsubscribe('ExecutionService:outboundResponse', this._onOutboundResponse);
868
+ this.messagingSystem.clearEventSubscriptions('SnapController:snapInstalled');
869
+ this.messagingSystem.clearEventSubscriptions('SnapController:snapUpdated');
881
870
  /* eslint-enable @typescript-eslint/unbound-method */ }
882
871
  /**
883
872
  * Passes a JSON-RPC request object to the RPC handler function of a snap.
@@ -927,17 +916,15 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
927
916
  super({
928
917
  messenger,
929
918
  metadata: {
930
- snapErrors: {
931
- persist: false,
932
- anonymous: false
933
- },
934
919
  snapStates: {
935
920
  persist: true,
936
921
  anonymous: false
937
922
  },
938
923
  snaps: {
939
924
  persist: (snaps)=>{
940
- return Object.values(snaps).map((snap)=>{
925
+ return Object.values(snaps)// We should not persist snaps that are in the installing state,
926
+ // since they haven't completed installation and would be unusable
927
+ .filter((snap)=>snap.status !== SnapStatus.Installing).map((snap)=>{
941
928
  return {
942
929
  ...snap,
943
930
  // At the time state is rehydrated, no snap will be running.
@@ -980,6 +967,7 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
980
967
  _class_private_method_init(this, _revokeAllSnapPermissions);
981
968
  _class_private_method_init(this, _createApproval);
982
969
  _class_private_method_init(this, _updateApproval);
970
+ _class_private_method_init(this, _resolveAllowlistVersion);
983
971
  /**
984
972
  * Returns a promise representing the complete installation of the requested snap.
985
973
  * If the snap is already being installed, the previously pending promise will be returned.
@@ -1005,8 +993,6 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
1005
993
  /**
1006
994
  * Fetches the manifest and source code of a snap.
1007
995
  *
1008
- * This function is not hash private yet because of tests.
1009
- *
1010
996
  * @param snapId - The id of the Snap.
1011
997
  * @param location - Source from which snap will be fetched.
1012
998
  * @returns A tuple of the Snap manifest object and the Snap source code.
@@ -1215,13 +1201,13 @@ function registerMessageHandlers() {
1215
1201
  this.messagingSystem.registerActionHandler(`${controllerName}:remove`, async (...args)=>this.removeSnap(...args));
1216
1202
  this.messagingSystem.registerActionHandler(`${controllerName}:getPermitted`, (...args)=>this.getPermittedSnaps(...args));
1217
1203
  this.messagingSystem.registerActionHandler(`${controllerName}:install`, async (...args)=>this.installSnaps(...args));
1218
- this.messagingSystem.registerActionHandler(`${controllerName}:removeSnapError`, (...args)=>this.removeSnapError(...args));
1219
1204
  this.messagingSystem.registerActionHandler(`${controllerName}:getAll`, (...args)=>this.getAllSnaps(...args));
1220
1205
  this.messagingSystem.registerActionHandler(`${controllerName}:incrementActiveReferences`, (...args)=>this.incrementActiveReferences(...args));
1221
1206
  this.messagingSystem.registerActionHandler(`${controllerName}:decrementActiveReferences`, (...args)=>this.decrementActiveReferences(...args));
1222
1207
  this.messagingSystem.registerActionHandler(`${controllerName}:getRegistryMetadata`, async (...args)=>this.getRegistryMetadata(...args));
1223
1208
  this.messagingSystem.registerActionHandler(`${controllerName}:disconnectOrigin`, (...args)=>this.removeSnapFromSubject(...args));
1224
1209
  this.messagingSystem.registerActionHandler(`${controllerName}:revokeDynamicPermissions`, (...args)=>this.revokeDynamicSnapPermissions(...args));
1210
+ this.messagingSystem.registerActionHandler(`${controllerName}:getFile`, (...args)=>this.getSnapFile(...args));
1225
1211
  }
1226
1212
  function pollForLastRequestStatus() {
1227
1213
  _class_private_field_set(this, _timeoutForLastRequestStatus, setTimeout(()=>{
@@ -1265,7 +1251,7 @@ async function assertIsInstallAllowed(snapId, snapInfo) {
1265
1251
  if (result.status === SnapsRegistryStatus.Blocked) {
1266
1252
  throw new Error(`Cannot install version "${snapInfo.version}" of snap "${snapId}": The version is blocked. ${result.reason?.explanation ?? ''}`);
1267
1253
  } else if (_class_private_field_get(this, _featureFlags).requireAllowlist && result.status !== SnapsRegistryStatus.Verified) {
1268
- throw new Error(`Cannot install version "${snapInfo.version}" of snap "${snapId}": The snap is not on the allow list.`);
1254
+ throw new Error(`Cannot install version "${snapInfo.version}" of snap "${snapId}": The snap is not on the allowlist.`);
1269
1255
  }
1270
1256
  }
1271
1257
  async function stopSnapsLastRequestPastMax() {
@@ -1331,6 +1317,9 @@ function updateApproval(id, requestState) {
1331
1317
  // Do nothing
1332
1318
  }
1333
1319
  }
1320
+ async function resolveAllowlistVersion(snapId, versionRange) {
1321
+ return await this.messagingSystem.call('SnapsRegistry:resolveVersion', snapId, versionRange);
1322
+ }
1334
1323
  async function add(args) {
1335
1324
  const { id: snapId, location, versionRange } = args;
1336
1325
  _class_private_method_get(this, _setupRuntime, setupRuntime).call(this, snapId, {
@@ -1344,7 +1333,7 @@ async function add(args) {
1344
1333
  // to null in the authorize() method.
1345
1334
  runtime.installPromise = (async ()=>{
1346
1335
  const fetchedSnap = await _class_private_method_get(this, _fetchSnap, fetchSnap).call(this, snapId, location);
1347
- const manifest = fetchedSnap.manifest.result;
1336
+ const manifest = fetchedSnap.files.manifest.result;
1348
1337
  if (!satisfiesVersionRange(manifest.version, versionRange)) {
1349
1338
  throw new Error(`Version mismatch. Manifest for "${snapId}" specifies version "${manifest.version}" which doesn't satisfy requested version range "${versionRange}".`);
1350
1339
  }
@@ -1414,15 +1403,16 @@ async function getEndowments(snapId) {
1414
1403
  return dedupedEndowments;
1415
1404
  }
1416
1405
  function set(args) {
1417
- const { id: snapId, origin, manifest, files, isUpdate = false } = args;
1406
+ const { id: snapId, origin, files, isUpdate = false } = args;
1407
+ const { manifest, sourceCode: sourceCodeFile, svgIcon, auxiliaryFiles: rawAuxiliaryFiles } = files;
1418
1408
  assertIsSnapManifest(manifest.result);
1419
1409
  const { version } = manifest.result;
1420
- const normalizedSourcePath = normalizeRelative(manifest.result.source.location.npm.filePath);
1421
- const { iconPath } = manifest.result.source.location.npm;
1422
- const normalizedIconPath = iconPath && normalizeRelative(iconPath);
1423
- const sourceCode = files.find((file)=>file.path === normalizedSourcePath)?.toString();
1424
- const svgIcon = normalizedIconPath ? files.find((file)=>file.path === normalizedIconPath) : undefined;
1410
+ const sourceCode = sourceCodeFile.toString();
1425
1411
  assert(typeof sourceCode === 'string' && sourceCode.length > 0, `Invalid source code for snap "${snapId}".`);
1412
+ const auxiliaryFiles = rawAuxiliaryFiles.map((file)=>({
1413
+ path: file.path,
1414
+ value: file.toString('base64')
1415
+ }));
1426
1416
  const snapsState = this.state.snaps;
1427
1417
  const existingSnap = snapsState[snapId];
1428
1418
  const previousVersionHistory = existingSnap?.versionHistory ?? [];
@@ -1447,7 +1437,8 @@ function set(args) {
1447
1437
  status: _class_private_field_get(this, _statusMachine).config.initial,
1448
1438
  sourceCode,
1449
1439
  version,
1450
- versionHistory
1440
+ versionHistory,
1441
+ auxiliaryFiles
1451
1442
  };
1452
1443
  // If the snap was blocked, it isn't any longer
1453
1444
  delete snap.blockInformation;
@@ -1475,19 +1466,15 @@ async function fetchSnap(snapId, location) {
1475
1466
  const sourceCode = await location.fetch(manifest.result.source.location.npm.filePath);
1476
1467
  const { iconPath } = manifest.result.source.location.npm;
1477
1468
  const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;
1478
- const files = [
1479
- sourceCode
1480
- ];
1481
- if (svgIcon) {
1482
- files.push(svgIcon);
1483
- }
1484
- validateFetchedSnap({
1469
+ const auxiliaryFiles = manifest.result.source.files ? await Promise.all(manifest.result.source.files.map(async (filePath)=>location.fetch(filePath))) : [];
1470
+ const files = {
1485
1471
  manifest,
1486
1472
  sourceCode,
1487
- svgIcon
1488
- });
1473
+ svgIcon,
1474
+ auxiliaryFiles
1475
+ };
1476
+ validateFetchedSnap(files);
1489
1477
  return {
1490
- manifest,
1491
1478
  files,
1492
1479
  location
1493
1480
  };
@@ -1556,8 +1543,11 @@ function getRpcRequestHandler(snapId) {
1556
1543
  _class_private_method_get(this, _recordSnapRpcRequestFinish, recordSnapRpcRequestFinish).call(this, snapId, request.id);
1557
1544
  return result;
1558
1545
  } catch (error) {
1559
- await this.stopSnap(snapId, SnapStatusEvents.Crash);
1560
- throw error;
1546
+ const [jsonRpcError, handled] = unwrapError(error);
1547
+ if (!handled) {
1548
+ await this.stopSnap(snapId, SnapStatusEvents.Crash);
1549
+ }
1550
+ throw jsonRpcError;
1561
1551
  }
1562
1552
  };
1563
1553
  runtime.rpcHandler = rpcHandler;