@metamask/snaps-controllers 0.26.2 → 0.27.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.
@@ -1 +1 @@
1
- {"version":3,"file":"MultiChainController.js","sourceRoot":"","sources":["../../src/multichain/MultiChainController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,+DAGmC;AAQnC,uDAmB+B;AAC/B,2CAAsD;AACtD,mCAAgC;AAEhC,oCAOkB;AAClB,yDAAyE;AACzE,yCAAsD;AAEtD,MAAM,cAAc,GAAG,sBAAsB,CAAC;AAE9C,MAAM,YAAY,GAA8B;IAC9C,QAAQ,EAAE,EAAE;CACb,CAAC;AAyCF,uEAAuE;AACvE,MAAa,oBAAqB,SAAQ,kCAIzC;IAGC;;;;;;OAMG;IACH,YAAY,EAAE,SAAS,EAAE,MAAM,EAA4B;QACzD,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE;gBACR,QAAQ,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE;aAC/C;YACD,IAAI,EAAE,cAAc;YACpB,KAAK,EAAE,YAAY;SACpB,CAAC,CAAC;QAjBL,+CAAyB;QAmBvB,uBAAA,IAAI,gCAAW,MAAM,MAAA,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,UAAU,CAAC,MAAc;QACvB,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,MAAc;QAC/B,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACxC,IAAA,cAAM,EAAC,OAAO,EAAE,sBAAsB,CAAC,CAAC;QAExC,MAAM,uBAAA,IAAI,oCAAQ,MAAZ,IAAI,EAAS,MAAM,EAAE;YACzB,MAAM,EAAE,oCAAoC;SAC7C,CAAC,CAAC;QAEH,IAAI,CAA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E,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YACb,IAAI,GAAG,KAAK,IAAI,EAAE;gBAChB,GAAG,CAAC,IAAA,mCAAqB,EAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC;aAC7C;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EAAE,EAAE,CAAC,CAAC;QAEP,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,uCAAuC,EAAE;YACjE,mBAAmB;YACnB,OAAO,EAAE,EAAE,MAAM,EAAE;SACpB,CAAC,CAAC;QAEH,OAAO,gBAAgB,CAAC;IAC1B,CAAC;CACF;AAtdD,oDAsdC","sourcesContent":["import { AddApprovalRequest } from '@metamask/approval-controller';\nimport {\n BaseControllerV2 as BaseController,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n GetPermissions,\n GrantPermissions,\n HasPermission,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { SnapKeyring } from '@metamask/snaps-types';\nimport {\n parseAccountId,\n AccountId,\n parseChainId,\n ChainId,\n ConnectArguments,\n HandlerType,\n NamespaceId,\n RequestArguments,\n RequestNamespace,\n Session,\n TruncatedSnap,\n SnapId,\n fromEntries,\n SessionNamespace,\n flatten,\n getSnapPermissionName,\n isAccountIdArray,\n Namespaces,\n} from '@metamask/snaps-utils';\nimport { hasProperty, assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\nimport {\n GetAllSnaps,\n HandleSnapRequest,\n IncrementActiveReferences,\n DecrementActiveReferences,\n SnapEndowments,\n getRunnableSnaps,\n} from '../snaps';\nimport { getKeyringCaveatNamespaces } from '../snaps/endowments/keyring';\nimport { findMatchingKeyringSnaps } from './matching';\n\nconst controllerName = 'MultiChainController';\n\nconst defaultState: MultiChainControllerState = {\n sessions: {},\n};\n\ntype AllowedActions =\n | GetAllSnaps\n | IncrementActiveReferences\n | DecrementActiveReferences\n | HandleSnapRequest\n | GetPermissions\n | HasPermission\n | AddApprovalRequest\n | GrantPermissions;\n\ntype MultiChainControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n never,\n AllowedActions['type'],\n never\n>;\n\ntype SessionData = {\n origin: string;\n requestedNamespaces: Record<NamespaceId, RequestNamespace>;\n providedNamespaces: Record<NamespaceId, RequestNamespace>;\n handlingSnaps: Record<NamespaceId, SnapId>;\n};\n\ntype MultiChainControllerState = {\n sessions: { [origin: string]: SessionData };\n};\n\ntype Notify = (\n origin: string,\n data: { method: string; params?: Record<string, unknown> },\n) => Promise<void>;\n\ntype MultiChainControllerArgs = {\n notify: Notify;\n messenger: MultiChainControllerMessenger;\n};\n\n// TODO(ritave): Support for legacy ethereum operations, not just snaps\nexport class MultiChainController extends BaseController<\n typeof controllerName,\n MultiChainControllerState,\n MultiChainControllerMessenger\n> {\n readonly #notify: Notify;\n\n /**\n * Construct a new {@link MultiChainController} instance.\n *\n * @param args - The arguments to construct the controller with.\n * @param args.messenger - The controller messenger to use.\n * @param args.notify - A function that should handle JSON-RPC notifications.\n */\n constructor({ messenger, notify }: MultiChainControllerArgs) {\n super({\n messenger,\n metadata: {\n sessions: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: defaultState,\n });\n\n this.#notify = notify;\n }\n\n /**\n * Get an open session for the given origin.\n *\n * @param origin - The origin to get the session for.\n * @returns The session, if it exists, or `undefined` otherwise.\n */\n getSession(origin: string): SessionData | undefined {\n return this.state.sessions[origin];\n }\n\n /**\n * Close a session for the given origin.\n *\n * @param origin - The origin to close the session for.\n * @throws If the session does not exist.\n */\n async closeSession(origin: string): Promise<void> {\n const session = this.getSession(origin);\n assert(session, 'No session to close.');\n\n await this.#notify(origin, {\n method: 'multichainHack_metamask_disconnect',\n });\n\n this.update((state) => {\n delete state.sessions[origin];\n });\n\n await Promise.all(\n Object.values(session.handlingSnaps).map((snapId) =>\n this.messagingSystem.call(\n 'SnapController:decrementActiveReferences',\n snapId,\n ),\n ),\n );\n }\n\n /**\n * Handles a new connection from the given origin. This will create a new\n * session, and close any existing session for the origin.\n *\n * @param origin - The origin to create the session for.\n * @param connection - The connection arguments.\n * @param connection.requiredNamespaces - The namespaces that the origin\n * requires.\n * @returns The session that was created.\n */\n async onConnect(\n origin: string,\n connection: ConnectArguments,\n ): Promise<Session> {\n const existingSession = this.getSession(origin);\n if (existingSession) {\n await this.closeSession(origin);\n }\n\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n // Get available namespaces supported by currently installed Snaps.\n const availableNamespaces = fromEntries(\n await Promise.all(\n filteredSnaps.map(async (snap) => [\n snap.id,\n await this.snapToNamespaces(snap),\n ]),\n ),\n );\n\n // The magical matching algorithm specified in SIP-2.\n const namespaceToSnaps = findMatchingKeyringSnaps(\n connection.requiredNamespaces,\n availableNamespaces,\n );\n\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n );\n\n // Find namespaces that can be satisfied with existing approved Snaps.\n const approvedNamespacesAndSnaps = Object.entries(namespaceToSnaps).reduce<\n Record<NamespaceId, SnapId[]>\n >((acc, [namespace, snapIds]) => {\n const approvedSnaps = snapIds.filter((snapId) => {\n return (\n permissions && hasProperty(permissions, getSnapPermissionName(snapId))\n );\n });\n\n if (approvedSnaps.length > 0) {\n acc[namespace] = approvedSnaps;\n }\n return acc;\n }, {});\n\n // If we either don't have a snap to handle a namespace or we have multiple we have conflicts\n const hasConflicts = Object.keys(namespaceToSnaps).some(\n (namespace) =>\n !hasProperty(approvedNamespacesAndSnaps, namespace) ||\n approvedNamespacesAndSnaps[namespace]?.length > 1,\n );\n\n // Use already approved snaps if they satisfy the requested namespaces.\n const filteredNamespacesAndSnaps = hasConflicts\n ? namespaceToSnaps\n : approvedNamespacesAndSnaps;\n\n // Fetch possible accounts from snaps.\n const possibleAccounts = await this.namespacesToAccounts(\n origin,\n filteredNamespacesAndSnaps,\n connection.requiredNamespaces,\n );\n\n // For now we fail here if no namespaces could be matched to a snap.\n // We don't fail if at least one namespace is matched to a snap.\n // TODO: Decide whether this is what we want\n assert(\n Object.values(possibleAccounts).some(\n (possibleAccount) => possibleAccount.length > 0,\n ),\n 'No installed snaps found for any requested namespace.',\n );\n\n // If currently installed Snaps / configuration doesn't solve request, we\n // need to show a prompt. This is handled by `resolveConflicts`.\n const resolvedAccounts = hasConflicts\n ? await this.resolveConflicts(origin, possibleAccounts)\n : fromEntries(\n Object.entries(possibleAccounts).map(\n ([namespace, snapAndAccounts]) => [\n namespace,\n snapAndAccounts[0] ?? null,\n ],\n ),\n );\n\n // Aggregate information about session namespaces.\n const providedNamespaces = Object.entries(\n connection.requiredNamespaces,\n ).reduce<Record<NamespaceId, SessionNamespace>>(\n (acc, [namespaceId, namespace]) => {\n const accounts = resolvedAccounts[namespaceId]?.accounts;\n if (accounts) {\n acc[namespaceId] = {\n accounts,\n chains: namespace.chains,\n events: namespace.events,\n methods: namespace.methods,\n };\n }\n return acc;\n },\n {},\n );\n\n // Collect information about handler Snaps for each namespace.\n const handlingSnaps = Object.entries(resolvedAccounts).reduce<\n Record<NamespaceId, SnapId>\n >((acc, [namespaceId, accountsAndSnap]) => {\n if (accountsAndSnap) {\n acc[namespaceId] = accountsAndSnap.snapId;\n }\n return acc;\n }, {});\n\n const session: SessionData = {\n origin,\n requestedNamespaces: connection.requiredNamespaces,\n providedNamespaces,\n handlingSnaps,\n };\n\n // Makes sure used Snaps aren't killed while they are serving the session.\n await Promise.all(\n Object.values(session.handlingSnaps).map((snapId) =>\n this.messagingSystem.call(\n 'SnapController:incrementActiveReferences',\n snapId,\n ),\n ),\n );\n\n this.update((state) => {\n state.sessions[origin] = session;\n });\n\n return { namespaces: providedNamespaces };\n }\n\n /**\n * Handle an incoming multichain request from the given origin. This will\n * forward the request to the appropriate Snap, and return the response.\n *\n * @param origin - The origin to handle the request for.\n * @param data - The request data.\n * @param data.chainId - The chain ID for the request.\n * @param data.request - The request arguments, i.e., the method and params.\n * @returns The response from the Snap.\n * @throws If the session does not exist, or the session does not provide the\n * requested namespace.\n */\n async onRequest(\n origin: string,\n data: { chainId: ChainId; request: RequestArguments },\n ): Promise<unknown> {\n const session = this.getSession(origin);\n assert(session, `Session for \"${origin}\" doesn't exist.`);\n\n const { namespace } = parseChainId(data.chainId);\n const sessionNamespace = session.providedNamespaces[namespace];\n assert(\n session.providedNamespaces[namespace]?.chains.includes(data.chainId),\n `Session for \"${origin}\" is not connected to \"${data.chainId}\" chain.`,\n );\n\n const { method } = data.request;\n assert(\n sessionNamespace?.methods?.includes(method),\n `Session for \"${origin}\" does not support ${method}`,\n );\n\n const snapId = session.handlingSnaps[namespace];\n assert(snapId !== undefined);\n\n const permissionName = getSnapPermissionName(snapId);\n\n // Check if origin has permission to communicate with this Snap.\n const hasPermission = this.messagingSystem.call(\n 'PermissionController:hasPermission',\n origin,\n permissionName,\n );\n\n // TODO: Get permission for origin connecting to snap, or get user approval.\n // In the future this is where we should prompt for this permission.\n // In this iteration, we will grant this permission in `onConnect`.\n assert(\n hasPermission,\n `${origin} does not have permission to communicate with ${snapId}.`,\n );\n\n return this.snapRequest({\n snapId,\n origin,\n method: 'handleRequest',\n args: data,\n });\n }\n\n /**\n * Send a request to the given Snap. This calls the given method with the\n * given arguments on the keyring class in the given Snap.\n *\n * @param options - The request options.\n * @param options.snapId - The ID of the Snap to send the request to.\n * @param options.origin - The origin of the request.\n * @param options.method - The request method.\n * @param options.args - The request params.\n * @returns The response from the Snap.\n */\n private async snapRequest({\n snapId,\n origin,\n method,\n args,\n }: {\n snapId: SnapId;\n origin: string;\n method: keyof SnapKeyring;\n args?: unknown;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin,\n handler: HandlerType.SnapKeyring,\n request: { method, params: args ? [args] : [] },\n });\n }\n\n /**\n * Get the accounts exposed by the Snap's keyring.\n *\n * This also verifies that the accounts returned by the snap are valid CAIP-10\n * account IDs.\n *\n * @param origin - The origin of the request.\n * @param snapId - The ID of the Snap to get the accounts from.\n * @returns The accounts, or `null` if the Snap does not have any accounts, or\n * the accounts are invalid (i.e., not valid CAIP-10 account IDs).\n */\n private async getSnapAccounts(\n origin: string,\n snapId: SnapId,\n ): Promise<AccountId[] | null> {\n try {\n const result = await this.snapRequest({\n snapId,\n origin,\n method: 'getAccounts',\n });\n\n if (isAccountIdArray(result)) {\n return result;\n }\n } catch (error) {\n // Ignore errors for now\n console.error(error);\n }\n\n return null;\n }\n\n /**\n * Get the namespaces for the given Snap, as described in the Snap's manifest.\n *\n * @param snap - The Snap to get the namespaces for.\n * @returns The namespaces, or `null` if the Snap does not have any\n * namespaces.\n */\n private snapToNamespaces(snap: TruncatedSnap): Namespaces | null {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n\n const keyringPermission = permissions?.[SnapEndowments.Keyring];\n return getKeyringCaveatNamespaces(keyringPermission);\n }\n\n /**\n * Maps from an object of namespace IDs and Snap IDs, and an object of\n * namespace IDs and requested namespaces, to an object of namespace IDs and\n * resolved accounts, with the Snap ID providing the accounts.\n *\n * @param origin - The origin of the request.\n * @param namespacesAndSnaps - An object of namespace IDs and Snap IDs\n * providing the namespace.\n * @param requestedNamespaces - An object of namespace IDs and requested\n * namespaces.\n * @returns An object of namespace IDs and resolved accounts, with the Snap ID\n * providing the accounts.\n */\n private async namespacesToAccounts(\n origin: string,\n namespacesAndSnaps: Record<NamespaceId, SnapId[]>,\n requestedNamespaces: Record<NamespaceId, RequestNamespace>,\n ): Promise<Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] }[]>> {\n const dedupedSnaps = [\n ...new Set(flatten(Object.values(namespacesAndSnaps))),\n ] as SnapId[];\n\n const allAccounts = await dedupedSnaps.reduce<\n Promise<Record<string, AccountId[]>>\n >(async (previousPromise, snapId) => {\n const result = await this.getSnapAccounts(origin, snapId);\n const acc = await previousPromise;\n if (result) {\n acc[snapId] = result;\n }\n return acc;\n }, Promise.resolve({}));\n\n return Object.keys(namespacesAndSnaps).reduce<\n Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] }[]>\n >((acc, namespaceId) => {\n const { chains } = requestedNamespaces[namespaceId];\n\n const accountInAnyRequestedChain = (account: AccountId) => {\n const { chainId: parsedChainId } = parseAccountId(account);\n return chains.some((chainId) => chainId === parsedChainId);\n };\n\n const result = Object.entries(allAccounts)\n .map(([snapId, accounts]) => ({\n snapId,\n accounts: accounts.filter(accountInAnyRequestedChain),\n }))\n .filter(({ accounts }) => accounts.length > 0);\n\n acc[namespaceId] = result;\n\n return acc;\n }, {});\n }\n\n /**\n * If multiple Snap IDs are provided for a namespace, this method will\n * determine which Snap ID to use for the namespace, by showing the user a\n * prompt.\n *\n * @param origin - The origin of the request.\n * @param possibleAccounts - An object containing the accounts provided by\n * each Snap ID for each namespace.\n * @returns An object containing the Snap ID to use for each namespace.\n */\n private async resolveConflicts(\n origin: string,\n possibleAccounts: Record<\n NamespaceId,\n { snapId: SnapId; accounts: AccountId[] }[]\n >,\n ): Promise<\n Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] } | null>\n > {\n // Get user approval for connection.\n const id = nanoid();\n const resolvedAccounts = (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n origin,\n id,\n type: 'multichain_connect',\n requestData: {\n possibleAccounts,\n },\n },\n true,\n )) as Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] } | null>;\n\n // TODO: In the future, use another permission here to not give full\n // permission after handshake.\n // Instead we should give origin only a read-only access to list of accounts\n // without allowing provider.request() talking to a snap before additional\n // user approval. The additional approval would be requested in `onRequest`.\n const approvedPermissions = Object.values(resolvedAccounts).reduce<\n Record<string, Partial<PermissionConstraint>>\n >((acc, cur) => {\n if (cur !== null) {\n acc[getSnapPermissionName(cur.snapId)] = {};\n }\n return acc;\n }, {});\n\n this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions,\n subject: { origin },\n });\n\n return resolvedAccounts;\n }\n}\n"]}
1
+ {"version":3,"file":"MultiChainController.js","sourceRoot":"","sources":["../../src/multichain/MultiChainController.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QACb,CAAC,EAAE,EAAE,CAAC,CAAC;QAEP,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,uCAAuC,EAAE;YACjE,mBAAmB;YACnB,OAAO,EAAE,EAAE,MAAM,EAAE;SACpB,CAAC,CAAC;QAEH,OAAO,gBAAgB,CAAC;IAC1B,CAAC;CACF;AAtdD,oDAsdC","sourcesContent":["import { AddApprovalRequest } from '@metamask/approval-controller';\nimport {\n BaseControllerV2 as BaseController,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n GetPermissions,\n GrantPermissions,\n HasPermission,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport {\n SnapKeyring,\n parseAccountId,\n AccountId,\n parseChainId,\n ChainId,\n ConnectArguments,\n HandlerType,\n NamespaceId,\n RequestArguments,\n RequestNamespace,\n Session,\n TruncatedSnap,\n SnapId,\n fromEntries,\n SessionNamespace,\n flatten,\n getSnapPermissionName,\n isAccountIdArray,\n Namespaces,\n} from '@metamask/snaps-utils';\nimport { hasProperty, assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\nimport {\n GetAllSnaps,\n HandleSnapRequest,\n IncrementActiveReferences,\n DecrementActiveReferences,\n SnapEndowments,\n getRunnableSnaps,\n} from '../snaps';\nimport { getKeyringCaveatNamespaces } from '../snaps/endowments/keyring';\nimport { findMatchingKeyringSnaps } from './matching';\n\nconst controllerName = 'MultiChainController';\n\nconst defaultState: MultiChainControllerState = {\n sessions: {},\n};\n\ntype AllowedActions =\n | GetAllSnaps\n | IncrementActiveReferences\n | DecrementActiveReferences\n | HandleSnapRequest\n | GetPermissions\n | HasPermission\n | AddApprovalRequest\n | GrantPermissions;\n\ntype MultiChainControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n never,\n AllowedActions['type'],\n never\n>;\n\ntype SessionData = {\n origin: string;\n requestedNamespaces: Record<NamespaceId, RequestNamespace>;\n providedNamespaces: Record<NamespaceId, RequestNamespace>;\n handlingSnaps: Record<NamespaceId, SnapId>;\n};\n\ntype MultiChainControllerState = {\n sessions: { [origin: string]: SessionData };\n};\n\ntype Notify = (\n origin: string,\n data: { method: string; params?: Record<string, unknown> },\n) => Promise<void>;\n\ntype MultiChainControllerArgs = {\n notify: Notify;\n messenger: MultiChainControllerMessenger;\n};\n\n// TODO(ritave): Support for legacy ethereum operations, not just snaps\nexport class MultiChainController extends BaseController<\n typeof controllerName,\n MultiChainControllerState,\n MultiChainControllerMessenger\n> {\n readonly #notify: Notify;\n\n /**\n * Construct a new {@link MultiChainController} instance.\n *\n * @param args - The arguments to construct the controller with.\n * @param args.messenger - The controller messenger to use.\n * @param args.notify - A function that should handle JSON-RPC notifications.\n */\n constructor({ messenger, notify }: MultiChainControllerArgs) {\n super({\n messenger,\n metadata: {\n sessions: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: defaultState,\n });\n\n this.#notify = notify;\n }\n\n /**\n * Get an open session for the given origin.\n *\n * @param origin - The origin to get the session for.\n * @returns The session, if it exists, or `undefined` otherwise.\n */\n getSession(origin: string): SessionData | undefined {\n return this.state.sessions[origin];\n }\n\n /**\n * Close a session for the given origin.\n *\n * @param origin - The origin to close the session for.\n * @throws If the session does not exist.\n */\n async closeSession(origin: string): Promise<void> {\n const session = this.getSession(origin);\n assert(session, 'No session to close.');\n\n await this.#notify(origin, {\n method: 'multichainHack_metamask_disconnect',\n });\n\n this.update((state) => {\n delete state.sessions[origin];\n });\n\n await Promise.all(\n Object.values(session.handlingSnaps).map((snapId) =>\n this.messagingSystem.call(\n 'SnapController:decrementActiveReferences',\n snapId,\n ),\n ),\n );\n }\n\n /**\n * Handles a new connection from the given origin. This will create a new\n * session, and close any existing session for the origin.\n *\n * @param origin - The origin to create the session for.\n * @param connection - The connection arguments.\n * @param connection.requiredNamespaces - The namespaces that the origin\n * requires.\n * @returns The session that was created.\n */\n async onConnect(\n origin: string,\n connection: ConnectArguments,\n ): Promise<Session> {\n const existingSession = this.getSession(origin);\n if (existingSession) {\n await this.closeSession(origin);\n }\n\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n // Get available namespaces supported by currently installed Snaps.\n const availableNamespaces = fromEntries(\n await Promise.all(\n filteredSnaps.map(async (snap) => [\n snap.id,\n await this.snapToNamespaces(snap),\n ]),\n ),\n );\n\n // The magical matching algorithm specified in SIP-2.\n const namespaceToSnaps = findMatchingKeyringSnaps(\n connection.requiredNamespaces,\n availableNamespaces,\n );\n\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n );\n\n // Find namespaces that can be satisfied with existing approved Snaps.\n const approvedNamespacesAndSnaps = Object.entries(namespaceToSnaps).reduce<\n Record<NamespaceId, SnapId[]>\n >((acc, [namespace, snapIds]) => {\n const approvedSnaps = snapIds.filter((snapId) => {\n return (\n permissions && hasProperty(permissions, getSnapPermissionName(snapId))\n );\n });\n\n if (approvedSnaps.length > 0) {\n acc[namespace] = approvedSnaps;\n }\n return acc;\n }, {});\n\n // If we either don't have a snap to handle a namespace or we have multiple we have conflicts\n const hasConflicts = Object.keys(namespaceToSnaps).some(\n (namespace) =>\n !hasProperty(approvedNamespacesAndSnaps, namespace) ||\n approvedNamespacesAndSnaps[namespace]?.length > 1,\n );\n\n // Use already approved snaps if they satisfy the requested namespaces.\n const filteredNamespacesAndSnaps = hasConflicts\n ? namespaceToSnaps\n : approvedNamespacesAndSnaps;\n\n // Fetch possible accounts from snaps.\n const possibleAccounts = await this.namespacesToAccounts(\n origin,\n filteredNamespacesAndSnaps,\n connection.requiredNamespaces,\n );\n\n // For now we fail here if no namespaces could be matched to a snap.\n // We don't fail if at least one namespace is matched to a snap.\n // TODO: Decide whether this is what we want\n assert(\n Object.values(possibleAccounts).some(\n (possibleAccount) => possibleAccount.length > 0,\n ),\n 'No installed snaps found for any requested namespace.',\n );\n\n // If currently installed Snaps / configuration doesn't solve request, we\n // need to show a prompt. This is handled by `resolveConflicts`.\n const resolvedAccounts = hasConflicts\n ? await this.resolveConflicts(origin, possibleAccounts)\n : fromEntries(\n Object.entries(possibleAccounts).map(\n ([namespace, snapAndAccounts]) => [\n namespace,\n snapAndAccounts[0] ?? null,\n ],\n ),\n );\n\n // Aggregate information about session namespaces.\n const providedNamespaces = Object.entries(\n connection.requiredNamespaces,\n ).reduce<Record<NamespaceId, SessionNamespace>>(\n (acc, [namespaceId, namespace]) => {\n const accounts = resolvedAccounts[namespaceId]?.accounts;\n if (accounts) {\n acc[namespaceId] = {\n accounts,\n chains: namespace.chains,\n events: namespace.events,\n methods: namespace.methods,\n };\n }\n return acc;\n },\n {},\n );\n\n // Collect information about handler Snaps for each namespace.\n const handlingSnaps = Object.entries(resolvedAccounts).reduce<\n Record<NamespaceId, SnapId>\n >((acc, [namespaceId, accountsAndSnap]) => {\n if (accountsAndSnap) {\n acc[namespaceId] = accountsAndSnap.snapId;\n }\n return acc;\n }, {});\n\n const session: SessionData = {\n origin,\n requestedNamespaces: connection.requiredNamespaces,\n providedNamespaces,\n handlingSnaps,\n };\n\n // Makes sure used Snaps aren't killed while they are serving the session.\n await Promise.all(\n Object.values(session.handlingSnaps).map((snapId) =>\n this.messagingSystem.call(\n 'SnapController:incrementActiveReferences',\n snapId,\n ),\n ),\n );\n\n this.update((state) => {\n state.sessions[origin] = session;\n });\n\n return { namespaces: providedNamespaces };\n }\n\n /**\n * Handle an incoming multichain request from the given origin. This will\n * forward the request to the appropriate Snap, and return the response.\n *\n * @param origin - The origin to handle the request for.\n * @param data - The request data.\n * @param data.chainId - The chain ID for the request.\n * @param data.request - The request arguments, i.e., the method and params.\n * @returns The response from the Snap.\n * @throws If the session does not exist, or the session does not provide the\n * requested namespace.\n */\n async onRequest(\n origin: string,\n data: { chainId: ChainId; request: RequestArguments },\n ): Promise<unknown> {\n const session = this.getSession(origin);\n assert(session, `Session for \"${origin}\" doesn't exist.`);\n\n const { namespace } = parseChainId(data.chainId);\n const sessionNamespace = session.providedNamespaces[namespace];\n assert(\n session.providedNamespaces[namespace]?.chains.includes(data.chainId),\n `Session for \"${origin}\" is not connected to \"${data.chainId}\" chain.`,\n );\n\n const { method } = data.request;\n assert(\n sessionNamespace?.methods?.includes(method),\n `Session for \"${origin}\" does not support ${method}`,\n );\n\n const snapId = session.handlingSnaps[namespace];\n assert(snapId !== undefined);\n\n const permissionName = getSnapPermissionName(snapId);\n\n // Check if origin has permission to communicate with this Snap.\n const hasPermission = this.messagingSystem.call(\n 'PermissionController:hasPermission',\n origin,\n permissionName,\n );\n\n // TODO: Get permission for origin connecting to snap, or get user approval.\n // In the future this is where we should prompt for this permission.\n // In this iteration, we will grant this permission in `onConnect`.\n assert(\n hasPermission,\n `${origin} does not have permission to communicate with ${snapId}.`,\n );\n\n return this.snapRequest({\n snapId,\n origin,\n method: 'handleRequest',\n args: data,\n });\n }\n\n /**\n * Send a request to the given Snap. This calls the given method with the\n * given arguments on the keyring class in the given Snap.\n *\n * @param options - The request options.\n * @param options.snapId - The ID of the Snap to send the request to.\n * @param options.origin - The origin of the request.\n * @param options.method - The request method.\n * @param options.args - The request params.\n * @returns The response from the Snap.\n */\n private async snapRequest({\n snapId,\n origin,\n method,\n args,\n }: {\n snapId: SnapId;\n origin: string;\n method: keyof SnapKeyring;\n args?: unknown;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin,\n handler: HandlerType.SnapKeyring,\n request: { method, params: args ? [args] : [] },\n });\n }\n\n /**\n * Get the accounts exposed by the Snap's keyring.\n *\n * This also verifies that the accounts returned by the snap are valid CAIP-10\n * account IDs.\n *\n * @param origin - The origin of the request.\n * @param snapId - The ID of the Snap to get the accounts from.\n * @returns The accounts, or `null` if the Snap does not have any accounts, or\n * the accounts are invalid (i.e., not valid CAIP-10 account IDs).\n */\n private async getSnapAccounts(\n origin: string,\n snapId: SnapId,\n ): Promise<AccountId[] | null> {\n try {\n const result = await this.snapRequest({\n snapId,\n origin,\n method: 'getAccounts',\n });\n\n if (isAccountIdArray(result)) {\n return result;\n }\n } catch (error) {\n // Ignore errors for now\n console.error(error);\n }\n\n return null;\n }\n\n /**\n * Get the namespaces for the given Snap, as described in the Snap's manifest.\n *\n * @param snap - The Snap to get the namespaces for.\n * @returns The namespaces, or `null` if the Snap does not have any\n * namespaces.\n */\n private snapToNamespaces(snap: TruncatedSnap): Namespaces | null {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n\n const keyringPermission = permissions?.[SnapEndowments.Keyring];\n return getKeyringCaveatNamespaces(keyringPermission);\n }\n\n /**\n * Maps from an object of namespace IDs and Snap IDs, and an object of\n * namespace IDs and requested namespaces, to an object of namespace IDs and\n * resolved accounts, with the Snap ID providing the accounts.\n *\n * @param origin - The origin of the request.\n * @param namespacesAndSnaps - An object of namespace IDs and Snap IDs\n * providing the namespace.\n * @param requestedNamespaces - An object of namespace IDs and requested\n * namespaces.\n * @returns An object of namespace IDs and resolved accounts, with the Snap ID\n * providing the accounts.\n */\n private async namespacesToAccounts(\n origin: string,\n namespacesAndSnaps: Record<NamespaceId, SnapId[]>,\n requestedNamespaces: Record<NamespaceId, RequestNamespace>,\n ): Promise<Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] }[]>> {\n const dedupedSnaps = [\n ...new Set(flatten(Object.values(namespacesAndSnaps))),\n ] as SnapId[];\n\n const allAccounts = await dedupedSnaps.reduce<\n Promise<Record<string, AccountId[]>>\n >(async (previousPromise, snapId) => {\n const result = await this.getSnapAccounts(origin, snapId);\n const acc = await previousPromise;\n if (result) {\n acc[snapId] = result;\n }\n return acc;\n }, Promise.resolve({}));\n\n return Object.keys(namespacesAndSnaps).reduce<\n Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] }[]>\n >((acc, namespaceId) => {\n const { chains } = requestedNamespaces[namespaceId];\n\n const accountInAnyRequestedChain = (account: AccountId) => {\n const { chainId: parsedChainId } = parseAccountId(account);\n return chains.some((chainId) => chainId === parsedChainId);\n };\n\n const result = Object.entries(allAccounts)\n .map(([snapId, accounts]) => ({\n snapId,\n accounts: accounts.filter(accountInAnyRequestedChain),\n }))\n .filter(({ accounts }) => accounts.length > 0);\n\n acc[namespaceId] = result;\n\n return acc;\n }, {});\n }\n\n /**\n * If multiple Snap IDs are provided for a namespace, this method will\n * determine which Snap ID to use for the namespace, by showing the user a\n * prompt.\n *\n * @param origin - The origin of the request.\n * @param possibleAccounts - An object containing the accounts provided by\n * each Snap ID for each namespace.\n * @returns An object containing the Snap ID to use for each namespace.\n */\n private async resolveConflicts(\n origin: string,\n possibleAccounts: Record<\n NamespaceId,\n { snapId: SnapId; accounts: AccountId[] }[]\n >,\n ): Promise<\n Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] } | null>\n > {\n // Get user approval for connection.\n const id = nanoid();\n const resolvedAccounts = (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n origin,\n id,\n type: 'multichain_connect',\n requestData: {\n possibleAccounts,\n },\n },\n true,\n )) as Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] } | null>;\n\n // TODO: In the future, use another permission here to not give full\n // permission after handshake.\n // Instead we should give origin only a read-only access to list of accounts\n // without allowing provider.request() talking to a snap before additional\n // user approval. The additional approval would be requested in `onRequest`.\n const approvedPermissions = Object.values(resolvedAccounts).reduce<\n Record<string, Partial<PermissionConstraint>>\n >((acc, cur) => {\n if (cur !== null) {\n acc[getSnapPermissionName(cur.snapId)] = {};\n }\n return acc;\n }, {});\n\n this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions,\n subject: { origin },\n });\n\n return resolvedAccounts;\n }\n}\n"]}
@@ -235,10 +235,6 @@ export declare type SnapControllerEvents = SnapAdded | SnapBlocked | SnapInstall
235
235
  export declare type AllowedActions = GetEndowments | GetPermissions | GetSubjectMetadata | HasPermission | HasPermissions | RevokePermissions | RevokeAllPermissions | RevokePermissionForAllSubjects | GrantPermissions | AddApprovalRequest | HandleRpcRequestAction | ExecuteSnapAction | TerminateAllSnapsAction | TerminateSnapAction;
236
236
  export declare type AllowedEvents = ExecutionServiceEvents;
237
237
  declare type SnapControllerMessenger = RestrictedControllerMessenger<typeof controllerName, SnapControllerActions | AllowedActions, SnapControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
238
- export declare enum AppKeyType {
239
- StateEncryption = "stateEncryption"
240
- }
241
- declare type GetAppKey = (subject: string, appKeyType: AppKeyType) => Promise<string>;
242
238
  declare type FeatureFlags = {
243
239
  /**
244
240
  * We still need to implement new UI approval page in metamask-extension before we can allow
@@ -287,10 +283,6 @@ declare type SnapControllerArgs = {
287
283
  * See {@link FeatureFlags}.
288
284
  */
289
285
  featureFlags: FeatureFlags;
290
- /**
291
- * A function to get an "app key" for a specific subject.
292
- */
293
- getAppKey: GetAppKey;
294
286
  /**
295
287
  * How frequently to check whether a snap is idle.
296
288
  */
@@ -331,7 +323,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
331
323
  #private;
332
324
  private readonly maxRequestTime;
333
325
  private readonly snapsRuntimeData;
334
- constructor({ closeAllConnections, messenger, state, getAppKey, environmentEndowmentPermissions, idleTimeCheckInterval, checkBlockList, maxIdleTime, maxRequestTime, fetchFunction, featureFlags, detectSnapLocation: detectSnapLocationFunction, }: SnapControllerArgs);
326
+ constructor({ closeAllConnections, messenger, state, environmentEndowmentPermissions, idleTimeCheckInterval, checkBlockList, maxIdleTime, maxRequestTime, fetchFunction, featureFlags, detectSnapLocation: detectSnapLocationFunction, }: SnapControllerArgs);
335
327
  /**
336
328
  * Checks all installed snaps against the block list and
337
329
  * blocks/unblocks snaps as appropriate. See {@link SnapController.blockSnap}
@@ -437,7 +429,7 @@ export declare class SnapController extends BaseController<string, SnapControlle
437
429
  * @param snapId - The id of the Snap whose state should be updated.
438
430
  * @param newSnapState - The new state of the snap.
439
431
  */
440
- updateSnapState(snapId: SnapId, newSnapState: Json): Promise<void>;
432
+ updateSnapState(snapId: SnapId, newSnapState: string): Promise<void>;
441
433
  /**
442
434
  * Clears the state of the snap with the given id.
443
435
  * This is distinct from the state MetaMask uses to manage snaps.
@@ -21,11 +21,10 @@ var __rest = (this && this.__rest) || function (s, e) {
21
21
  }
22
22
  return t;
23
23
  };
24
- var _SnapController_instances, _SnapController_closeAllConnections, _SnapController_environmentEndowmentPermissions, _SnapController_featureFlags, _SnapController_fetchFunction, _SnapController_idleTimeCheckInterval, _SnapController_checkSnapBlockList, _SnapController_maxIdleTime, _SnapController_detectSnapLocation, _SnapController_rollbackSnapshots, _SnapController_getAppKey, _SnapController_timeoutForLastRequestStatus, _SnapController_statusMachine, _SnapController_initializeStateMachine, _SnapController_registerMessageHandlers, _SnapController_pollForLastRequestStatus, _SnapController_blockSnap, _SnapController_unblockSnap, _SnapController_assertIsUnblocked, _SnapController_stopSnapsLastRequestPastMax, _SnapController_transition, _SnapController_terminateSnap, _SnapController_getEncryptionKey, _SnapController_encryptSnapState, _SnapController_decryptSnapState, _SnapController_add, _SnapController_startSnap, _SnapController_getEndowments, _SnapController_set, _SnapController_fetchSnap, _SnapController_processSnapPermissions, _SnapController_getRpcRequestHandler, _SnapController_executeWithTimeout, _SnapController_recordSnapRpcRequestStart, _SnapController_recordSnapRpcRequestFinish, _SnapController_getRollbackSnapshot, _SnapController_createRollbackSnapshot, _SnapController_rollbackSnap, _SnapController_rollbackSnaps, _SnapController_getRuntime, _SnapController_getRuntimeExpect, _SnapController_setupRuntime, _SnapController_calculatePermissionsChange, _SnapController_isValidUpdate;
24
+ var _SnapController_instances, _SnapController_closeAllConnections, _SnapController_environmentEndowmentPermissions, _SnapController_featureFlags, _SnapController_fetchFunction, _SnapController_idleTimeCheckInterval, _SnapController_checkSnapBlockList, _SnapController_maxIdleTime, _SnapController_detectSnapLocation, _SnapController_rollbackSnapshots, _SnapController_timeoutForLastRequestStatus, _SnapController_statusMachine, _SnapController_initializeStateMachine, _SnapController_registerMessageHandlers, _SnapController_pollForLastRequestStatus, _SnapController_blockSnap, _SnapController_unblockSnap, _SnapController_assertIsUnblocked, _SnapController_stopSnapsLastRequestPastMax, _SnapController_transition, _SnapController_terminateSnap, _SnapController_add, _SnapController_startSnap, _SnapController_getEndowments, _SnapController_set, _SnapController_fetchSnap, _SnapController_processSnapPermissions, _SnapController_getRpcRequestHandler, _SnapController_executeWithTimeout, _SnapController_recordSnapRpcRequestStart, _SnapController_recordSnapRpcRequestFinish, _SnapController_getRollbackSnapshot, _SnapController_createRollbackSnapshot, _SnapController_rollbackSnap, _SnapController_rollbackSnaps, _SnapController_getRuntime, _SnapController_getRuntimeExpect, _SnapController_setupRuntime, _SnapController_calculatePermissionsChange, _SnapController_isValidUpdate;
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.SnapController = exports.AppKeyType = exports.SNAP_APPROVAL_UPDATE = exports.SNAP_APPROVAL_INSTALL = exports.controllerName = void 0;
26
+ exports.SnapController = exports.SNAP_APPROVAL_UPDATE = exports.SNAP_APPROVAL_INSTALL = exports.controllerName = void 0;
27
27
  const base_controller_1 = require("@metamask/base-controller");
28
- const browser_passworder_1 = require("@metamask/browser-passworder");
29
28
  const rpc_methods_1 = require("@metamask/rpc-methods");
30
29
  const snaps_utils_1 = require("@metamask/snaps-utils");
31
30
  const subject_metadata_controller_1 = require("@metamask/subject-metadata-controller");
@@ -52,10 +51,6 @@ const TRUNCATED_SNAP_PROPERTIES = new Set([
52
51
  'enabled',
53
52
  'blocked',
54
53
  ]);
55
- var AppKeyType;
56
- (function (AppKeyType) {
57
- AppKeyType["StateEncryption"] = "stateEncryption";
58
- })(AppKeyType = exports.AppKeyType || (exports.AppKeyType = {}));
59
54
  const defaultState = {
60
55
  snapErrors: {},
61
56
  snaps: {},
@@ -85,7 +80,7 @@ const name = 'SnapController';
85
80
  * - Start: Initializes the snap in its SES realm with the authorized permissions.
86
81
  */
87
82
  class SnapController extends base_controller_1.BaseControllerV2 {
88
- constructor({ closeAllConnections, messenger, state, getAppKey, environmentEndowmentPermissions = [], idleTimeCheckInterval = (0, utils_1.inMilliseconds)(5, utils_1.Duration.Second), checkBlockList, maxIdleTime = (0, utils_1.inMilliseconds)(30, utils_1.Duration.Second), maxRequestTime = (0, utils_1.inMilliseconds)(60, utils_1.Duration.Second), fetchFunction = globalThis.fetch.bind(globalThis), featureFlags = {}, detectSnapLocation: detectSnapLocationFunction = location_1.detectSnapLocation, }) {
83
+ constructor({ closeAllConnections, messenger, state, environmentEndowmentPermissions = [], idleTimeCheckInterval = (0, utils_1.inMilliseconds)(5, utils_1.Duration.Second), checkBlockList, maxIdleTime = (0, utils_1.inMilliseconds)(30, utils_1.Duration.Second), maxRequestTime = (0, utils_1.inMilliseconds)(60, utils_1.Duration.Second), fetchFunction = globalThis.fetch.bind(globalThis), featureFlags = {}, detectSnapLocation: detectSnapLocationFunction = location_1.detectSnapLocation, }) {
89
84
  var _a, _b;
90
85
  super({
91
86
  messenger,
@@ -137,14 +132,12 @@ class SnapController extends base_controller_1.BaseControllerV2 {
137
132
  _SnapController_maxIdleTime.set(this, void 0);
138
133
  _SnapController_detectSnapLocation.set(this, void 0);
139
134
  _SnapController_rollbackSnapshots.set(this, void 0);
140
- _SnapController_getAppKey.set(this, void 0);
141
135
  _SnapController_timeoutForLastRequestStatus.set(this, void 0);
142
136
  _SnapController_statusMachine.set(this, void 0);
143
137
  __classPrivateFieldSet(this, _SnapController_closeAllConnections, closeAllConnections, "f");
144
138
  __classPrivateFieldSet(this, _SnapController_environmentEndowmentPermissions, environmentEndowmentPermissions, "f");
145
139
  __classPrivateFieldSet(this, _SnapController_featureFlags, featureFlags, "f");
146
140
  __classPrivateFieldSet(this, _SnapController_fetchFunction, fetchFunction, "f");
147
- __classPrivateFieldSet(this, _SnapController_getAppKey, getAppKey, "f");
148
141
  __classPrivateFieldSet(this, _SnapController_idleTimeCheckInterval, idleTimeCheckInterval, "f");
149
142
  __classPrivateFieldSet(this, _SnapController_checkSnapBlockList, checkBlockList, "f");
150
143
  __classPrivateFieldSet(this, _SnapController_maxIdleTime, maxIdleTime, "f");
@@ -385,9 +378,8 @@ class SnapController extends base_controller_1.BaseControllerV2 {
385
378
  * @param newSnapState - The new state of the snap.
386
379
  */
387
380
  async updateSnapState(snapId, newSnapState) {
388
- const encrypted = await __classPrivateFieldGet(this, _SnapController_instances, "m", _SnapController_encryptSnapState).call(this, snapId, newSnapState);
389
381
  const runtime = __classPrivateFieldGet(this, _SnapController_instances, "m", _SnapController_getRuntimeExpect).call(this, snapId);
390
- runtime.state = encrypted;
382
+ runtime.state = newSnapState;
391
383
  }
392
384
  /**
393
385
  * Clears the state of the snap with the given id.
@@ -438,7 +430,7 @@ class SnapController extends base_controller_1.BaseControllerV2 {
438
430
  */
439
431
  async getSnapState(snapId) {
440
432
  const { state } = __classPrivateFieldGet(this, _SnapController_instances, "m", _SnapController_getRuntimeExpect).call(this, snapId);
441
- return state ? __classPrivateFieldGet(this, _SnapController_instances, "m", _SnapController_decryptSnapState).call(this, snapId, state) : null;
433
+ return state !== null && state !== void 0 ? state : null;
442
434
  }
443
435
  /**
444
436
  * Completely clear the controller's state: delete all associated data,
@@ -844,7 +836,7 @@ class SnapController extends base_controller_1.BaseControllerV2 {
844
836
  }
845
837
  }
846
838
  exports.SnapController = SnapController;
847
- _SnapController_closeAllConnections = new WeakMap(), _SnapController_environmentEndowmentPermissions = new WeakMap(), _SnapController_featureFlags = new WeakMap(), _SnapController_fetchFunction = new WeakMap(), _SnapController_idleTimeCheckInterval = new WeakMap(), _SnapController_checkSnapBlockList = new WeakMap(), _SnapController_maxIdleTime = new WeakMap(), _SnapController_detectSnapLocation = new WeakMap(), _SnapController_rollbackSnapshots = new WeakMap(), _SnapController_getAppKey = new WeakMap(), _SnapController_timeoutForLastRequestStatus = new WeakMap(), _SnapController_statusMachine = new WeakMap(), _SnapController_instances = new WeakSet(), _SnapController_initializeStateMachine = function _SnapController_initializeStateMachine() {
839
+ _SnapController_closeAllConnections = new WeakMap(), _SnapController_environmentEndowmentPermissions = new WeakMap(), _SnapController_featureFlags = new WeakMap(), _SnapController_fetchFunction = new WeakMap(), _SnapController_idleTimeCheckInterval = new WeakMap(), _SnapController_checkSnapBlockList = new WeakMap(), _SnapController_maxIdleTime = new WeakMap(), _SnapController_detectSnapLocation = new WeakMap(), _SnapController_rollbackSnapshots = new WeakMap(), _SnapController_timeoutForLastRequestStatus = new WeakMap(), _SnapController_statusMachine = new WeakMap(), _SnapController_instances = new WeakSet(), _SnapController_initializeStateMachine = function _SnapController_initializeStateMachine() {
848
840
  const disableGuard = ({ snapId }) => {
849
841
  return this.getExpect(snapId).enabled;
850
842
  };
@@ -988,21 +980,6 @@ async function _SnapController_assertIsUnblocked(snapId, snapInfo) {
988
980
  async function _SnapController_terminateSnap(snapId) {
989
981
  await this.messagingSystem.call('ExecutionService:terminateSnap', snapId);
990
982
  this.messagingSystem.publish('SnapController:snapTerminated', this.getTruncatedExpect(snapId));
991
- }, _SnapController_getEncryptionKey = async function _SnapController_getEncryptionKey(snapId) {
992
- return __classPrivateFieldGet(this, _SnapController_getAppKey, "f").call(this, snapId, AppKeyType.StateEncryption);
993
- }, _SnapController_encryptSnapState = async function _SnapController_encryptSnapState(snapId, state) {
994
- const appKey = await __classPrivateFieldGet(this, _SnapController_instances, "m", _SnapController_getEncryptionKey).call(this, snapId);
995
- return (0, browser_passworder_1.encrypt)(appKey, state);
996
- }, _SnapController_decryptSnapState = async function _SnapController_decryptSnapState(snapId, encrypted) {
997
- const appKey = await __classPrivateFieldGet(this, _SnapController_instances, "m", _SnapController_getEncryptionKey).call(this, snapId);
998
- try {
999
- const value = await (0, browser_passworder_1.decrypt)(appKey, encrypted);
1000
- (0, utils_1.assert)((0, utils_1.isValidJson)(value));
1001
- return value;
1002
- }
1003
- catch (error) {
1004
- throw new Error('Failed to decrypt snap state, the state must be corrupted.');
1005
- }
1006
983
  }, _SnapController_add =
1007
984
  /**
1008
985
  * Returns a promise representing the complete installation of the requested snap.
@@ -1 +1 @@
1
- {"version":3,"file":"SnapController.js","sourceRoot":"","sources":["../../src/snaps/SnapController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,+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D,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAE5C,IAAI,IAAA,mCAAqB,EAAC,YAAY,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE;QAChE,OAAO,KAAK,CAAC;KACd;IAED,IAAI,IAAA,qBAAO,EAAC,YAAY,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE;QAClD,OAAO,KAAK,CAAC;KACd;IAED,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { AddApprovalRequest } from '@metamask/approval-controller';\nimport {\n BaseControllerV2 as BaseController,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { encrypt, decrypt } from '@metamask/browser-passworder';\nimport {\n Caveat,\n GetEndowments,\n GetPermissions,\n GrantPermissions,\n HasPermission,\n HasPermissions,\n PermissionConstraint,\n PermissionsRequest,\n RequestedPermissions,\n RevokeAllPermissions,\n RevokePermissionForAllSubjects,\n RevokePermissions,\n SubjectPermissions,\n ValidPermission,\n} from '@metamask/permission-controller';\nimport { caveatMappers } from '@metamask/rpc-methods';\nimport {\n assertIsSnapManifest,\n BlockedSnapInfo,\n DEFAULT_ENDOWMENTS,\n DEFAULT_REQUESTED_SNAP_VERSION,\n fromEntries,\n getSnapPermissionName,\n gtVersion,\n gtRange,\n InstallSnapsResult,\n isValidSemVerRange,\n PersistedSnap,\n ProcessSnapResult,\n RequestedSnapPermissions,\n resolveVersionRange,\n satisfiesVersionRange,\n SemVerRange,\n Snap,\n SnapId,\n SnapManifest,\n SnapPermissions,\n SnapRpcHook,\n SnapRpcHookArgs,\n SnapStatus,\n SnapStatusEvents,\n SNAP_PREFIX,\n SNAP_PREFIX_REGEX,\n StatusContext,\n StatusEvents,\n StatusStates,\n TruncatedSnap,\n TruncatedSnapFields,\n ValidatedSnapId,\n validateSnapId,\n validateSnapShasum,\n VirtualFile,\n} from '@metamask/snaps-utils';\nimport {\n GetSubjectMetadata,\n SubjectType,\n} from '@metamask/subject-metadata-controller';\nimport {\n assert,\n Duration,\n hasProperty,\n inMilliseconds,\n isNonEmptyArray,\n isValidJson,\n Json,\n NonEmptyArray,\n timeSince,\n} from '@metamask/utils';\nimport { createMachine, interpret, StateMachine } from '@xstate/fsm';\nimport { ethErrors } from 'eth-rpc-errors';\nimport type { Patch } from 'immer';\nimport { nanoid } from 'nanoid';\n\nimport { forceStrict, validateMachine } from '../fsm';\nimport {\n ExecuteSnapAction,\n ExecutionServiceEvents,\n HandleRpcRequestAction,\n SnapErrorJson,\n TerminateAllSnapsAction,\n TerminateSnapAction,\n} from '../services';\nimport { hasTimedOut, setDiff, withTimeout } from '../utils';\nimport {\n endowmentCaveatMappers,\n handlerEndowments,\n SnapEndowments,\n} from './endowments';\nimport { getRpcCaveatOrigins } from './endowments/rpc';\nimport { detectSnapLocation, SnapLocation } from './location';\nimport { RequestQueue } from './RequestQueue';\nimport { Timer } from './Timer';\n\nexport const controllerName = 'SnapController';\n\n// TODO: Figure out how to name these\nexport const SNAP_APPROVAL_INSTALL = 'wallet_installSnap';\nexport const SNAP_APPROVAL_UPDATE = 'wallet_updateSnap';\n\nconst TRUNCATED_SNAP_PROPERTIES = new Set<TruncatedSnapFields>([\n 'initialPermissions',\n 'id',\n 'permissionName',\n 'version',\n 'enabled',\n 'blocked',\n]);\n\nexport type PendingRequest = {\n requestId: unknown;\n timer: Timer;\n};\n\n/**\n * A wrapper type for any data stored during runtime of Snaps.\n * It is not persisted in state as it contains non-serializable data and is only relevant for the\n * current session.\n */\nexport interface SnapRuntimeData {\n /**\n * A promise that resolves when the Snap has finished installing\n */\n installPromise: null | Promise<PersistedSnap>;\n\n /**\n * A Unix timestamp for the last time the Snap received an RPC request\n */\n lastRequest: null | number;\n\n /**\n * The current number of active references where this Snap is being used\n */\n activeReferences: number;\n\n /**\n * The current pending inbound requests, meaning requests that are processed by snaps.\n */\n pendingInboundRequests: PendingRequest[];\n\n /**\n * The current pending outbound requests, meaning requests made from snaps towards the MetaMask\n * extension.\n */\n pendingOutboundRequests: number;\n\n /**\n * RPC handler designated for the Snap\n */\n rpcHandler: null | SnapRpcHook;\n\n /**\n * The finite state machine interpreter for possible states that the Snap can be in such as\n * stopped, running, blocked\n *\n * @see {@link SnapController:constructor}\n */\n interpreter: StateMachine.Service<StatusContext, StatusEvents, StatusStates>;\n\n /**\n * The snap source code\n */\n sourceCode: null | string;\n\n /**\n * The snap state (encrypted)\n */\n state: null | string;\n}\n\nexport type SnapError = {\n message: string;\n code: number;\n data?: Json;\n};\n\n/**\n * The return type of {@link SnapController.#fetchSnap} and its sibling methods.\n */\ntype FetchSnapResult = {\n /**\n * The manifest of the fetched Snap.\n */\n manifest: VirtualFile<SnapManifest>;\n\n /**\n * Auxillary files references in manifest.\n */\n files: VirtualFile[];\n\n /**\n * Location that was used to fetch the snap.\n *\n * Helpful if you want to pass it forward since files will be still cached.\n */\n location: SnapLocation;\n};\n\n// Types that probably should be defined elsewhere in prod\ntype CloseAllConnectionsFunction = (origin: string) => void;\ntype StoredSnaps = Record<SnapId, Snap>;\n\nexport type SnapControllerState = {\n snaps: StoredSnaps;\n // This type needs to be defined but is always empty in practice.\n // eslint-disable-next-line @typescript-eslint/ban-types\n snapStates: {};\n snapErrors: {\n [internalID: string]: SnapError & { internalID: string };\n };\n};\n\nexport type PersistedSnapControllerState = SnapControllerState & {\n snaps: Record<SnapId, PersistedSnap>;\n snapStates: Record<SnapId, string>;\n};\n\ntype RollbackSnapshot = {\n statePatches: Patch[];\n sourceCode: string | null;\n permissions: {\n revoked: unknown;\n granted: unknown[];\n requestData: unknown;\n };\n newVersion: string;\n};\n\n// Controller Messenger Actions\n\n/**\n * Gets the specified Snap from state.\n */\nexport type GetSnap = {\n type: `${typeof controllerName}:get`;\n handler: SnapController['get'];\n};\n\n/**\n * Handles sending an inbound request to a snap and returns its result.\n */\nexport type HandleSnapRequest = {\n type: `${typeof controllerName}:handleRequest`;\n handler: SnapController['handleRequest'];\n};\n\n/**\n * Gets the specified Snap's persisted state.\n */\nexport type GetSnapState = {\n type: `${typeof controllerName}:getSnapState`;\n handler: SnapController['getSnapState'];\n};\n\n/**\n * Checks if the specified snap exists in state.\n */\nexport type HasSnap = {\n type: `${typeof controllerName}:has`;\n handler: SnapController['has'];\n};\n\n/**\n * Updates the specified Snap's persisted state.\n */\nexport type UpdateSnapState = {\n type: `${typeof controllerName}:updateSnapState`;\n handler: SnapController['updateSnapState'];\n};\n\n/**\n * Clears the specified Snap's persisted state.\n */\nexport type ClearSnapState = {\n type: `${typeof controllerName}:clearSnapState`;\n handler: SnapController['clearSnapState'];\n};\n\n/**\n * Checks all installed snaps against the blocklist.\n */\nexport type UpdateBlockedSnaps = {\n type: `${typeof controllerName}:updateBlockedSnaps`;\n handler: SnapController['updateBlockedSnaps'];\n};\n\nexport type EnableSnap = {\n type: `${typeof controllerName}:enable`;\n handler: SnapController['enableSnap'];\n};\n\nexport type DisableSnap = {\n type: `${typeof controllerName}:disable`;\n handler: SnapController['disableSnap'];\n};\n\nexport type RemoveSnap = {\n type: `${typeof controllerName}:remove`;\n handler: SnapController['removeSnap'];\n};\n\nexport type GetPermittedSnaps = {\n type: `${typeof controllerName}:getPermitted`;\n handler: SnapController['getPermittedSnaps'];\n};\n\nexport type GetAllSnaps = {\n type: `${typeof controllerName}:getAll`;\n handler: SnapController['getAllSnaps'];\n};\n\nexport type IncrementActiveReferences = {\n type: `${typeof controllerName}:incrementActiveReferences`;\n handler: SnapController['incrementActiveReferences'];\n};\n\nexport type DecrementActiveReferences = {\n type: `${typeof controllerName}:decrementActiveReferences`;\n handler: SnapController['decrementActiveReferences'];\n};\n\nexport type InstallSnaps = {\n type: `${typeof controllerName}:install`;\n handler: SnapController['installSnaps'];\n};\n\nexport type RemoveSnapError = {\n type: `${typeof controllerName}:removeSnapError`;\n handler: SnapController['removeSnapError'];\n};\n\nexport type SnapControllerActions =\n | ClearSnapState\n | GetSnap\n | GetSnapState\n | HandleSnapRequest\n | HasSnap\n | UpdateBlockedSnaps\n | UpdateSnapState\n | EnableSnap\n | DisableSnap\n | RemoveSnap\n | GetPermittedSnaps\n | InstallSnaps\n | RemoveSnapError\n | GetAllSnaps\n | IncrementActiveReferences\n | DecrementActiveReferences;\n\n// Controller Messenger Events\n\nexport type SnapStateChange = {\n type: `${typeof controllerName}:stateChange`;\n payload: [SnapControllerState, Patch[]];\n};\n\n/**\n * Emitted when a Snap has been added to state during installation.\n */\nexport type SnapAdded = {\n type: `${typeof controllerName}:snapAdded`;\n payload: [snap: Snap, svgIcon: string | undefined];\n};\n\n/**\n * Emitted when an installed snap has been blocked.\n */\nexport type SnapBlocked = {\n type: `${typeof controllerName}:snapBlocked`;\n payload: [snapId: string, blockedSnapInfo: BlockedSnapInfo];\n};\n\n/**\n * Emitted when a snap has been started after being added and authorized during\n * installation.\n */\nexport type SnapInstalled = {\n type: `${typeof controllerName}:snapInstalled`;\n payload: [snap: TruncatedSnap];\n};\n\n/**\n * Emitted when a snap is removed.\n */\nexport type SnapRemoved = {\n type: `${typeof controllerName}:snapRemoved`;\n payload: [snap: TruncatedSnap];\n};\n\n/**\n * Emitted when an installed snap has been unblocked.\n */\nexport type SnapUnblocked = {\n type: `${typeof controllerName}:snapUnblocked`;\n payload: [snapId: string];\n};\n\n/**\n * Emitted when a snap is updated.\n */\nexport type SnapUpdated = {\n type: `${typeof controllerName}:snapUpdated`;\n payload: [snap: TruncatedSnap, oldVersion: string];\n};\n\n/**\n * Emitted when a snap is rolled back.\n */\nexport type SnapRolledback = {\n type: `${typeof controllerName}:snapRolledback`;\n payload: [snap: TruncatedSnap, failedVersion: string];\n};\n/**\n * Emitted when a Snap is terminated. This is different from the snap being\n * stopped as it can also be triggered when a snap fails initialization.\n */\nexport type SnapTerminated = {\n type: `${typeof controllerName}:snapTerminated`;\n payload: [snap: TruncatedSnap];\n};\n\nexport type SnapControllerEvents =\n | SnapAdded\n | SnapBlocked\n | SnapInstalled\n | SnapRemoved\n | SnapStateChange\n | SnapUnblocked\n | SnapUpdated\n | SnapRolledback\n | SnapTerminated;\n\nexport type AllowedActions =\n | GetEndowments\n | GetPermissions\n | GetSubjectMetadata\n | HasPermission\n | HasPermissions\n | RevokePermissions\n | RevokeAllPermissions\n | RevokePermissionForAllSubjects\n | GrantPermissions\n | AddApprovalRequest\n | HandleRpcRequestAction\n | ExecuteSnapAction\n | TerminateAllSnapsAction\n | TerminateSnapAction;\n\nexport type AllowedEvents = ExecutionServiceEvents;\n\ntype SnapControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SnapControllerActions | AllowedActions,\n SnapControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport enum AppKeyType {\n StateEncryption = 'stateEncryption',\n}\n\ntype GetAppKey = (subject: string, appKeyType: AppKeyType) => Promise<string>;\n\ntype FeatureFlags = {\n /**\n * We still need to implement new UI approval page in metamask-extension before we can allow\n * DApps to update Snaps. After it's added, this flag can be removed.\n *\n * @see {SNAP_APPROVAL_UPDATE}\n * @see {SnapController.processRequestedSnap}\n */\n dappsCanUpdateSnaps?: true;\n};\n\ntype SemVerVersion = string;\ntype SnapInfo = { version: SemVerVersion; shasum: string };\nexport type CheckSnapBlockListArg = Record<SnapId, SnapInfo>;\n\nexport type CheckSnapBlockListResult = Record<\n SnapId,\n | {\n blocked: true;\n reason?: string;\n infoUrl?: string;\n }\n | { blocked: false }\n>;\n\n/**\n * Checks whether a version of a snap is blocked.\n */\nexport type CheckSnapBlockList = (\n snapsToCheck: CheckSnapBlockListArg,\n) => Promise<CheckSnapBlockListResult>;\n\ntype SnapControllerArgs = {\n /**\n * A teardown function that allows the host to clean up its instrumentation\n * for a running snap.\n */\n closeAllConnections: CloseAllConnectionsFunction;\n\n /**\n * The names of endowment permissions whose values are the names of JavaScript\n * APIs that will be added to the snap execution environment at runtime.\n */\n environmentEndowmentPermissions: string[];\n\n /**\n * The function that will be used by the controller fo make network requests.\n * Should be compatible with {@link fetch}.\n */\n fetchFunction?: typeof fetch;\n\n /**\n * Flags that enable or disable features in the controller.\n * See {@link FeatureFlags}.\n */\n featureFlags: FeatureFlags;\n\n /**\n * A function to get an \"app key\" for a specific subject.\n */\n getAppKey: GetAppKey;\n\n /**\n * How frequently to check whether a snap is idle.\n */\n idleTimeCheckInterval?: number;\n\n /**\n * A function that checks whether the specified snap and version is blocked.\n */\n checkBlockList: CheckSnapBlockList;\n\n /**\n * The maximum amount of time that a snap may be idle.\n */\n maxIdleTime?: number;\n\n /**\n * The controller messenger.\n */\n messenger: SnapControllerMessenger;\n\n /**\n * The maximum amount of time a snap may take to process an RPC request,\n * unless it is permitted to take longer.\n */\n maxRequestTime?: number;\n\n /**\n * The npm registry URL that will be used to fetch published snaps.\n */\n npmRegistryUrl?: string;\n\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: PersistedSnapControllerState;\n\n /**\n * A function that takes Snap Id and converts it into a class that fetches files.\n *\n * Used for test overrides.\n */\n detectSnapLocation?: typeof detectSnapLocation;\n};\ntype AddSnapArgs = {\n id: SnapId;\n origin: string;\n location: SnapLocation;\n};\n\n// When we set a snap, we need all required properties to be present and\n// validated.\ntype SetSnapArgs = Omit<AddSnapArgs, 'id' | 'location'> & {\n id: ValidatedSnapId;\n manifest: VirtualFile<SnapManifest>;\n files: VirtualFile[];\n /**\n * @default '*'\n */\n // TODO(ritave): Used only for validation in #set, should be moved elsewhere.\n versionRange?: SemVerRange;\n isUpdate?: boolean;\n};\n\nconst defaultState: SnapControllerState = {\n snapErrors: {},\n snaps: {},\n snapStates: {},\n};\n\n/**\n * Truncates the properties of a snap to only ones that are easily serializable.\n *\n * @param snap - The snap to truncate.\n * @returns Object with serializable snap properties.\n */\nfunction truncateSnap(snap: Snap): TruncatedSnap {\n const truncatedSnap = Object.keys(snap).reduce<Partial<TruncatedSnap>>(\n (serialized, key) => {\n if (TRUNCATED_SNAP_PROPERTIES.has(key as any)) {\n serialized[key as keyof TruncatedSnap] = snap[\n key as keyof TruncatedSnap\n ] as any;\n }\n\n return serialized;\n },\n {},\n );\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return truncatedSnap as TruncatedSnap;\n}\n\nconst name = 'SnapController';\n\n/*\n * A snap is initialized in three phases:\n * - Add: Loads the snap from a remote source and parses it.\n * - Authorize: Requests the snap's required permissions from the user.\n * - Start: Initializes the snap in its SES realm with the authorized permissions.\n */\n\nexport class SnapController extends BaseController<\n string,\n SnapControllerState,\n SnapControllerMessenger\n> {\n #closeAllConnections: CloseAllConnectionsFunction;\n\n #environmentEndowmentPermissions: string[];\n\n #featureFlags: FeatureFlags;\n\n #fetchFunction: typeof fetch;\n\n #idleTimeCheckInterval: number;\n\n #checkSnapBlockList: CheckSnapBlockList;\n\n #maxIdleTime: number;\n\n // This property cannot be hash private yet because of tests.\n private readonly maxRequestTime: number;\n\n #detectSnapLocation: typeof detectSnapLocation;\n\n // This property cannot be hash private yet because of tests.\n private readonly snapsRuntimeData: Map<SnapId, SnapRuntimeData>;\n\n #rollbackSnapshots: Map<SnapId, RollbackSnapshot>;\n\n #getAppKey: GetAppKey;\n\n #timeoutForLastRequestStatus?: number;\n\n #statusMachine!: StateMachine.Machine<\n StatusContext,\n StatusEvents,\n StatusStates\n >;\n\n constructor({\n closeAllConnections,\n messenger,\n state,\n getAppKey,\n environmentEndowmentPermissions = [],\n idleTimeCheckInterval = inMilliseconds(5, Duration.Second),\n checkBlockList,\n maxIdleTime = inMilliseconds(30, Duration.Second),\n maxRequestTime = inMilliseconds(60, Duration.Second),\n fetchFunction = globalThis.fetch.bind(globalThis),\n featureFlags = {},\n detectSnapLocation: detectSnapLocationFunction = detectSnapLocation,\n }: SnapControllerArgs) {\n super({\n messenger,\n metadata: {\n snapErrors: {\n persist: false,\n anonymous: false,\n },\n snapStates: {\n persist: () => {\n return Object.keys(this.state.snaps).reduce<\n Record<string, string | null>\n >((acc, cur) => {\n acc[cur] = this.#getRuntimeExpect(cur).state;\n return acc;\n }, {});\n },\n anonymous: false,\n },\n snaps: {\n persist: (snaps) => {\n return Object.values(snaps)\n .map((snap) => {\n return {\n ...snap,\n sourceCode: this.#getRuntimeExpect(snap.id).sourceCode,\n // At the time state is rehydrated, no snap will be running.\n status: SnapStatus.Stopped,\n };\n })\n .reduce((memo: Record<string, Snap>, snap) => {\n memo[snap.id] = snap;\n return memo;\n }, {});\n },\n anonymous: false,\n },\n },\n name,\n state: {\n ...defaultState,\n ...{\n ...state,\n snaps: Object.values(state?.snaps ?? {}).reduce(\n (memo: Record<string, Snap>, snap) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { sourceCode, ...rest } = snap;\n memo[snap.id] = rest;\n return memo;\n },\n {},\n ),\n },\n },\n });\n\n this.#closeAllConnections = closeAllConnections;\n this.#environmentEndowmentPermissions = environmentEndowmentPermissions;\n this.#featureFlags = featureFlags;\n this.#fetchFunction = fetchFunction;\n this.#getAppKey = getAppKey;\n this.#idleTimeCheckInterval = idleTimeCheckInterval;\n this.#checkSnapBlockList = checkBlockList;\n this.#maxIdleTime = maxIdleTime;\n this.maxRequestTime = maxRequestTime;\n this.#detectSnapLocation = detectSnapLocationFunction;\n this._onUnhandledSnapError = this._onUnhandledSnapError.bind(this);\n this._onOutboundRequest = this._onOutboundRequest.bind(this);\n this._onOutboundResponse = this._onOutboundResponse.bind(this);\n this.#rollbackSnapshots = new Map();\n this.snapsRuntimeData = new Map();\n this.#pollForLastRequestStatus();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'ExecutionService:unhandledError',\n this._onUnhandledSnapError,\n );\n\n this.messagingSystem.subscribe(\n 'ExecutionService:outboundRequest',\n this._onOutboundRequest,\n );\n\n this.messagingSystem.subscribe(\n 'ExecutionService:outboundResponse',\n this._onOutboundResponse,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#initializeStateMachine();\n this.#registerMessageHandlers();\n\n Object.values(state?.snaps ?? {}).forEach((snap) =>\n this.#setupRuntime(snap.id, {\n sourceCode: snap.sourceCode,\n state: state?.snapStates?.[snap.id] ?? null,\n }),\n );\n }\n\n /**\n * We track status of a Snap using a finite-state-machine.\n * It keeps track of whether the snap is started / stopped / etc.\n *\n * @see {@link SnapController.transition} for interacting with the machine.\n */\n // We initialize the machine in the instance because the status is currently tightly coupled\n // with the SnapController - the guard checks for enabled status inside the SnapController state.\n // In the future, side-effects could be added to the machine during transitions.\n #initializeStateMachine() {\n const disableGuard = ({ snapId }: StatusContext) => {\n return this.getExpect(snapId).enabled;\n };\n\n const statusConfig: StateMachine.Config<\n StatusContext,\n StatusEvents,\n StatusStates\n > = {\n initial: SnapStatus.Installing,\n states: {\n [SnapStatus.Installing]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n },\n },\n [SnapStatus.Updating]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n },\n },\n [SnapStatus.Running]: {\n on: {\n [SnapStatusEvents.Stop]: SnapStatus.Stopped,\n [SnapStatusEvents.Crash]: SnapStatus.Crashed,\n },\n },\n [SnapStatus.Stopped]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n [SnapStatusEvents.Update]: SnapStatus.Updating,\n },\n },\n [SnapStatus.Crashed]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n },\n },\n },\n };\n this.#statusMachine = createMachine(statusConfig);\n validateMachine(this.#statusMachine);\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:clearSnapState`,\n (...args) => this.clearSnapState(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:get`,\n (...args) => this.get(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getSnapState`,\n async (...args) => this.getSnapState(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:handleRequest`,\n async (...args) => this.handleRequest(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:has`,\n (...args) => this.has(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateBlockedSnaps`,\n async () => this.updateBlockedSnaps(),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateSnapState`,\n async (...args) => this.updateSnapState(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:enable`,\n (...args) => this.enableSnap(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:disable`,\n async (...args) => this.disableSnap(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:remove`,\n async (...args) => this.removeSnap(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getPermitted`,\n (...args) => this.getPermittedSnaps(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:install`,\n async (...args) => this.installSnaps(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:removeSnapError`,\n (...args) => this.removeSnapError(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getAll`,\n (...args) => this.getAllSnaps(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:incrementActiveReferences`,\n (...args) => this.incrementActiveReferences(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:decrementActiveReferences`,\n (...args) => this.decrementActiveReferences(...args),\n );\n }\n\n #pollForLastRequestStatus() {\n this.#timeoutForLastRequestStatus = setTimeout(() => {\n this.#stopSnapsLastRequestPastMax().catch((error) => {\n // TODO: Decide how to handle errors.\n console.error(error);\n });\n\n this.#pollForLastRequestStatus();\n }, this.#idleTimeCheckInterval) as unknown as number;\n }\n\n /**\n * Checks all installed snaps against the block list and\n * blocks/unblocks snaps as appropriate. See {@link SnapController.blockSnap}\n * for more information.\n */\n async updateBlockedSnaps(): Promise<void> {\n const blockedSnaps = await this.#checkSnapBlockList(\n Object.values(this.state.snaps).reduce<CheckSnapBlockListArg>(\n (blockListArg, snap) => {\n blockListArg[snap.id] = {\n version: snap.version,\n shasum: snap.manifest.source.shasum,\n };\n return blockListArg;\n },\n {},\n ),\n );\n\n await Promise.all(\n Object.entries(blockedSnaps).map(\n async ([snapId, { blocked, ...blockData }]) => {\n if (blocked) {\n return this.#blockSnap(snapId, blockData);\n }\n\n return this.#unblockSnap(snapId);\n },\n ),\n );\n }\n\n /**\n * Blocks an installed snap and prevents it from being started again. Emits\n * {@link SnapBlocked}. Does nothing if the snap is not installed.\n *\n * @param snapId - The snap to block.\n * @param blockedSnapInfo - Information detailing why the snap is blocked.\n */\n async #blockSnap(\n snapId: SnapId,\n blockedSnapInfo: BlockedSnapInfo,\n ): Promise<void> {\n if (!this.has(snapId)) {\n return;\n }\n\n try {\n this.update((state: any) => {\n state.snaps[snapId].blocked = true;\n state.snaps[snapId].blockInformation = blockedSnapInfo;\n });\n\n await this.disableSnap(snapId);\n } catch (error) {\n console.error(\n `Encountered error when stopping blocked snap \"${snapId}\".`,\n error,\n );\n }\n\n this.messagingSystem.publish(\n `${controllerName}:snapBlocked`,\n snapId,\n blockedSnapInfo,\n );\n }\n\n /**\n * Unblocks a snap so that it can be enabled and started again. Emits\n * {@link SnapUnblocked}. Does nothing if the snap is not installed or already\n * unblocked.\n *\n * @param snapId - The id of the snap to unblock.\n */\n #unblockSnap(snapId: SnapId) {\n if (!this.has(snapId) || !this.state.snaps[snapId].blocked) {\n return;\n }\n\n this.update((state: any) => {\n state.snaps[snapId].blocked = false;\n delete state.snaps[snapId].blockInformation;\n });\n\n this.messagingSystem.publish(`${controllerName}:snapUnblocked`, snapId);\n }\n\n /**\n * Checks the block list to determine whether a version of a snap is blocked.\n *\n * @param snapId - The snap id to check.\n * @param snapInfo - Snap information containing version and shasum.\n * @returns Whether the version of the snap is blocked or not.\n */\n async isBlocked(\n snapId: ValidatedSnapId,\n snapInfo: SnapInfo,\n ): Promise<boolean> {\n const result = await this.#checkSnapBlockList({\n [snapId]: snapInfo,\n });\n return result[snapId].blocked;\n }\n\n /**\n * Asserts that a version of a snap is not blocked. Succeeds automatically\n * if {@link SnapController._checkSnapBlockList} is undefined.\n *\n * @param snapId - The id of the snap to check.\n * @param snapInfo - Snap information containing version and shasum.\n */\n async #assertIsUnblocked(snapId: ValidatedSnapId, snapInfo: SnapInfo) {\n if (await this.isBlocked(snapId, snapInfo)) {\n throw new Error(\n `Cannot install version \"${snapInfo.version}\" of snap \"${snapId}\": the version is blocked.`,\n );\n }\n }\n\n async #stopSnapsLastRequestPastMax() {\n const entries = [...this.snapsRuntimeData.entries()];\n return Promise.all(\n entries\n .filter(\n ([_snapId, runtime]) =>\n runtime.activeReferences === 0 &&\n runtime.pendingInboundRequests.length === 0 &&\n // lastRequest should always be set here but TypeScript wants this check\n runtime.lastRequest &&\n this.#maxIdleTime &&\n timeSince(runtime.lastRequest) > this.#maxIdleTime,\n )\n .map(async ([snapId]) => this.stopSnap(snapId, SnapStatusEvents.Stop)),\n );\n }\n\n _onUnhandledSnapError(snapId: SnapId, error: SnapErrorJson) {\n this.stopSnap(snapId, SnapStatusEvents.Crash)\n .then(() => this.addSnapError(error))\n .catch((stopSnapError) => {\n // TODO: Decide how to handle errors.\n console.error(stopSnapError);\n });\n }\n\n _onOutboundRequest(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n // Ideally we would only pause the pending request that is making the outbound request\n // but right now we don't have a way to know which request initiated the outbound request\n runtime.pendingInboundRequests\n .filter((pendingRequest) => pendingRequest.timer.status === 'running')\n .forEach((pendingRequest) => pendingRequest.timer.pause());\n runtime.pendingOutboundRequests += 1;\n }\n\n _onOutboundResponse(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.pendingOutboundRequests -= 1;\n if (runtime.pendingOutboundRequests === 0) {\n runtime.pendingInboundRequests\n .filter((pendingRequest) => pendingRequest.timer.status === 'paused')\n .forEach((pendingRequest) => pendingRequest.timer.resume());\n }\n }\n\n /**\n * Transitions between states using `snapStatusStateMachineConfig` as the template to figure out\n * the next state. This transition function uses a very minimal subset of XState conventions:\n * - supports initial state\n * - .on supports raw event target string\n * - .on supports {target, cond} object\n * - the arguments for `cond` is the `SerializedSnap` instead of Xstate convention of `(event,\n * context) => boolean`\n *\n * @param snapId - The id of the snap to transition.\n * @param event - The event enum to use to transition.\n */\n #transition(snapId: SnapId, event: StatusEvents | StatusEvents['type']) {\n const { interpreter } = this.#getRuntimeExpect(snapId);\n interpreter.send(event);\n this.update((state: any) => {\n state.snaps[snapId].status = interpreter.state.value;\n });\n }\n\n /**\n * Starts the given snap. Throws an error if no such snap exists\n * or if it is already running.\n *\n * @param snapId - The id of the Snap to start.\n */\n async startSnap(snapId: SnapId): Promise<void> {\n const runtime = this.#getRuntimeExpect(snapId);\n\n if (this.state.snaps[snapId].enabled === false) {\n throw new Error(`Snap \"${snapId}\" is disabled.`);\n }\n\n assert(runtime.sourceCode);\n\n await this.#startSnap({\n snapId,\n sourceCode: runtime.sourceCode,\n });\n }\n\n /**\n * Enables the given snap. A snap can only be started if it is enabled. A snap\n * can only be enabled if it isn't blocked.\n *\n * @param snapId - The id of the Snap to enable.\n */\n enableSnap(snapId: SnapId): void {\n this.getExpect(snapId);\n\n if (this.state.snaps[snapId].blocked) {\n throw new Error(`Snap \"${snapId}\" is blocked and cannot be enabled.`);\n }\n\n this.update((state: any) => {\n state.snaps[snapId].enabled = true;\n });\n }\n\n /**\n * Disables the given snap. A snap can only be started if it is enabled.\n *\n * @param snapId - The id of the Snap to disable.\n * @returns A promise that resolves once the snap has been disabled.\n */\n async disableSnap(snapId: SnapId): Promise<void> {\n if (!this.has(snapId)) {\n throw new Error(`Snap \"${snapId}\" not found.`);\n }\n\n this.update((state: any) => {\n state.snaps[snapId].enabled = false;\n });\n\n if (this.isRunning(snapId)) {\n return this.stopSnap(snapId, SnapStatusEvents.Stop);\n }\n\n return Promise.resolve();\n }\n\n /**\n * Stops the given snap, removes all hooks, closes all connections, and\n * terminates its worker.\n *\n * @param snapId - The id of the Snap to stop.\n * @param statusEvent - The Snap status event that caused the snap to be\n * stopped.\n */\n public async stopSnap(\n snapId: SnapId,\n statusEvent:\n | SnapStatusEvents.Stop\n | SnapStatusEvents.Crash = SnapStatusEvents.Stop,\n ): Promise<void> {\n const runtime = this.#getRuntime(snapId);\n if (!runtime) {\n throw new Error(`The snap \"${snapId}\" is not running.`);\n }\n\n // Reset request tracking\n runtime.lastRequest = null;\n runtime.pendingInboundRequests = [];\n runtime.pendingOutboundRequests = 0;\n try {\n if (this.isRunning(snapId)) {\n this.#closeAllConnections(snapId);\n await this.#terminateSnap(snapId);\n }\n } finally {\n if (this.isRunning(snapId)) {\n this.#transition(snapId, statusEvent);\n }\n }\n }\n\n /**\n * Terminates the specified snap and emits the `snapTerminated` event.\n *\n * @param snapId - The snap to terminate.\n */\n async #terminateSnap(snapId: SnapId) {\n await this.messagingSystem.call('ExecutionService:terminateSnap', snapId);\n this.messagingSystem.publish(\n 'SnapController:snapTerminated',\n this.getTruncatedExpect(snapId),\n );\n }\n\n /**\n * Returns whether the given snap is running.\n * Throws an error if the snap doesn't exist.\n *\n * @param snapId - The id of the Snap to check.\n * @returns `true` if the snap is running, otherwise `false`.\n */\n isRunning(snapId: SnapId): boolean {\n return this.getExpect(snapId).status === 'running';\n }\n\n /**\n * Returns whether the given snap has been added to state.\n *\n * @param snapId - The id of the Snap to check for.\n * @returns `true` if the snap exists in the controller state, otherwise `false`.\n */\n has(snapId: SnapId): boolean {\n return Boolean(this.get(snapId));\n }\n\n /**\n * Gets the snap with the given id if it exists, including all data.\n * This should not be used if the snap is to be serializable, as e.g.\n * the snap sourceCode may be quite large.\n *\n * @param snapId - The id of the Snap to get.\n * @returns The entire snap object from the controller state.\n */\n get(snapId: SnapId): Snap | undefined {\n return this.state.snaps[snapId];\n }\n\n /**\n * Gets the snap with the given id, throws if doesn't.\n * This should not be used if the snap is to be serializable, as e.g.\n * the snap sourceCode may be quite large.\n *\n * @see {@link SnapController.get}\n * @throws {@link Error}. If the snap doesn't exist\n * @param snapId - The id of the snap to get.\n * @returns The entire snap object.\n */\n getExpect(snapId: SnapId): Snap {\n const snap = this.get(snapId);\n assert(snap !== undefined, new Error(`Snap \"${snapId}\" not found.`));\n return snap;\n }\n\n /**\n * Gets the snap with the given id if it exists, excluding any\n * non-serializable or expensive-to-serialize data.\n *\n * @param snapId - The id of the Snap to get.\n * @returns A truncated version of the snap state, that is less expensive to serialize.\n */\n // TODO(ritave): this.get returns undefined, this.getTruncated returns null\n getTruncated(snapId: SnapId): TruncatedSnap | null {\n const snap = this.get(snapId);\n\n return snap ? truncateSnap(snap) : null;\n }\n\n /**\n * Gets the snap with the given id, throw if it doesn't exist.\n *\n * @throws {@link Error}. If snap doesn't exist\n * @param snapId - The id of the snap to get.\n * @returns A truncated version of the snap state, that is less expensive to serialize.\n */\n getTruncatedExpect(snapId: SnapId): TruncatedSnap {\n return truncateSnap(this.getExpect(snapId));\n }\n\n /**\n * Updates the own state of the snap with the given id.\n * This is distinct from the state MetaMask uses to manage snaps.\n *\n * @param snapId - The id of the Snap whose state should be updated.\n * @param newSnapState - The new state of the snap.\n */\n async updateSnapState(snapId: SnapId, newSnapState: Json): Promise<void> {\n const encrypted = await this.#encryptSnapState(snapId, newSnapState);\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.state = encrypted;\n }\n\n /**\n * Clears the state of the snap with the given id.\n * This is distinct from the state MetaMask uses to manage snaps.\n *\n * @param snapId - The id of the Snap whose state should be cleared.\n */\n clearSnapState(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.state = null;\n }\n\n /**\n * Adds error from a snap to the SnapController state.\n *\n * @param snapError - The error to store on the SnapController.\n */\n addSnapError(snapError: SnapError): void {\n this.update((state: any) => {\n const id = nanoid();\n state.snapErrors[id] = {\n ...snapError,\n internalID: id,\n };\n });\n }\n\n /**\n * Removes an error by internalID from the SnapControllers state.\n *\n * @param internalID - The internal error ID to remove on the SnapController.\n */\n removeSnapError(internalID: string) {\n this.update((state: any) => {\n delete state.snapErrors[internalID];\n });\n }\n\n /**\n * Clears all errors from the SnapControllers state.\n */\n clearSnapErrors() {\n this.update((state: any) => {\n state.snapErrors = {};\n });\n }\n\n /**\n * Gets the own state of the snap with the given id.\n * This is distinct from the state MetaMask uses to manage snaps.\n *\n * @param snapId - The id of the Snap whose state to get.\n * @returns A promise that resolves with the decrypted snap state or null if no state exists.\n * @throws If the snap state decryption fails.\n */\n async getSnapState(snapId: SnapId): Promise<Json> {\n const { state } = this.#getRuntimeExpect(snapId);\n return state ? this.#decryptSnapState(snapId, state) : null;\n }\n\n async #getEncryptionKey(snapId: SnapId): Promise<string> {\n return this.#getAppKey(snapId, AppKeyType.StateEncryption);\n }\n\n async #encryptSnapState(snapId: SnapId, state: Json): Promise<string> {\n const appKey = await this.#getEncryptionKey(snapId);\n return encrypt(appKey, state);\n }\n\n async #decryptSnapState(snapId: SnapId, encrypted: string): Promise<Json> {\n const appKey = await this.#getEncryptionKey(snapId);\n try {\n const value = await decrypt(appKey, encrypted);\n\n assert(isValidJson(value));\n return value;\n } catch (error) {\n throw new Error(\n 'Failed to decrypt snap state, the state must be corrupted.',\n );\n }\n }\n\n /**\n * Completely clear the controller's state: delete all associated data,\n * handlers, event listeners, and permissions; tear down all snap providers.\n */\n async clearState() {\n const snapIds = Object.keys(this.state.snaps);\n snapIds.forEach((snapId) => {\n this.#closeAllConnections(snapId);\n });\n\n await this.messagingSystem.call('ExecutionService:terminateAllSnaps');\n snapIds.forEach((snapId) => this.revokeAllSnapPermissions(snapId));\n\n this.update((state: any) => {\n state.snaps = {};\n state.snapStates = {};\n });\n }\n\n /**\n * Removes the given snap from state, and clears all associated handlers\n * and listeners.\n *\n * @param snapId - The id of the Snap.\n * @returns A promise that resolves once the snap has been removed.\n */\n async removeSnap(snapId: SnapId): Promise<void> {\n return this.removeSnaps([snapId]);\n }\n\n /**\n * Stops the given snaps, removes them from state, and clears all associated\n * permissions, handlers, and listeners.\n *\n * @param snapIds - The ids of the Snaps.\n */\n async removeSnaps(snapIds: string[]): Promise<void> {\n if (!Array.isArray(snapIds)) {\n throw new Error('Expected array of snap ids.');\n }\n\n await Promise.all(\n snapIds.map(async (snapId) => {\n const truncated = this.getTruncatedExpect(snapId);\n // Disable the snap and revoke all of its permissions before deleting\n // it. This ensures that the snap will not be restarted or otherwise\n // affect the host environment while we are deleting it.\n await this.disableSnap(snapId);\n this.revokeAllSnapPermissions(snapId);\n\n const permissionName = getSnapPermissionName(snapId);\n // Revoke all subjects access to the snap\n this.messagingSystem.call(\n 'PermissionController:revokePermissionForAllSubjects',\n permissionName,\n );\n\n this.snapsRuntimeData.delete(snapId);\n\n this.update((state: any) => {\n delete state.snaps[snapId];\n delete state.snapStates[snapId];\n });\n\n this.messagingSystem.publish(`SnapController:snapRemoved`, truncated);\n }),\n );\n }\n\n /**\n * Safely revokes all permissions granted to a Snap.\n *\n * @param snapId - The snap ID.\n */\n private revokeAllSnapPermissions(snapId: string) {\n if (\n this.messagingSystem.call('PermissionController:hasPermissions', snapId)\n ) {\n this.messagingSystem.call(\n 'PermissionController:revokeAllPermissions',\n snapId,\n );\n }\n }\n\n /**\n * Handles incrementing the activeReferences counter.\n *\n * @param snapId - The snap id of the snap that was referenced.\n */\n incrementActiveReferences(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.activeReferences += 1;\n }\n\n /**\n * Handles decrement the activeReferences counter.\n *\n * @param snapId - The snap id of the snap that was referenced..\n */\n decrementActiveReferences(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n assert(\n runtime.activeReferences > 0,\n 'SnapController reference management is in an invalid state.',\n );\n runtime.activeReferences -= 1;\n }\n\n /**\n * Gets all snaps in their truncated format.\n *\n * @returns All installed snaps in their truncated format.\n */\n getAllSnaps(): TruncatedSnap[] {\n return Object.values(this.state.snaps).map(truncateSnap);\n }\n\n /**\n * Gets the serialized permitted snaps of the given origin, if any.\n *\n * @param origin - The origin whose permitted snaps to retrieve.\n * @returns The serialized permitted snaps for the origin.\n */\n getPermittedSnaps(origin: string): InstallSnapsResult {\n return Object.values(\n this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n ) ?? {},\n ).reduce<InstallSnapsResult>((permittedSnaps, perm) => {\n if (perm.parentCapability.startsWith(SNAP_PREFIX)) {\n const snapId = perm.parentCapability.replace(SNAP_PREFIX_REGEX, '');\n const snap = this.get(snapId);\n const truncatedSnap = this.getTruncated(snapId);\n\n if (truncatedSnap && snap?.status !== SnapStatus.Installing) {\n permittedSnaps[snapId] = truncatedSnap;\n }\n }\n return permittedSnaps;\n }, {});\n }\n\n /**\n * Installs the snaps requested by the given origin, returning the snap\n * object if the origin is permitted to install it, and an authorization error\n * otherwise.\n *\n * @param origin - The origin that requested to install the snaps.\n * @param requestedSnaps - The snaps to install.\n * @returns An object of snap ids and snap objects, or errors if a\n * snap couldn't be installed.\n */\n async installSnaps(\n origin: string,\n requestedSnaps: RequestedSnapPermissions,\n ): Promise<InstallSnapsResult> {\n const result: InstallSnapsResult = {};\n\n const snapIds = Object.keys(requestedSnaps);\n\n // Existing snaps may need to be updated\n const pendingUpdates = snapIds.filter((snapId) => this.has(snapId));\n\n // Non-existing snaps will need to be installed\n const pendingInstalls = snapIds.filter(\n (snapId) => !pendingUpdates.includes(snapId),\n );\n\n try {\n for (const [snapId, { version: rawVersion }] of Object.entries(\n requestedSnaps,\n )) {\n const [error, version] = resolveVersionRange(rawVersion);\n\n if (error) {\n throw ethErrors.rpc.invalidParams(\n `The \"version\" field must be a valid SemVer version range if specified. Received: \"${rawVersion}\".`,\n );\n }\n\n const permissionName = getSnapPermissionName(snapId);\n\n if (\n !this.messagingSystem.call(\n 'PermissionController:hasPermission',\n origin,\n permissionName,\n )\n ) {\n throw ethErrors.provider.unauthorized(\n `Not authorized to install snap \"${snapId}\". Request the permission for the snap before attempting to install it.`,\n );\n }\n\n const isUpdate = pendingUpdates.includes(snapId);\n\n if (isUpdate && this.#isValidUpdate(snapId, version)) {\n let rollbackSnapshot = this.#getRollbackSnapshot(snapId);\n if (rollbackSnapshot === undefined) {\n const prevSourceCode = this.#getRuntimeExpect(snapId).sourceCode;\n rollbackSnapshot = this.#createRollbackSnapshot(snapId);\n rollbackSnapshot.sourceCode = prevSourceCode;\n rollbackSnapshot.newVersion = version;\n } else {\n throw new Error('This snap is already being updated.');\n }\n }\n\n result[snapId] = await this.processRequestedSnap(\n origin,\n snapId,\n version,\n );\n }\n snapIds.forEach((snapId) => this.#rollbackSnapshots.delete(snapId));\n } catch (error) {\n const installed = pendingInstalls.filter((snapId) => this.has(snapId));\n await this.removeSnaps(installed);\n const snapshottedSnaps = [...this.#rollbackSnapshots.keys()];\n const snapsToRollback = pendingUpdates.filter((snapId) =>\n snapshottedSnaps.includes(snapId),\n );\n await this.#rollbackSnaps(snapsToRollback);\n\n throw error;\n }\n return result;\n }\n\n /**\n * Adds, authorizes, and runs the given snap with a snap provider.\n * Results from this method should be efficiently serializable.\n *\n * @param origin - The origin requesting the snap.\n * @param snapId - The id of the snap.\n * @param versionRange - The semver range of the snap to install.\n * @returns The resulting snap object, or an error if something went wrong.\n */\n private async processRequestedSnap(\n origin: string,\n snapId: SnapId,\n versionRange: SemVerRange,\n ): Promise<ProcessSnapResult> {\n validateSnapId(snapId);\n\n const location = this.#detectSnapLocation(snapId, {\n versionRange,\n fetch: this.#fetchFunction,\n });\n\n const existingSnap = this.getTruncated(snapId);\n // For devX we always re-install local snaps.\n if (existingSnap && !location.shouldAlwaysReload) {\n if (satisfiesVersionRange(existingSnap.version, versionRange)) {\n return existingSnap;\n }\n\n if (this.#featureFlags.dappsCanUpdateSnaps === true) {\n const updateResult = await this.updateSnap(\n origin,\n snapId,\n versionRange,\n location,\n );\n if (updateResult === null) {\n throw ethErrors.rpc.invalidParams(\n `Snap \"${snapId}@${existingSnap.version}\" is already installed. Couldn't update to a version inside requested \"${versionRange}\" range.`,\n );\n }\n return updateResult;\n }\n throw ethErrors.rpc.invalidParams(\n `Version mismatch with already installed snap. ${snapId}@${existingSnap.version} doesn't satisfy requested version ${versionRange}.`,\n );\n }\n\n // Existing snaps must be stopped before overwriting\n if (existingSnap && this.isRunning(snapId)) {\n await this.stopSnap(snapId, SnapStatusEvents.Stop);\n }\n\n try {\n const { sourceCode } = await this.#add({\n origin,\n id: snapId,\n location,\n });\n\n await this.authorize(origin, snapId);\n\n await this.#startSnap({\n snapId,\n sourceCode,\n });\n\n const truncated = this.getTruncatedExpect(snapId);\n\n this.messagingSystem.publish(`SnapController:snapInstalled`, truncated);\n return truncated;\n } catch (error) {\n console.error(`Error when adding snap.`, error);\n\n throw error;\n }\n }\n\n /**\n * Updates an installed snap. The flow is similar to\n * {@link SnapController.installSnaps}. The user will be asked if they want\n * to update, then approve any permission changes, and finally the snap will\n * be restarted.\n *\n * The update will fail if the user rejects any prompt or if the new version\n * of the snap is blocked.\n *\n * If the original version of the snap was blocked and the update succeeded,\n * the snap will be unblocked and enabled before it is restarted.\n *\n * @param origin - The origin requesting the snap update.\n * @param snapId - The id of the Snap to be updated.\n * @param newVersionRange - A semver version range in which the maximum version will be chosen.\n * @param location - Optional location that was already used during installation flow.\n * @returns The snap metadata if updated, `null` otherwise.\n */\n async updateSnap(\n origin: string,\n snapId: ValidatedSnapId,\n newVersionRange: string = DEFAULT_REQUESTED_SNAP_VERSION,\n location?: SnapLocation,\n ): Promise<TruncatedSnap | null> {\n const snap = this.getExpect(snapId);\n\n if (!isValidSemVerRange(newVersionRange)) {\n throw new Error(\n `Received invalid snap version range: \"${newVersionRange}\".`,\n );\n }\n const newSnap = await this.#fetchSnap(\n snapId,\n location ??\n this.#detectSnapLocation(snapId, { versionRange: newVersionRange }),\n );\n const newVersion = newSnap.manifest.result.version;\n if (!gtVersion(newVersion, snap.version)) {\n console.warn(\n `Tried updating snap \"${snapId}\" within \"${newVersionRange}\" version range, but newer version \"${snap.version}\" is already installed`,\n );\n return null;\n }\n\n await this.#assertIsUnblocked(snapId, {\n version: newVersion,\n shasum: newSnap.manifest.result.source.shasum,\n });\n\n const processedPermissions = this.#processSnapPermissions(\n newSnap.manifest.result.initialPermissions,\n );\n\n const { newPermissions, unusedPermissions, approvedPermissions } =\n this.#calculatePermissionsChange(snapId, processedPermissions);\n\n const id = nanoid();\n const { permissions: approvedNewPermissions, ...requestData } =\n (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n origin,\n id,\n type: SNAP_APPROVAL_UPDATE,\n requestData: {\n // First two keys mirror installation params\n metadata: { id, origin: snapId, dappOrigin: origin },\n permissions: newPermissions,\n snapId,\n newVersion: newSnap.manifest.result.version,\n newPermissions,\n approvedPermissions,\n unusedPermissions,\n },\n },\n true,\n )) as PermissionsRequest;\n\n if (this.isRunning(snapId)) {\n await this.stopSnap(snapId, SnapStatusEvents.Stop);\n }\n\n this.#transition(snapId, SnapStatusEvents.Update);\n\n this.#set({\n origin,\n id: snapId,\n manifest: newSnap.manifest,\n files: newSnap.files,\n versionRange: newVersionRange,\n isUpdate: true,\n });\n\n const unusedPermissionsKeys = Object.keys(unusedPermissions);\n if (isNonEmptyArray(unusedPermissionsKeys)) {\n this.messagingSystem.call('PermissionController:revokePermissions', {\n [snapId]: unusedPermissionsKeys,\n });\n }\n\n if (isNonEmptyArray(Object.keys(approvedNewPermissions))) {\n this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions: approvedNewPermissions,\n subject: { origin: snapId },\n requestData,\n });\n }\n\n const rollbackSnapshot = this.#getRollbackSnapshot(snapId);\n if (rollbackSnapshot !== undefined) {\n rollbackSnapshot.permissions.revoked = unusedPermissions;\n rollbackSnapshot.permissions.granted = Object.keys(\n approvedNewPermissions,\n );\n rollbackSnapshot.permissions.requestData = requestData;\n }\n\n const sourceCode = newSnap.files\n .find(\n (file) =>\n file.path === newSnap.manifest.result.source.location.npm.filePath,\n )\n ?.toString();\n assert(sourceCode !== undefined);\n\n try {\n await this.#startSnap({ snapId, sourceCode });\n } catch {\n throw new Error(`Snap ${snapId} crashed with updated source code.`);\n }\n\n const truncatedSnap = this.getTruncatedExpect(snapId);\n this.messagingSystem.publish(\n 'SnapController:snapUpdated',\n truncatedSnap,\n snap.version,\n );\n\n return truncatedSnap;\n }\n\n /**\n * Returns a promise representing the complete installation of the requested snap.\n * If the snap is already being installed, the previously pending promise will be returned.\n *\n * @param args - Object containing the snap id and either the URL of the snap's manifest,\n * or the snap's manifest and source code. The object may also optionally contain a target\n * version.\n * @returns The resulting snap object.\n */\n async #add(args: AddSnapArgs): Promise<PersistedSnap> {\n const { id: snapId, location } = args;\n validateSnapId(snapId);\n\n this.#setupRuntime(snapId, { sourceCode: null, state: null });\n const runtime = this.#getRuntimeExpect(snapId);\n if (!runtime.installPromise) {\n console.info(`Adding snap: ${snapId}`);\n\n // If fetching and setting the snap succeeds, this property will be set\n // to null in the authorize() method.\n runtime.installPromise = (async () => {\n const fetchedSnap = await this.#fetchSnap(snapId, location);\n await this.#assertIsUnblocked(snapId, {\n version: fetchedSnap.manifest.result.version,\n shasum: fetchedSnap.manifest.result.source.shasum,\n });\n\n return this.#set({\n ...args,\n ...fetchedSnap,\n id: snapId,\n });\n })();\n }\n\n try {\n return await runtime.installPromise;\n } catch (error) {\n // Reset promise so users can retry installation in case the problem is\n // temporary.\n runtime.installPromise = null;\n throw error;\n }\n }\n\n async #startSnap(snapData: { snapId: string; sourceCode: string }) {\n const { snapId } = snapData;\n if (this.isRunning(snapId)) {\n throw new Error(`Snap \"${snapId}\" is already started.`);\n }\n\n try {\n const result = await this.#executeWithTimeout(\n snapId,\n this.messagingSystem.call('ExecutionService:executeSnap', {\n ...snapData,\n endowments: await this.#getEndowments(snapId),\n }),\n );\n this.#transition(snapId, SnapStatusEvents.Start);\n return result;\n } catch (error) {\n await this.#terminateSnap(snapId);\n throw error;\n }\n }\n\n /**\n * Gets the names of all endowments that will be added to the Snap's\n * Compartment when it executes. These should be the names of global\n * JavaScript APIs accessible in the root realm of the execution environment.\n *\n * Throws an error if the endowment getter for a permission returns a truthy\n * value that is not an array of strings.\n *\n * @param snapId - The id of the snap whose SES endowments to get.\n * @returns An array of the names of the endowments.\n */\n async #getEndowments(snapId: string): Promise<string[]> {\n let allEndowments: string[] = [];\n\n for (const permissionName of this.#environmentEndowmentPermissions) {\n if (\n this.messagingSystem.call(\n 'PermissionController:hasPermission',\n snapId,\n permissionName,\n )\n ) {\n const endowments = await this.messagingSystem.call(\n 'PermissionController:getEndowments',\n snapId,\n permissionName,\n );\n\n if (endowments) {\n // We don't have any guarantees about the type of the endowments\n // value, so we have to guard at runtime.\n if (\n !Array.isArray(endowments) ||\n endowments.some((value) => typeof value !== 'string')\n ) {\n throw new Error('Expected an array of string endowment names.');\n }\n\n allEndowments = allEndowments.concat(endowments as string[]);\n }\n }\n }\n\n const dedupedEndowments = [\n ...new Set([...DEFAULT_ENDOWMENTS, ...allEndowments]),\n ];\n\n if (\n dedupedEndowments.length <\n // This is a bug in TypeScript: https://github.com/microsoft/TypeScript/issues/48313\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n DEFAULT_ENDOWMENTS.length + allEndowments.length\n ) {\n console.error(\n 'Duplicate endowments found. Default endowments should not be requested.',\n allEndowments,\n );\n }\n return dedupedEndowments;\n }\n\n /**\n * Sets a snap in state. Called when a snap is installed or updated. Performs\n * various validation checks on the received arguments, and will throw if\n * validation fails.\n *\n * The snap will be enabled and unblocked by the time this method returns,\n * regardless of its previous state.\n *\n * See {@link SnapController.add} and {@link SnapController.updateSnap} for\n * usage.\n *\n * @param args - The add snap args.\n * @returns The resulting snap object.\n */\n #set(args: SetSnapArgs): PersistedSnap {\n const {\n id: snapId,\n origin,\n manifest,\n files,\n versionRange = DEFAULT_REQUESTED_SNAP_VERSION,\n isUpdate = false,\n } = args;\n\n assertIsSnapManifest(manifest.result);\n const { version } = manifest.result;\n\n if (!satisfiesVersionRange(version, versionRange)) {\n throw new Error(\n `Version mismatch. Manifest for \"${snapId}\" specifies version \"${version}\" which doesn't satisfy requested version range \"${versionRange}\"`,\n );\n }\n\n const sourceCode = files\n .find(\n (file) => file.path === manifest.result.source.location.npm.filePath,\n )\n ?.toString();\n const svgIcon = files.find(\n (file) =>\n manifest.result.source.location.npm.iconPath !== undefined &&\n file.path === manifest.result.source.location.npm.iconPath,\n );\n assert(sourceCode !== undefined);\n if (typeof sourceCode !== 'string' || sourceCode.length === 0) {\n throw new Error(`Invalid source code for snap \"${snapId}\".`);\n }\n\n const snapsState = this.state.snaps;\n\n const existingSnap = snapsState[snapId];\n\n const previousVersionHistory = existingSnap?.versionHistory ?? [];\n const versionHistory = [\n ...previousVersionHistory,\n {\n version,\n date: Date.now(),\n origin,\n },\n ];\n\n const snap: Snap = {\n // Restore relevant snap state if it exists\n ...existingSnap,\n\n // Note that the snap will be unblocked and enabled, regardless of its\n // previous state.\n blocked: false,\n enabled: true,\n\n // So we can easily correlate the snap with its permission\n permissionName: getSnapPermissionName(snapId),\n\n id: snapId,\n initialPermissions: manifest.result.initialPermissions,\n manifest: manifest.result,\n status: this.#statusMachine.config.initial as StatusStates['value'],\n version,\n versionHistory,\n };\n // If the snap was blocked, it isn't any longer\n delete snap.blockInformation;\n\n // store the snap back in state\n const { inversePatches } = this.update((state: any) => {\n state.snaps[snapId] = snap;\n });\n\n // checking for isUpdate here as this function is also used in\n // the install flow, we do not care to create snapshots for installs\n if (isUpdate) {\n const rollbackSnapshot = this.#getRollbackSnapshot(snapId);\n if (rollbackSnapshot !== undefined) {\n rollbackSnapshot.statePatches = inversePatches;\n }\n }\n\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.sourceCode = sourceCode;\n\n this.messagingSystem.publish(\n `SnapController:snapAdded`,\n snap,\n svgIcon?.toString(),\n );\n return { ...snap, sourceCode };\n }\n\n /**\n * Fetches the manifest and source code of a snap.\n *\n * This function is not hash private yet because of tests.\n *\n * @param snapId - The id of the Snap.\n * @param location - Source from which snap will be fetched.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\n async #fetchSnap(\n snapId: ValidatedSnapId,\n location: SnapLocation,\n ): Promise<FetchSnapResult> {\n try {\n const manifest = await location.manifest();\n const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\n );\n validateSnapShasum(manifest.result, sourceCode.toString());\n const { iconPath } = manifest.result.source.location.npm;\n\n const files = [sourceCode];\n if (iconPath) {\n files.push(await location.fetch(iconPath));\n }\n\n return { manifest, files, location };\n } catch (error) {\n // TODO(ritave): Export `getErrorMessage()` from @metamask/utils and use it here\n // https://github.com/MetaMask/utils/blob/62d022ef83c91fa4d150e51913be4441508a0ab1/src/assert.ts\n const message = error instanceof Error ? error.message : error.toString();\n throw new Error(`Failed to fetch Snap \"${snapId}\": ${message}.`);\n }\n }\n\n /**\n * Map initial permissions as defined in a Snap manifest to something that can\n * be processed by the PermissionsController. Each caveat mapping function\n * should return a valid permission caveat value.\n *\n * This function does not validate the caveat values, since that is done by\n * the PermissionsController itself, upon requesting the permissions.\n *\n * @param initialPermissions - The initial permissions to process.\n * @returns The processed permissions.\n * @private\n */\n #processSnapPermissions(\n initialPermissions: SnapPermissions,\n ): Record<string, Pick<PermissionConstraint, 'caveats'>> {\n return fromEntries(\n Object.entries(initialPermissions).map(([initialPermission, value]) => {\n if (hasProperty(caveatMappers, initialPermission)) {\n return [initialPermission, caveatMappers[initialPermission](value)];\n } else if (hasProperty(endowmentCaveatMappers, initialPermission)) {\n return [\n initialPermission,\n endowmentCaveatMappers[initialPermission](value),\n ];\n }\n\n // If we have no mapping, this may be a non-snap permission, return as-is\n return [\n initialPermission,\n value as Pick<PermissionConstraint, 'caveats'>,\n ];\n }),\n );\n }\n\n /**\n * Initiates a request for the given snap's initial permissions.\n * Must be called in order. See processRequestedSnap.\n *\n * This function is not hash private yet because of tests.\n *\n * @param origin - The origin of the install request.\n * @param snapId - The id of the Snap.\n * @returns The snap's approvedPermissions.\n */\n private async authorize(origin: string, snapId: SnapId): Promise<void> {\n console.info(`Authorizing snap: ${snapId}`);\n const snapsState = this.state.snaps;\n const snap = snapsState[snapId];\n const { initialPermissions } = snap;\n\n try {\n const processedPermissions =\n this.#processSnapPermissions(initialPermissions);\n const id = nanoid();\n const { permissions: approvedPermissions, ...requestData } =\n (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n origin,\n id,\n type: SNAP_APPROVAL_INSTALL,\n requestData: {\n // Mirror previous installation metadata\n metadata: { id, origin: snapId, dappOrigin: origin },\n permissions: processedPermissions,\n snapId,\n },\n },\n true,\n )) as PermissionsRequest;\n\n if (isNonEmptyArray(Object.keys(approvedPermissions))) {\n this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions,\n subject: { origin: snapId },\n requestData,\n });\n }\n } finally {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.installPromise = null;\n }\n }\n\n destroy() {\n super.destroy();\n\n if (this.#timeoutForLastRequestStatus) {\n clearTimeout(this.#timeoutForLastRequestStatus);\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'ExecutionService:unhandledError',\n this._onUnhandledSnapError,\n );\n\n this.messagingSystem.unsubscribe(\n 'ExecutionService:outboundRequest',\n this._onOutboundRequest,\n );\n\n this.messagingSystem.unsubscribe(\n 'ExecutionService:outboundResponse',\n this._onOutboundResponse,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n }\n\n /**\n * Passes a JSON-RPC request object to the RPC handler function of a snap.\n *\n * @param options - A bag of options.\n * @param options.snapId - The ID of the recipient snap.\n * @param options.origin - The origin of the RPC request.\n * @param options.handler - The handler to trigger on the snap for the request.\n * @param options.request - The JSON-RPC request object.\n * @returns The result of the JSON-RPC request.\n */\n async handleRequest({\n snapId,\n origin,\n handler: handlerType,\n request,\n }: SnapRpcHookArgs & { snapId: SnapId }): Promise<unknown> {\n const permissionName = handlerEndowments[handlerType];\n const hasPermission = this.messagingSystem.call(\n 'PermissionController:hasPermission',\n snapId,\n permissionName,\n );\n\n if (!hasPermission) {\n throw new Error(\n `Snap \"${snapId}\" is not permitted to use \"${permissionName}\".`,\n );\n }\n\n if (permissionName === SnapEndowments.Rpc) {\n const subject = this.messagingSystem.call(\n 'SubjectMetadataController:getSubjectMetadata',\n origin,\n );\n const isSnap = subject?.subjectType === SubjectType.Snap;\n\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const rpcPermission = permissions?.[SnapEndowments.Rpc];\n assert(rpcPermission);\n\n const origins = getRpcCaveatOrigins(rpcPermission);\n assert(origins);\n\n if ((isSnap && !origins.snaps) || (!isSnap && !origins.dapps)) {\n throw new Error(\n `Snap \"${snapId}\" is not permitted to handle JSON-RPC requests from \"${origin}\".`,\n );\n }\n }\n\n const handler = await this.#getRpcRequestHandler(snapId);\n if (!handler) {\n throw new Error(\n `Snap RPC message handler not found for snap \"${snapId}\".`,\n );\n }\n\n return handler({ origin, handler: handlerType, request });\n }\n\n /**\n * Gets the RPC message handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC handler for the given snap.\n */\n #getRpcRequestHandler(snapId: SnapId): SnapRpcHook {\n const runtime = this.#getRuntimeExpect(snapId);\n const existingHandler = runtime.rpcHandler;\n if (existingHandler) {\n return existingHandler;\n }\n\n const requestQueue = new RequestQueue(5);\n // We need to set up this promise map to map snapIds to their respective startPromises,\n // because otherwise we would lose context on the correct startPromise.\n const startPromises = new Map<string, Promise<void>>();\n\n const rpcHandler = async ({\n origin,\n handler: handlerType,\n request,\n }: SnapRpcHookArgs) => {\n if (this.state.snaps[snapId].enabled === false) {\n throw new Error(`Snap \"${snapId}\" is disabled.`);\n }\n\n if (this.state.snaps[snapId].status === SnapStatus.Installing) {\n throw new Error(\n `Snap \"${snapId}\" is currently being installed. Please try again later.`,\n );\n }\n\n if (!this.isRunning(snapId)) {\n let localStartPromise = startPromises.get(snapId);\n if (!localStartPromise) {\n localStartPromise = this.startSnap(snapId);\n startPromises.set(snapId, localStartPromise);\n } else if (requestQueue.get(origin) >= requestQueue.maxQueueSize) {\n throw new Error(\n 'Exceeds maximum number of requests waiting to be resolved, please try again.',\n );\n }\n\n requestQueue.increment(origin);\n try {\n await localStartPromise;\n } finally {\n requestQueue.decrement(origin);\n // Only delete startPromise for a snap if its value hasn't changed\n if (startPromises.get(snapId) === localStartPromise) {\n startPromises.delete(snapId);\n }\n }\n }\n\n let _request = request;\n if (!hasProperty(request, 'jsonrpc')) {\n _request = { ...request, jsonrpc: '2.0' };\n } else if (request.jsonrpc !== '2.0') {\n throw ethErrors.rpc.invalidRequest({\n message: 'Invalid \"jsonrpc\" property. Must be \"2.0\" if provided.',\n data: request.jsonrpc,\n });\n }\n\n const timer = new Timer(this.maxRequestTime);\n this.#recordSnapRpcRequestStart(snapId, request.id, timer);\n\n const handleRpcRequestPromise = this.messagingSystem.call(\n 'ExecutionService:handleRpcRequest',\n snapId,\n { origin, handler: handlerType, request: _request },\n );\n\n // This will either get the result or reject due to the timeout.\n try {\n const result = await this.#executeWithTimeout(\n snapId,\n handleRpcRequestPromise,\n timer,\n );\n this.#recordSnapRpcRequestFinish(snapId, request.id);\n return result;\n } catch (error) {\n await this.stopSnap(snapId, SnapStatusEvents.Crash);\n throw error;\n }\n };\n\n runtime.rpcHandler = rpcHandler;\n return rpcHandler;\n }\n\n /**\n * Awaits the specified promise and rejects if the promise doesn't resolve\n * before the timeout.\n *\n * @param snapId - The snap id.\n * @param promise - The promise to await.\n * @param timer - An optional timer object to control the timeout.\n * @returns The result of the promise or rejects if the promise times out.\n * @template PromiseValue - The value of the Promise.\n */\n async #executeWithTimeout<PromiseValue>(\n snapId: SnapId,\n promise: Promise<PromiseValue>,\n timer?: Timer,\n ): Promise<PromiseValue> {\n const isLongRunning = this.messagingSystem.call(\n 'PermissionController:hasPermission',\n snapId,\n SnapEndowments.LongRunning,\n );\n\n // Long running snaps have timeouts disabled\n if (isLongRunning) {\n return promise;\n }\n\n const result = await withTimeout(promise, timer ?? this.maxRequestTime);\n if (result === hasTimedOut) {\n throw new Error('The request timed out.');\n }\n return result;\n }\n\n #recordSnapRpcRequestStart(snapId: SnapId, requestId: unknown, timer: Timer) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.pendingInboundRequests.push({ requestId, timer });\n runtime.lastRequest = null;\n }\n\n #recordSnapRpcRequestFinish(snapId: SnapId, requestId: unknown) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.pendingInboundRequests = runtime.pendingInboundRequests.filter(\n (request) => request.requestId !== requestId,\n );\n\n if (runtime.pendingInboundRequests.length === 0) {\n runtime.lastRequest = Date.now();\n }\n }\n\n /**\n * Retrieves the rollback snapshot of a snap.\n *\n * @param snapId - The snap id.\n * @returns A `RollbackSnapshot` or `undefined` if one doesn't exist.\n */\n #getRollbackSnapshot(snapId: SnapId): RollbackSnapshot | undefined {\n return this.#rollbackSnapshots.get(snapId);\n }\n\n /**\n * Creates a `RollbackSnapshot` that is used to help ensure\n * atomicity in multiple snap updates.\n *\n * @param snapId - The snap id.\n * @throws {@link Error}. If the snap exists before creation or if creation fails.\n * @returns A `RollbackSnapshot`.\n */\n #createRollbackSnapshot(snapId: SnapId): RollbackSnapshot {\n assert(\n this.#rollbackSnapshots.get(snapId) === undefined,\n new Error(`Snap \"${snapId}\" rollback snapshot already exists.`),\n );\n\n this.#rollbackSnapshots.set(snapId, {\n statePatches: [],\n sourceCode: '',\n permissions: { revoked: null, granted: [], requestData: null },\n newVersion: '',\n });\n\n const newRollbackSnapshot = this.#rollbackSnapshots.get(snapId);\n\n assert(\n newRollbackSnapshot !== undefined,\n new Error(`Snapshot creation failed for ${snapId}.`),\n );\n return newRollbackSnapshot;\n }\n\n /**\n * Rolls back a snap to its previous state, permissions\n * and source code based on the `RollbackSnapshot` that\n * is captured during the update process. After rolling back,\n * the function also emits an event indicating that the\n * snap has been rolled back and it clears the snapshot\n * for that snap.\n *\n * @param snapId - The snap id.\n * @throws {@link Error}. If a snapshot does not exist.\n */\n async #rollbackSnap(snapId: SnapId) {\n const rollbackSnapshot = this.#getRollbackSnapshot(snapId);\n if (!rollbackSnapshot) {\n throw new Error('A snapshot does not exist for this snap.');\n }\n\n await this.stopSnap(snapId, SnapStatusEvents.Stop);\n\n const { statePatches, sourceCode, permissions } = rollbackSnapshot;\n\n if (statePatches?.length) {\n this.applyPatches(statePatches);\n }\n\n if (sourceCode) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.sourceCode = sourceCode;\n }\n\n if (permissions.revoked && Object.keys(permissions.revoked).length) {\n this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions: permissions.revoked as RequestedPermissions,\n subject: { origin: snapId },\n requestData: permissions.requestData as Record<string, unknown>,\n });\n }\n\n if (permissions.granted?.length) {\n this.messagingSystem.call('PermissionController:revokePermissions', {\n [snapId]: permissions.granted as NonEmptyArray<string>,\n });\n }\n\n const truncatedSnap = this.getTruncatedExpect(snapId);\n\n this.messagingSystem.publish(\n 'SnapController:snapRolledback',\n truncatedSnap,\n rollbackSnapshot.newVersion,\n );\n\n this.#rollbackSnapshots.delete(snapId);\n }\n\n /**\n * Iterates through an array of snap ids\n * and calls `rollbackSnap` on them.\n *\n * @param snapIds - An array of snap ids.\n */\n async #rollbackSnaps(snapIds: SnapId[]) {\n for (const snapId of snapIds) {\n await this.#rollbackSnap(snapId);\n }\n }\n\n #getRuntime(snapId: SnapId): SnapRuntimeData | undefined {\n return this.snapsRuntimeData.get(snapId);\n }\n\n #getRuntimeExpect(snapId: SnapId): SnapRuntimeData {\n const runtime = this.#getRuntime(snapId);\n assert(\n runtime !== undefined,\n new Error(`Snap \"${snapId}\" runtime data not found`),\n );\n return runtime;\n }\n\n #setupRuntime(\n snapId: SnapId,\n data: { sourceCode: string | null; state: string | null },\n ) {\n if (this.snapsRuntimeData.has(snapId)) {\n return;\n }\n\n const snap = this.get(snapId);\n const interpreter = interpret(this.#statusMachine);\n interpreter.start({\n context: { snapId },\n value:\n snap?.status ??\n (this.#statusMachine.config.initial as StatusStates['value']),\n });\n\n forceStrict(interpreter);\n\n this.snapsRuntimeData.set(snapId, {\n lastRequest: null,\n rpcHandler: null,\n installPromise: null,\n activeReferences: 0,\n pendingInboundRequests: [],\n pendingOutboundRequests: 0,\n interpreter,\n ...data,\n });\n }\n\n #calculatePermissionsChange(\n snapId: SnapId,\n desiredPermissionsSet: RequestedSnapPermissions,\n ): {\n newPermissions: RequestedSnapPermissions;\n unusedPermissions: SubjectPermissions<\n ValidPermission<string, Caveat<string, any>>\n >;\n approvedPermissions: SubjectPermissions<\n ValidPermission<string, Caveat<string, any>>\n >;\n } {\n const oldPermissions =\n this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n ) ?? {};\n\n const newPermissions = setDiff(desiredPermissionsSet, oldPermissions);\n // TODO(ritave): The assumption that these are unused only holds so long as we do not\n // permit dynamic permission requests.\n const unusedPermissions = setDiff(oldPermissions, desiredPermissionsSet);\n\n // It's a Set Intersection of oldPermissions and desiredPermissionsSet\n // oldPermissions ∖ (oldPermissions ∖ desiredPermissionsSet) ⟺ oldPermissions ∩ desiredPermissionsSet\n const approvedPermissions = setDiff(oldPermissions, unusedPermissions);\n\n return { newPermissions, unusedPermissions, approvedPermissions };\n }\n\n /**\n * Checks if a snap will pass version validation checks\n * with the new version range that is requested. The first\n * check that is done is to check if the existing snap version\n * falls inside the requested range. If it does, we want to return\n * false because we do not care to create a rollback snapshot in\n * that scenario. The second check is to ensure that the current\n * snap version is not greater than all possible versions in\n * the requested version range. If it is, then we also want\n * to return false in that scenario.\n *\n * @param snapId - The snap id.\n * @param newVersionRange - The new version range being requsted.\n * @returns `true` if validation checks pass and `false` if they do not.\n */\n #isValidUpdate(snapId: SnapId, newVersionRange: SemVerRange): boolean {\n const existingSnap = this.getExpect(snapId);\n\n if (satisfiesVersionRange(existingSnap.version, newVersionRange)) {\n return false;\n }\n\n if (gtRange(existingSnap.version, newVersionRange)) {\n return false;\n }\n\n return true;\n }\n}\n"]}
1
+ {"version":3,"file":"SnapController.js","sourceRoot":"","sources":["../../src/snaps/SnapController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;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CAAC,CAAC;IAEvE,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,CAAC;AACpE,CAAC,yEAiBc,MAAc,EAAE,eAA4B;IACzD,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAE5C,IAAI,IAAA,mCAAqB,EAAC,YAAY,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE;QAChE,OAAO,KAAK,CAAC;KACd;IAED,IAAI,IAAA,qBAAO,EAAC,YAAY,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE;QAClD,OAAO,KAAK,CAAC;KACd;IAED,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { AddApprovalRequest } from '@metamask/approval-controller';\nimport {\n BaseControllerV2 as BaseController,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n Caveat,\n GetEndowments,\n GetPermissions,\n GrantPermissions,\n HasPermission,\n HasPermissions,\n PermissionConstraint,\n PermissionsRequest,\n RequestedPermissions,\n RevokeAllPermissions,\n RevokePermissionForAllSubjects,\n RevokePermissions,\n SubjectPermissions,\n ValidPermission,\n} from '@metamask/permission-controller';\nimport { caveatMappers } from '@metamask/rpc-methods';\nimport {\n assertIsSnapManifest,\n BlockedSnapInfo,\n DEFAULT_ENDOWMENTS,\n DEFAULT_REQUESTED_SNAP_VERSION,\n fromEntries,\n getSnapPermissionName,\n gtVersion,\n gtRange,\n InstallSnapsResult,\n isValidSemVerRange,\n PersistedSnap,\n ProcessSnapResult,\n RequestedSnapPermissions,\n resolveVersionRange,\n satisfiesVersionRange,\n SemVerRange,\n Snap,\n SnapId,\n SnapManifest,\n SnapPermissions,\n SnapRpcHook,\n SnapRpcHookArgs,\n SnapStatus,\n SnapStatusEvents,\n SNAP_PREFIX,\n SNAP_PREFIX_REGEX,\n StatusContext,\n StatusEvents,\n StatusStates,\n TruncatedSnap,\n TruncatedSnapFields,\n ValidatedSnapId,\n validateSnapId,\n validateSnapShasum,\n VirtualFile,\n} from '@metamask/snaps-utils';\nimport {\n GetSubjectMetadata,\n SubjectType,\n} from '@metamask/subject-metadata-controller';\nimport {\n assert,\n Duration,\n hasProperty,\n inMilliseconds,\n isNonEmptyArray,\n Json,\n NonEmptyArray,\n timeSince,\n} from '@metamask/utils';\nimport { createMachine, interpret, StateMachine } from '@xstate/fsm';\nimport { ethErrors } from 'eth-rpc-errors';\nimport type { Patch } from 'immer';\nimport { nanoid } from 'nanoid';\n\nimport { forceStrict, validateMachine } from '../fsm';\nimport {\n ExecuteSnapAction,\n ExecutionServiceEvents,\n HandleRpcRequestAction,\n SnapErrorJson,\n TerminateAllSnapsAction,\n TerminateSnapAction,\n} from '../services';\nimport { hasTimedOut, setDiff, withTimeout } from '../utils';\nimport {\n endowmentCaveatMappers,\n handlerEndowments,\n SnapEndowments,\n} from './endowments';\nimport { getRpcCaveatOrigins } from './endowments/rpc';\nimport { detectSnapLocation, SnapLocation } from './location';\nimport { RequestQueue } from './RequestQueue';\nimport { Timer } from './Timer';\n\nexport const controllerName = 'SnapController';\n\n// TODO: Figure out how to name these\nexport const SNAP_APPROVAL_INSTALL = 'wallet_installSnap';\nexport const SNAP_APPROVAL_UPDATE = 'wallet_updateSnap';\n\nconst TRUNCATED_SNAP_PROPERTIES = new Set<TruncatedSnapFields>([\n 'initialPermissions',\n 'id',\n 'permissionName',\n 'version',\n 'enabled',\n 'blocked',\n]);\n\nexport type PendingRequest = {\n requestId: unknown;\n timer: Timer;\n};\n\n/**\n * A wrapper type for any data stored during runtime of Snaps.\n * It is not persisted in state as it contains non-serializable data and is only relevant for the\n * current session.\n */\nexport interface SnapRuntimeData {\n /**\n * A promise that resolves when the Snap has finished installing\n */\n installPromise: null | Promise<PersistedSnap>;\n\n /**\n * A Unix timestamp for the last time the Snap received an RPC request\n */\n lastRequest: null | number;\n\n /**\n * The current number of active references where this Snap is being used\n */\n activeReferences: number;\n\n /**\n * The current pending inbound requests, meaning requests that are processed by snaps.\n */\n pendingInboundRequests: PendingRequest[];\n\n /**\n * The current pending outbound requests, meaning requests made from snaps towards the MetaMask\n * extension.\n */\n pendingOutboundRequests: number;\n\n /**\n * RPC handler designated for the Snap\n */\n rpcHandler: null | SnapRpcHook;\n\n /**\n * The finite state machine interpreter for possible states that the Snap can be in such as\n * stopped, running, blocked\n *\n * @see {@link SnapController:constructor}\n */\n interpreter: StateMachine.Service<StatusContext, StatusEvents, StatusStates>;\n\n /**\n * The snap source code\n */\n sourceCode: null | string;\n\n /**\n * The snap state (encrypted)\n */\n state: null | string;\n}\n\nexport type SnapError = {\n message: string;\n code: number;\n data?: Json;\n};\n\n/**\n * The return type of {@link SnapController.#fetchSnap} and its sibling methods.\n */\ntype FetchSnapResult = {\n /**\n * The manifest of the fetched Snap.\n */\n manifest: VirtualFile<SnapManifest>;\n\n /**\n * Auxillary files references in manifest.\n */\n files: VirtualFile[];\n\n /**\n * Location that was used to fetch the snap.\n *\n * Helpful if you want to pass it forward since files will be still cached.\n */\n location: SnapLocation;\n};\n\n// Types that probably should be defined elsewhere in prod\ntype CloseAllConnectionsFunction = (origin: string) => void;\ntype StoredSnaps = Record<SnapId, Snap>;\n\nexport type SnapControllerState = {\n snaps: StoredSnaps;\n // This type needs to be defined but is always empty in practice.\n // eslint-disable-next-line @typescript-eslint/ban-types\n snapStates: {};\n snapErrors: {\n [internalID: string]: SnapError & { internalID: string };\n };\n};\n\nexport type PersistedSnapControllerState = SnapControllerState & {\n snaps: Record<SnapId, PersistedSnap>;\n snapStates: Record<SnapId, string>;\n};\n\ntype RollbackSnapshot = {\n statePatches: Patch[];\n sourceCode: string | null;\n permissions: {\n revoked: unknown;\n granted: unknown[];\n requestData: unknown;\n };\n newVersion: string;\n};\n\n// Controller Messenger Actions\n\n/**\n * Gets the specified Snap from state.\n */\nexport type GetSnap = {\n type: `${typeof controllerName}:get`;\n handler: SnapController['get'];\n};\n\n/**\n * Handles sending an inbound request to a snap and returns its result.\n */\nexport type HandleSnapRequest = {\n type: `${typeof controllerName}:handleRequest`;\n handler: SnapController['handleRequest'];\n};\n\n/**\n * Gets the specified Snap's persisted state.\n */\nexport type GetSnapState = {\n type: `${typeof controllerName}:getSnapState`;\n handler: SnapController['getSnapState'];\n};\n\n/**\n * Checks if the specified snap exists in state.\n */\nexport type HasSnap = {\n type: `${typeof controllerName}:has`;\n handler: SnapController['has'];\n};\n\n/**\n * Updates the specified Snap's persisted state.\n */\nexport type UpdateSnapState = {\n type: `${typeof controllerName}:updateSnapState`;\n handler: SnapController['updateSnapState'];\n};\n\n/**\n * Clears the specified Snap's persisted state.\n */\nexport type ClearSnapState = {\n type: `${typeof controllerName}:clearSnapState`;\n handler: SnapController['clearSnapState'];\n};\n\n/**\n * Checks all installed snaps against the blocklist.\n */\nexport type UpdateBlockedSnaps = {\n type: `${typeof controllerName}:updateBlockedSnaps`;\n handler: SnapController['updateBlockedSnaps'];\n};\n\nexport type EnableSnap = {\n type: `${typeof controllerName}:enable`;\n handler: SnapController['enableSnap'];\n};\n\nexport type DisableSnap = {\n type: `${typeof controllerName}:disable`;\n handler: SnapController['disableSnap'];\n};\n\nexport type RemoveSnap = {\n type: `${typeof controllerName}:remove`;\n handler: SnapController['removeSnap'];\n};\n\nexport type GetPermittedSnaps = {\n type: `${typeof controllerName}:getPermitted`;\n handler: SnapController['getPermittedSnaps'];\n};\n\nexport type GetAllSnaps = {\n type: `${typeof controllerName}:getAll`;\n handler: SnapController['getAllSnaps'];\n};\n\nexport type IncrementActiveReferences = {\n type: `${typeof controllerName}:incrementActiveReferences`;\n handler: SnapController['incrementActiveReferences'];\n};\n\nexport type DecrementActiveReferences = {\n type: `${typeof controllerName}:decrementActiveReferences`;\n handler: SnapController['decrementActiveReferences'];\n};\n\nexport type InstallSnaps = {\n type: `${typeof controllerName}:install`;\n handler: SnapController['installSnaps'];\n};\n\nexport type RemoveSnapError = {\n type: `${typeof controllerName}:removeSnapError`;\n handler: SnapController['removeSnapError'];\n};\n\nexport type SnapControllerActions =\n | ClearSnapState\n | GetSnap\n | GetSnapState\n | HandleSnapRequest\n | HasSnap\n | UpdateBlockedSnaps\n | UpdateSnapState\n | EnableSnap\n | DisableSnap\n | RemoveSnap\n | GetPermittedSnaps\n | InstallSnaps\n | RemoveSnapError\n | GetAllSnaps\n | IncrementActiveReferences\n | DecrementActiveReferences;\n\n// Controller Messenger Events\n\nexport type SnapStateChange = {\n type: `${typeof controllerName}:stateChange`;\n payload: [SnapControllerState, Patch[]];\n};\n\n/**\n * Emitted when a Snap has been added to state during installation.\n */\nexport type SnapAdded = {\n type: `${typeof controllerName}:snapAdded`;\n payload: [snap: Snap, svgIcon: string | undefined];\n};\n\n/**\n * Emitted when an installed snap has been blocked.\n */\nexport type SnapBlocked = {\n type: `${typeof controllerName}:snapBlocked`;\n payload: [snapId: string, blockedSnapInfo: BlockedSnapInfo];\n};\n\n/**\n * Emitted when a snap has been started after being added and authorized during\n * installation.\n */\nexport type SnapInstalled = {\n type: `${typeof controllerName}:snapInstalled`;\n payload: [snap: TruncatedSnap];\n};\n\n/**\n * Emitted when a snap is removed.\n */\nexport type SnapRemoved = {\n type: `${typeof controllerName}:snapRemoved`;\n payload: [snap: TruncatedSnap];\n};\n\n/**\n * Emitted when an installed snap has been unblocked.\n */\nexport type SnapUnblocked = {\n type: `${typeof controllerName}:snapUnblocked`;\n payload: [snapId: string];\n};\n\n/**\n * Emitted when a snap is updated.\n */\nexport type SnapUpdated = {\n type: `${typeof controllerName}:snapUpdated`;\n payload: [snap: TruncatedSnap, oldVersion: string];\n};\n\n/**\n * Emitted when a snap is rolled back.\n */\nexport type SnapRolledback = {\n type: `${typeof controllerName}:snapRolledback`;\n payload: [snap: TruncatedSnap, failedVersion: string];\n};\n/**\n * Emitted when a Snap is terminated. This is different from the snap being\n * stopped as it can also be triggered when a snap fails initialization.\n */\nexport type SnapTerminated = {\n type: `${typeof controllerName}:snapTerminated`;\n payload: [snap: TruncatedSnap];\n};\n\nexport type SnapControllerEvents =\n | SnapAdded\n | SnapBlocked\n | SnapInstalled\n | SnapRemoved\n | SnapStateChange\n | SnapUnblocked\n | SnapUpdated\n | SnapRolledback\n | SnapTerminated;\n\nexport type AllowedActions =\n | GetEndowments\n | GetPermissions\n | GetSubjectMetadata\n | HasPermission\n | HasPermissions\n | RevokePermissions\n | RevokeAllPermissions\n | RevokePermissionForAllSubjects\n | GrantPermissions\n | AddApprovalRequest\n | HandleRpcRequestAction\n | ExecuteSnapAction\n | TerminateAllSnapsAction\n | TerminateSnapAction;\n\nexport type AllowedEvents = ExecutionServiceEvents;\n\ntype SnapControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SnapControllerActions | AllowedActions,\n SnapControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\ntype FeatureFlags = {\n /**\n * We still need to implement new UI approval page in metamask-extension before we can allow\n * DApps to update Snaps. After it's added, this flag can be removed.\n *\n * @see {SNAP_APPROVAL_UPDATE}\n * @see {SnapController.processRequestedSnap}\n */\n dappsCanUpdateSnaps?: true;\n};\n\ntype SemVerVersion = string;\ntype SnapInfo = { version: SemVerVersion; shasum: string };\nexport type CheckSnapBlockListArg = Record<SnapId, SnapInfo>;\n\nexport type CheckSnapBlockListResult = Record<\n SnapId,\n | {\n blocked: true;\n reason?: string;\n infoUrl?: string;\n }\n | { blocked: false }\n>;\n\n/**\n * Checks whether a version of a snap is blocked.\n */\nexport type CheckSnapBlockList = (\n snapsToCheck: CheckSnapBlockListArg,\n) => Promise<CheckSnapBlockListResult>;\n\ntype SnapControllerArgs = {\n /**\n * A teardown function that allows the host to clean up its instrumentation\n * for a running snap.\n */\n closeAllConnections: CloseAllConnectionsFunction;\n\n /**\n * The names of endowment permissions whose values are the names of JavaScript\n * APIs that will be added to the snap execution environment at runtime.\n */\n environmentEndowmentPermissions: string[];\n\n /**\n * The function that will be used by the controller fo make network requests.\n * Should be compatible with {@link fetch}.\n */\n fetchFunction?: typeof fetch;\n\n /**\n * Flags that enable or disable features in the controller.\n * See {@link FeatureFlags}.\n */\n featureFlags: FeatureFlags;\n\n /**\n * How frequently to check whether a snap is idle.\n */\n idleTimeCheckInterval?: number;\n\n /**\n * A function that checks whether the specified snap and version is blocked.\n */\n checkBlockList: CheckSnapBlockList;\n\n /**\n * The maximum amount of time that a snap may be idle.\n */\n maxIdleTime?: number;\n\n /**\n * The controller messenger.\n */\n messenger: SnapControllerMessenger;\n\n /**\n * The maximum amount of time a snap may take to process an RPC request,\n * unless it is permitted to take longer.\n */\n maxRequestTime?: number;\n\n /**\n * The npm registry URL that will be used to fetch published snaps.\n */\n npmRegistryUrl?: string;\n\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: PersistedSnapControllerState;\n\n /**\n * A function that takes Snap Id and converts it into a class that fetches files.\n *\n * Used for test overrides.\n */\n detectSnapLocation?: typeof detectSnapLocation;\n};\ntype AddSnapArgs = {\n id: SnapId;\n origin: string;\n location: SnapLocation;\n};\n\n// When we set a snap, we need all required properties to be present and\n// validated.\ntype SetSnapArgs = Omit<AddSnapArgs, 'id' | 'location'> & {\n id: ValidatedSnapId;\n manifest: VirtualFile<SnapManifest>;\n files: VirtualFile[];\n /**\n * @default '*'\n */\n // TODO(ritave): Used only for validation in #set, should be moved elsewhere.\n versionRange?: SemVerRange;\n isUpdate?: boolean;\n};\n\nconst defaultState: SnapControllerState = {\n snapErrors: {},\n snaps: {},\n snapStates: {},\n};\n\n/**\n * Truncates the properties of a snap to only ones that are easily serializable.\n *\n * @param snap - The snap to truncate.\n * @returns Object with serializable snap properties.\n */\nfunction truncateSnap(snap: Snap): TruncatedSnap {\n const truncatedSnap = Object.keys(snap).reduce<Partial<TruncatedSnap>>(\n (serialized, key) => {\n if (TRUNCATED_SNAP_PROPERTIES.has(key as any)) {\n serialized[key as keyof TruncatedSnap] = snap[\n key as keyof TruncatedSnap\n ] as any;\n }\n\n return serialized;\n },\n {},\n );\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return truncatedSnap as TruncatedSnap;\n}\n\nconst name = 'SnapController';\n\n/*\n * A snap is initialized in three phases:\n * - Add: Loads the snap from a remote source and parses it.\n * - Authorize: Requests the snap's required permissions from the user.\n * - Start: Initializes the snap in its SES realm with the authorized permissions.\n */\n\nexport class SnapController extends BaseController<\n string,\n SnapControllerState,\n SnapControllerMessenger\n> {\n #closeAllConnections: CloseAllConnectionsFunction;\n\n #environmentEndowmentPermissions: string[];\n\n #featureFlags: FeatureFlags;\n\n #fetchFunction: typeof fetch;\n\n #idleTimeCheckInterval: number;\n\n #checkSnapBlockList: CheckSnapBlockList;\n\n #maxIdleTime: number;\n\n // This property cannot be hash private yet because of tests.\n private readonly maxRequestTime: number;\n\n #detectSnapLocation: typeof detectSnapLocation;\n\n // This property cannot be hash private yet because of tests.\n private readonly snapsRuntimeData: Map<SnapId, SnapRuntimeData>;\n\n #rollbackSnapshots: Map<SnapId, RollbackSnapshot>;\n\n #timeoutForLastRequestStatus?: number;\n\n #statusMachine!: StateMachine.Machine<\n StatusContext,\n StatusEvents,\n StatusStates\n >;\n\n constructor({\n closeAllConnections,\n messenger,\n state,\n environmentEndowmentPermissions = [],\n idleTimeCheckInterval = inMilliseconds(5, Duration.Second),\n checkBlockList,\n maxIdleTime = inMilliseconds(30, Duration.Second),\n maxRequestTime = inMilliseconds(60, Duration.Second),\n fetchFunction = globalThis.fetch.bind(globalThis),\n featureFlags = {},\n detectSnapLocation: detectSnapLocationFunction = detectSnapLocation,\n }: SnapControllerArgs) {\n super({\n messenger,\n metadata: {\n snapErrors: {\n persist: false,\n anonymous: false,\n },\n snapStates: {\n persist: () => {\n return Object.keys(this.state.snaps).reduce<\n Record<string, string | null>\n >((acc, cur) => {\n acc[cur] = this.#getRuntimeExpect(cur).state;\n return acc;\n }, {});\n },\n anonymous: false,\n },\n snaps: {\n persist: (snaps) => {\n return Object.values(snaps)\n .map((snap) => {\n return {\n ...snap,\n sourceCode: this.#getRuntimeExpect(snap.id).sourceCode,\n // At the time state is rehydrated, no snap will be running.\n status: SnapStatus.Stopped,\n };\n })\n .reduce((memo: Record<string, Snap>, snap) => {\n memo[snap.id] = snap;\n return memo;\n }, {});\n },\n anonymous: false,\n },\n },\n name,\n state: {\n ...defaultState,\n ...{\n ...state,\n snaps: Object.values(state?.snaps ?? {}).reduce(\n (memo: Record<string, Snap>, snap) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { sourceCode, ...rest } = snap;\n memo[snap.id] = rest;\n return memo;\n },\n {},\n ),\n },\n },\n });\n\n this.#closeAllConnections = closeAllConnections;\n this.#environmentEndowmentPermissions = environmentEndowmentPermissions;\n this.#featureFlags = featureFlags;\n this.#fetchFunction = fetchFunction;\n this.#idleTimeCheckInterval = idleTimeCheckInterval;\n this.#checkSnapBlockList = checkBlockList;\n this.#maxIdleTime = maxIdleTime;\n this.maxRequestTime = maxRequestTime;\n this.#detectSnapLocation = detectSnapLocationFunction;\n this._onUnhandledSnapError = this._onUnhandledSnapError.bind(this);\n this._onOutboundRequest = this._onOutboundRequest.bind(this);\n this._onOutboundResponse = this._onOutboundResponse.bind(this);\n this.#rollbackSnapshots = new Map();\n this.snapsRuntimeData = new Map();\n this.#pollForLastRequestStatus();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'ExecutionService:unhandledError',\n this._onUnhandledSnapError,\n );\n\n this.messagingSystem.subscribe(\n 'ExecutionService:outboundRequest',\n this._onOutboundRequest,\n );\n\n this.messagingSystem.subscribe(\n 'ExecutionService:outboundResponse',\n this._onOutboundResponse,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#initializeStateMachine();\n this.#registerMessageHandlers();\n\n Object.values(state?.snaps ?? {}).forEach((snap) =>\n this.#setupRuntime(snap.id, {\n sourceCode: snap.sourceCode,\n state: state?.snapStates?.[snap.id] ?? null,\n }),\n );\n }\n\n /**\n * We track status of a Snap using a finite-state-machine.\n * It keeps track of whether the snap is started / stopped / etc.\n *\n * @see {@link SnapController.transition} for interacting with the machine.\n */\n // We initialize the machine in the instance because the status is currently tightly coupled\n // with the SnapController - the guard checks for enabled status inside the SnapController state.\n // In the future, side-effects could be added to the machine during transitions.\n #initializeStateMachine() {\n const disableGuard = ({ snapId }: StatusContext) => {\n return this.getExpect(snapId).enabled;\n };\n\n const statusConfig: StateMachine.Config<\n StatusContext,\n StatusEvents,\n StatusStates\n > = {\n initial: SnapStatus.Installing,\n states: {\n [SnapStatus.Installing]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n },\n },\n [SnapStatus.Updating]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n },\n },\n [SnapStatus.Running]: {\n on: {\n [SnapStatusEvents.Stop]: SnapStatus.Stopped,\n [SnapStatusEvents.Crash]: SnapStatus.Crashed,\n },\n },\n [SnapStatus.Stopped]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n [SnapStatusEvents.Update]: SnapStatus.Updating,\n },\n },\n [SnapStatus.Crashed]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n },\n },\n },\n };\n this.#statusMachine = createMachine(statusConfig);\n validateMachine(this.#statusMachine);\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:clearSnapState`,\n (...args) => this.clearSnapState(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:get`,\n (...args) => this.get(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getSnapState`,\n async (...args) => this.getSnapState(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:handleRequest`,\n async (...args) => this.handleRequest(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:has`,\n (...args) => this.has(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateBlockedSnaps`,\n async () => this.updateBlockedSnaps(),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateSnapState`,\n async (...args) => this.updateSnapState(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:enable`,\n (...args) => this.enableSnap(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:disable`,\n async (...args) => this.disableSnap(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:remove`,\n async (...args) => this.removeSnap(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getPermitted`,\n (...args) => this.getPermittedSnaps(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:install`,\n async (...args) => this.installSnaps(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:removeSnapError`,\n (...args) => this.removeSnapError(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getAll`,\n (...args) => this.getAllSnaps(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:incrementActiveReferences`,\n (...args) => this.incrementActiveReferences(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:decrementActiveReferences`,\n (...args) => this.decrementActiveReferences(...args),\n );\n }\n\n #pollForLastRequestStatus() {\n this.#timeoutForLastRequestStatus = setTimeout(() => {\n this.#stopSnapsLastRequestPastMax().catch((error) => {\n // TODO: Decide how to handle errors.\n console.error(error);\n });\n\n this.#pollForLastRequestStatus();\n }, this.#idleTimeCheckInterval) as unknown as number;\n }\n\n /**\n * Checks all installed snaps against the block list and\n * blocks/unblocks snaps as appropriate. See {@link SnapController.blockSnap}\n * for more information.\n */\n async updateBlockedSnaps(): Promise<void> {\n const blockedSnaps = await this.#checkSnapBlockList(\n Object.values(this.state.snaps).reduce<CheckSnapBlockListArg>(\n (blockListArg, snap) => {\n blockListArg[snap.id] = {\n version: snap.version,\n shasum: snap.manifest.source.shasum,\n };\n return blockListArg;\n },\n {},\n ),\n );\n\n await Promise.all(\n Object.entries(blockedSnaps).map(\n async ([snapId, { blocked, ...blockData }]) => {\n if (blocked) {\n return this.#blockSnap(snapId, blockData);\n }\n\n return this.#unblockSnap(snapId);\n },\n ),\n );\n }\n\n /**\n * Blocks an installed snap and prevents it from being started again. Emits\n * {@link SnapBlocked}. Does nothing if the snap is not installed.\n *\n * @param snapId - The snap to block.\n * @param blockedSnapInfo - Information detailing why the snap is blocked.\n */\n async #blockSnap(\n snapId: SnapId,\n blockedSnapInfo: BlockedSnapInfo,\n ): Promise<void> {\n if (!this.has(snapId)) {\n return;\n }\n\n try {\n this.update((state: any) => {\n state.snaps[snapId].blocked = true;\n state.snaps[snapId].blockInformation = blockedSnapInfo;\n });\n\n await this.disableSnap(snapId);\n } catch (error) {\n console.error(\n `Encountered error when stopping blocked snap \"${snapId}\".`,\n error,\n );\n }\n\n this.messagingSystem.publish(\n `${controllerName}:snapBlocked`,\n snapId,\n blockedSnapInfo,\n );\n }\n\n /**\n * Unblocks a snap so that it can be enabled and started again. Emits\n * {@link SnapUnblocked}. Does nothing if the snap is not installed or already\n * unblocked.\n *\n * @param snapId - The id of the snap to unblock.\n */\n #unblockSnap(snapId: SnapId) {\n if (!this.has(snapId) || !this.state.snaps[snapId].blocked) {\n return;\n }\n\n this.update((state: any) => {\n state.snaps[snapId].blocked = false;\n delete state.snaps[snapId].blockInformation;\n });\n\n this.messagingSystem.publish(`${controllerName}:snapUnblocked`, snapId);\n }\n\n /**\n * Checks the block list to determine whether a version of a snap is blocked.\n *\n * @param snapId - The snap id to check.\n * @param snapInfo - Snap information containing version and shasum.\n * @returns Whether the version of the snap is blocked or not.\n */\n async isBlocked(\n snapId: ValidatedSnapId,\n snapInfo: SnapInfo,\n ): Promise<boolean> {\n const result = await this.#checkSnapBlockList({\n [snapId]: snapInfo,\n });\n return result[snapId].blocked;\n }\n\n /**\n * Asserts that a version of a snap is not blocked. Succeeds automatically\n * if {@link SnapController._checkSnapBlockList} is undefined.\n *\n * @param snapId - The id of the snap to check.\n * @param snapInfo - Snap information containing version and shasum.\n */\n async #assertIsUnblocked(snapId: ValidatedSnapId, snapInfo: SnapInfo) {\n if (await this.isBlocked(snapId, snapInfo)) {\n throw new Error(\n `Cannot install version \"${snapInfo.version}\" of snap \"${snapId}\": the version is blocked.`,\n );\n }\n }\n\n async #stopSnapsLastRequestPastMax() {\n const entries = [...this.snapsRuntimeData.entries()];\n return Promise.all(\n entries\n .filter(\n ([_snapId, runtime]) =>\n runtime.activeReferences === 0 &&\n runtime.pendingInboundRequests.length === 0 &&\n // lastRequest should always be set here but TypeScript wants this check\n runtime.lastRequest &&\n this.#maxIdleTime &&\n timeSince(runtime.lastRequest) > this.#maxIdleTime,\n )\n .map(async ([snapId]) => this.stopSnap(snapId, SnapStatusEvents.Stop)),\n );\n }\n\n _onUnhandledSnapError(snapId: SnapId, error: SnapErrorJson) {\n this.stopSnap(snapId, SnapStatusEvents.Crash)\n .then(() => this.addSnapError(error))\n .catch((stopSnapError) => {\n // TODO: Decide how to handle errors.\n console.error(stopSnapError);\n });\n }\n\n _onOutboundRequest(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n // Ideally we would only pause the pending request that is making the outbound request\n // but right now we don't have a way to know which request initiated the outbound request\n runtime.pendingInboundRequests\n .filter((pendingRequest) => pendingRequest.timer.status === 'running')\n .forEach((pendingRequest) => pendingRequest.timer.pause());\n runtime.pendingOutboundRequests += 1;\n }\n\n _onOutboundResponse(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.pendingOutboundRequests -= 1;\n if (runtime.pendingOutboundRequests === 0) {\n runtime.pendingInboundRequests\n .filter((pendingRequest) => pendingRequest.timer.status === 'paused')\n .forEach((pendingRequest) => pendingRequest.timer.resume());\n }\n }\n\n /**\n * Transitions between states using `snapStatusStateMachineConfig` as the template to figure out\n * the next state. This transition function uses a very minimal subset of XState conventions:\n * - supports initial state\n * - .on supports raw event target string\n * - .on supports {target, cond} object\n * - the arguments for `cond` is the `SerializedSnap` instead of Xstate convention of `(event,\n * context) => boolean`\n *\n * @param snapId - The id of the snap to transition.\n * @param event - The event enum to use to transition.\n */\n #transition(snapId: SnapId, event: StatusEvents | StatusEvents['type']) {\n const { interpreter } = this.#getRuntimeExpect(snapId);\n interpreter.send(event);\n this.update((state: any) => {\n state.snaps[snapId].status = interpreter.state.value;\n });\n }\n\n /**\n * Starts the given snap. Throws an error if no such snap exists\n * or if it is already running.\n *\n * @param snapId - The id of the Snap to start.\n */\n async startSnap(snapId: SnapId): Promise<void> {\n const runtime = this.#getRuntimeExpect(snapId);\n\n if (this.state.snaps[snapId].enabled === false) {\n throw new Error(`Snap \"${snapId}\" is disabled.`);\n }\n\n assert(runtime.sourceCode);\n\n await this.#startSnap({\n snapId,\n sourceCode: runtime.sourceCode,\n });\n }\n\n /**\n * Enables the given snap. A snap can only be started if it is enabled. A snap\n * can only be enabled if it isn't blocked.\n *\n * @param snapId - The id of the Snap to enable.\n */\n enableSnap(snapId: SnapId): void {\n this.getExpect(snapId);\n\n if (this.state.snaps[snapId].blocked) {\n throw new Error(`Snap \"${snapId}\" is blocked and cannot be enabled.`);\n }\n\n this.update((state: any) => {\n state.snaps[snapId].enabled = true;\n });\n }\n\n /**\n * Disables the given snap. A snap can only be started if it is enabled.\n *\n * @param snapId - The id of the Snap to disable.\n * @returns A promise that resolves once the snap has been disabled.\n */\n async disableSnap(snapId: SnapId): Promise<void> {\n if (!this.has(snapId)) {\n throw new Error(`Snap \"${snapId}\" not found.`);\n }\n\n this.update((state: any) => {\n state.snaps[snapId].enabled = false;\n });\n\n if (this.isRunning(snapId)) {\n return this.stopSnap(snapId, SnapStatusEvents.Stop);\n }\n\n return Promise.resolve();\n }\n\n /**\n * Stops the given snap, removes all hooks, closes all connections, and\n * terminates its worker.\n *\n * @param snapId - The id of the Snap to stop.\n * @param statusEvent - The Snap status event that caused the snap to be\n * stopped.\n */\n public async stopSnap(\n snapId: SnapId,\n statusEvent:\n | SnapStatusEvents.Stop\n | SnapStatusEvents.Crash = SnapStatusEvents.Stop,\n ): Promise<void> {\n const runtime = this.#getRuntime(snapId);\n if (!runtime) {\n throw new Error(`The snap \"${snapId}\" is not running.`);\n }\n\n // Reset request tracking\n runtime.lastRequest = null;\n runtime.pendingInboundRequests = [];\n runtime.pendingOutboundRequests = 0;\n try {\n if (this.isRunning(snapId)) {\n this.#closeAllConnections(snapId);\n await this.#terminateSnap(snapId);\n }\n } finally {\n if (this.isRunning(snapId)) {\n this.#transition(snapId, statusEvent);\n }\n }\n }\n\n /**\n * Terminates the specified snap and emits the `snapTerminated` event.\n *\n * @param snapId - The snap to terminate.\n */\n async #terminateSnap(snapId: SnapId) {\n await this.messagingSystem.call('ExecutionService:terminateSnap', snapId);\n this.messagingSystem.publish(\n 'SnapController:snapTerminated',\n this.getTruncatedExpect(snapId),\n );\n }\n\n /**\n * Returns whether the given snap is running.\n * Throws an error if the snap doesn't exist.\n *\n * @param snapId - The id of the Snap to check.\n * @returns `true` if the snap is running, otherwise `false`.\n */\n isRunning(snapId: SnapId): boolean {\n return this.getExpect(snapId).status === 'running';\n }\n\n /**\n * Returns whether the given snap has been added to state.\n *\n * @param snapId - The id of the Snap to check for.\n * @returns `true` if the snap exists in the controller state, otherwise `false`.\n */\n has(snapId: SnapId): boolean {\n return Boolean(this.get(snapId));\n }\n\n /**\n * Gets the snap with the given id if it exists, including all data.\n * This should not be used if the snap is to be serializable, as e.g.\n * the snap sourceCode may be quite large.\n *\n * @param snapId - The id of the Snap to get.\n * @returns The entire snap object from the controller state.\n */\n get(snapId: SnapId): Snap | undefined {\n return this.state.snaps[snapId];\n }\n\n /**\n * Gets the snap with the given id, throws if doesn't.\n * This should not be used if the snap is to be serializable, as e.g.\n * the snap sourceCode may be quite large.\n *\n * @see {@link SnapController.get}\n * @throws {@link Error}. If the snap doesn't exist\n * @param snapId - The id of the snap to get.\n * @returns The entire snap object.\n */\n getExpect(snapId: SnapId): Snap {\n const snap = this.get(snapId);\n assert(snap !== undefined, new Error(`Snap \"${snapId}\" not found.`));\n return snap;\n }\n\n /**\n * Gets the snap with the given id if it exists, excluding any\n * non-serializable or expensive-to-serialize data.\n *\n * @param snapId - The id of the Snap to get.\n * @returns A truncated version of the snap state, that is less expensive to serialize.\n */\n // TODO(ritave): this.get returns undefined, this.getTruncated returns null\n getTruncated(snapId: SnapId): TruncatedSnap | null {\n const snap = this.get(snapId);\n\n return snap ? truncateSnap(snap) : null;\n }\n\n /**\n * Gets the snap with the given id, throw if it doesn't exist.\n *\n * @throws {@link Error}. If snap doesn't exist\n * @param snapId - The id of the snap to get.\n * @returns A truncated version of the snap state, that is less expensive to serialize.\n */\n getTruncatedExpect(snapId: SnapId): TruncatedSnap {\n return truncateSnap(this.getExpect(snapId));\n }\n\n /**\n * Updates the own state of the snap with the given id.\n * This is distinct from the state MetaMask uses to manage snaps.\n *\n * @param snapId - The id of the Snap whose state should be updated.\n * @param newSnapState - The new state of the snap.\n */\n async updateSnapState(snapId: SnapId, newSnapState: string): Promise<void> {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.state = newSnapState;\n }\n\n /**\n * Clears the state of the snap with the given id.\n * This is distinct from the state MetaMask uses to manage snaps.\n *\n * @param snapId - The id of the Snap whose state should be cleared.\n */\n clearSnapState(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.state = null;\n }\n\n /**\n * Adds error from a snap to the SnapController state.\n *\n * @param snapError - The error to store on the SnapController.\n */\n addSnapError(snapError: SnapError): void {\n this.update((state: any) => {\n const id = nanoid();\n state.snapErrors[id] = {\n ...snapError,\n internalID: id,\n };\n });\n }\n\n /**\n * Removes an error by internalID from the SnapControllers state.\n *\n * @param internalID - The internal error ID to remove on the SnapController.\n */\n removeSnapError(internalID: string) {\n this.update((state: any) => {\n delete state.snapErrors[internalID];\n });\n }\n\n /**\n * Clears all errors from the SnapControllers state.\n */\n clearSnapErrors() {\n this.update((state: any) => {\n state.snapErrors = {};\n });\n }\n\n /**\n * Gets the own state of the snap with the given id.\n * This is distinct from the state MetaMask uses to manage snaps.\n *\n * @param snapId - The id of the Snap whose state to get.\n * @returns A promise that resolves with the decrypted snap state or null if no state exists.\n * @throws If the snap state decryption fails.\n */\n async getSnapState(snapId: SnapId): Promise<Json> {\n const { state } = this.#getRuntimeExpect(snapId);\n return state ?? null;\n }\n\n /**\n * Completely clear the controller's state: delete all associated data,\n * handlers, event listeners, and permissions; tear down all snap providers.\n */\n async clearState() {\n const snapIds = Object.keys(this.state.snaps);\n snapIds.forEach((snapId) => {\n this.#closeAllConnections(snapId);\n });\n\n await this.messagingSystem.call('ExecutionService:terminateAllSnaps');\n snapIds.forEach((snapId) => this.revokeAllSnapPermissions(snapId));\n\n this.update((state: any) => {\n state.snaps = {};\n state.snapStates = {};\n });\n }\n\n /**\n * Removes the given snap from state, and clears all associated handlers\n * and listeners.\n *\n * @param snapId - The id of the Snap.\n * @returns A promise that resolves once the snap has been removed.\n */\n async removeSnap(snapId: SnapId): Promise<void> {\n return this.removeSnaps([snapId]);\n }\n\n /**\n * Stops the given snaps, removes them from state, and clears all associated\n * permissions, handlers, and listeners.\n *\n * @param snapIds - The ids of the Snaps.\n */\n async removeSnaps(snapIds: string[]): Promise<void> {\n if (!Array.isArray(snapIds)) {\n throw new Error('Expected array of snap ids.');\n }\n\n await Promise.all(\n snapIds.map(async (snapId) => {\n const truncated = this.getTruncatedExpect(snapId);\n // Disable the snap and revoke all of its permissions before deleting\n // it. This ensures that the snap will not be restarted or otherwise\n // affect the host environment while we are deleting it.\n await this.disableSnap(snapId);\n this.revokeAllSnapPermissions(snapId);\n\n const permissionName = getSnapPermissionName(snapId);\n // Revoke all subjects access to the snap\n this.messagingSystem.call(\n 'PermissionController:revokePermissionForAllSubjects',\n permissionName,\n );\n\n this.snapsRuntimeData.delete(snapId);\n\n this.update((state: any) => {\n delete state.snaps[snapId];\n delete state.snapStates[snapId];\n });\n\n this.messagingSystem.publish(`SnapController:snapRemoved`, truncated);\n }),\n );\n }\n\n /**\n * Safely revokes all permissions granted to a Snap.\n *\n * @param snapId - The snap ID.\n */\n private revokeAllSnapPermissions(snapId: string) {\n if (\n this.messagingSystem.call('PermissionController:hasPermissions', snapId)\n ) {\n this.messagingSystem.call(\n 'PermissionController:revokeAllPermissions',\n snapId,\n );\n }\n }\n\n /**\n * Handles incrementing the activeReferences counter.\n *\n * @param snapId - The snap id of the snap that was referenced.\n */\n incrementActiveReferences(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.activeReferences += 1;\n }\n\n /**\n * Handles decrement the activeReferences counter.\n *\n * @param snapId - The snap id of the snap that was referenced..\n */\n decrementActiveReferences(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n assert(\n runtime.activeReferences > 0,\n 'SnapController reference management is in an invalid state.',\n );\n runtime.activeReferences -= 1;\n }\n\n /**\n * Gets all snaps in their truncated format.\n *\n * @returns All installed snaps in their truncated format.\n */\n getAllSnaps(): TruncatedSnap[] {\n return Object.values(this.state.snaps).map(truncateSnap);\n }\n\n /**\n * Gets the serialized permitted snaps of the given origin, if any.\n *\n * @param origin - The origin whose permitted snaps to retrieve.\n * @returns The serialized permitted snaps for the origin.\n */\n getPermittedSnaps(origin: string): InstallSnapsResult {\n return Object.values(\n this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n ) ?? {},\n ).reduce<InstallSnapsResult>((permittedSnaps, perm) => {\n if (perm.parentCapability.startsWith(SNAP_PREFIX)) {\n const snapId = perm.parentCapability.replace(SNAP_PREFIX_REGEX, '');\n const snap = this.get(snapId);\n const truncatedSnap = this.getTruncated(snapId);\n\n if (truncatedSnap && snap?.status !== SnapStatus.Installing) {\n permittedSnaps[snapId] = truncatedSnap;\n }\n }\n return permittedSnaps;\n }, {});\n }\n\n /**\n * Installs the snaps requested by the given origin, returning the snap\n * object if the origin is permitted to install it, and an authorization error\n * otherwise.\n *\n * @param origin - The origin that requested to install the snaps.\n * @param requestedSnaps - The snaps to install.\n * @returns An object of snap ids and snap objects, or errors if a\n * snap couldn't be installed.\n */\n async installSnaps(\n origin: string,\n requestedSnaps: RequestedSnapPermissions,\n ): Promise<InstallSnapsResult> {\n const result: InstallSnapsResult = {};\n\n const snapIds = Object.keys(requestedSnaps);\n\n // Existing snaps may need to be updated\n const pendingUpdates = snapIds.filter((snapId) => this.has(snapId));\n\n // Non-existing snaps will need to be installed\n const pendingInstalls = snapIds.filter(\n (snapId) => !pendingUpdates.includes(snapId),\n );\n\n try {\n for (const [snapId, { version: rawVersion }] of Object.entries(\n requestedSnaps,\n )) {\n const [error, version] = resolveVersionRange(rawVersion);\n\n if (error) {\n throw ethErrors.rpc.invalidParams(\n `The \"version\" field must be a valid SemVer version range if specified. Received: \"${rawVersion}\".`,\n );\n }\n\n const permissionName = getSnapPermissionName(snapId);\n\n if (\n !this.messagingSystem.call(\n 'PermissionController:hasPermission',\n origin,\n permissionName,\n )\n ) {\n throw ethErrors.provider.unauthorized(\n `Not authorized to install snap \"${snapId}\". Request the permission for the snap before attempting to install it.`,\n );\n }\n\n const isUpdate = pendingUpdates.includes(snapId);\n\n if (isUpdate && this.#isValidUpdate(snapId, version)) {\n let rollbackSnapshot = this.#getRollbackSnapshot(snapId);\n if (rollbackSnapshot === undefined) {\n const prevSourceCode = this.#getRuntimeExpect(snapId).sourceCode;\n rollbackSnapshot = this.#createRollbackSnapshot(snapId);\n rollbackSnapshot.sourceCode = prevSourceCode;\n rollbackSnapshot.newVersion = version;\n } else {\n throw new Error('This snap is already being updated.');\n }\n }\n\n result[snapId] = await this.processRequestedSnap(\n origin,\n snapId,\n version,\n );\n }\n snapIds.forEach((snapId) => this.#rollbackSnapshots.delete(snapId));\n } catch (error) {\n const installed = pendingInstalls.filter((snapId) => this.has(snapId));\n await this.removeSnaps(installed);\n const snapshottedSnaps = [...this.#rollbackSnapshots.keys()];\n const snapsToRollback = pendingUpdates.filter((snapId) =>\n snapshottedSnaps.includes(snapId),\n );\n await this.#rollbackSnaps(snapsToRollback);\n\n throw error;\n }\n return result;\n }\n\n /**\n * Adds, authorizes, and runs the given snap with a snap provider.\n * Results from this method should be efficiently serializable.\n *\n * @param origin - The origin requesting the snap.\n * @param snapId - The id of the snap.\n * @param versionRange - The semver range of the snap to install.\n * @returns The resulting snap object, or an error if something went wrong.\n */\n private async processRequestedSnap(\n origin: string,\n snapId: SnapId,\n versionRange: SemVerRange,\n ): Promise<ProcessSnapResult> {\n validateSnapId(snapId);\n\n const location = this.#detectSnapLocation(snapId, {\n versionRange,\n fetch: this.#fetchFunction,\n });\n\n const existingSnap = this.getTruncated(snapId);\n // For devX we always re-install local snaps.\n if (existingSnap && !location.shouldAlwaysReload) {\n if (satisfiesVersionRange(existingSnap.version, versionRange)) {\n return existingSnap;\n }\n\n if (this.#featureFlags.dappsCanUpdateSnaps === true) {\n const updateResult = await this.updateSnap(\n origin,\n snapId,\n versionRange,\n location,\n );\n if (updateResult === null) {\n throw ethErrors.rpc.invalidParams(\n `Snap \"${snapId}@${existingSnap.version}\" is already installed. Couldn't update to a version inside requested \"${versionRange}\" range.`,\n );\n }\n return updateResult;\n }\n throw ethErrors.rpc.invalidParams(\n `Version mismatch with already installed snap. ${snapId}@${existingSnap.version} doesn't satisfy requested version ${versionRange}.`,\n );\n }\n\n // Existing snaps must be stopped before overwriting\n if (existingSnap && this.isRunning(snapId)) {\n await this.stopSnap(snapId, SnapStatusEvents.Stop);\n }\n\n try {\n const { sourceCode } = await this.#add({\n origin,\n id: snapId,\n location,\n });\n\n await this.authorize(origin, snapId);\n\n await this.#startSnap({\n snapId,\n sourceCode,\n });\n\n const truncated = this.getTruncatedExpect(snapId);\n\n this.messagingSystem.publish(`SnapController:snapInstalled`, truncated);\n return truncated;\n } catch (error) {\n console.error(`Error when adding snap.`, error);\n\n throw error;\n }\n }\n\n /**\n * Updates an installed snap. The flow is similar to\n * {@link SnapController.installSnaps}. The user will be asked if they want\n * to update, then approve any permission changes, and finally the snap will\n * be restarted.\n *\n * The update will fail if the user rejects any prompt or if the new version\n * of the snap is blocked.\n *\n * If the original version of the snap was blocked and the update succeeded,\n * the snap will be unblocked and enabled before it is restarted.\n *\n * @param origin - The origin requesting the snap update.\n * @param snapId - The id of the Snap to be updated.\n * @param newVersionRange - A semver version range in which the maximum version will be chosen.\n * @param location - Optional location that was already used during installation flow.\n * @returns The snap metadata if updated, `null` otherwise.\n */\n async updateSnap(\n origin: string,\n snapId: ValidatedSnapId,\n newVersionRange: string = DEFAULT_REQUESTED_SNAP_VERSION,\n location?: SnapLocation,\n ): Promise<TruncatedSnap | null> {\n const snap = this.getExpect(snapId);\n\n if (!isValidSemVerRange(newVersionRange)) {\n throw new Error(\n `Received invalid snap version range: \"${newVersionRange}\".`,\n );\n }\n const newSnap = await this.#fetchSnap(\n snapId,\n location ??\n this.#detectSnapLocation(snapId, { versionRange: newVersionRange }),\n );\n const newVersion = newSnap.manifest.result.version;\n if (!gtVersion(newVersion, snap.version)) {\n console.warn(\n `Tried updating snap \"${snapId}\" within \"${newVersionRange}\" version range, but newer version \"${snap.version}\" is already installed`,\n );\n return null;\n }\n\n await this.#assertIsUnblocked(snapId, {\n version: newVersion,\n shasum: newSnap.manifest.result.source.shasum,\n });\n\n const processedPermissions = this.#processSnapPermissions(\n newSnap.manifest.result.initialPermissions,\n );\n\n const { newPermissions, unusedPermissions, approvedPermissions } =\n this.#calculatePermissionsChange(snapId, processedPermissions);\n\n const id = nanoid();\n const { permissions: approvedNewPermissions, ...requestData } =\n (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n origin,\n id,\n type: SNAP_APPROVAL_UPDATE,\n requestData: {\n // First two keys mirror installation params\n metadata: { id, origin: snapId, dappOrigin: origin },\n permissions: newPermissions,\n snapId,\n newVersion: newSnap.manifest.result.version,\n newPermissions,\n approvedPermissions,\n unusedPermissions,\n },\n },\n true,\n )) as PermissionsRequest;\n\n if (this.isRunning(snapId)) {\n await this.stopSnap(snapId, SnapStatusEvents.Stop);\n }\n\n this.#transition(snapId, SnapStatusEvents.Update);\n\n this.#set({\n origin,\n id: snapId,\n manifest: newSnap.manifest,\n files: newSnap.files,\n versionRange: newVersionRange,\n isUpdate: true,\n });\n\n const unusedPermissionsKeys = Object.keys(unusedPermissions);\n if (isNonEmptyArray(unusedPermissionsKeys)) {\n this.messagingSystem.call('PermissionController:revokePermissions', {\n [snapId]: unusedPermissionsKeys,\n });\n }\n\n if (isNonEmptyArray(Object.keys(approvedNewPermissions))) {\n this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions: approvedNewPermissions,\n subject: { origin: snapId },\n requestData,\n });\n }\n\n const rollbackSnapshot = this.#getRollbackSnapshot(snapId);\n if (rollbackSnapshot !== undefined) {\n rollbackSnapshot.permissions.revoked = unusedPermissions;\n rollbackSnapshot.permissions.granted = Object.keys(\n approvedNewPermissions,\n );\n rollbackSnapshot.permissions.requestData = requestData;\n }\n\n const sourceCode = newSnap.files\n .find(\n (file) =>\n file.path === newSnap.manifest.result.source.location.npm.filePath,\n )\n ?.toString();\n assert(sourceCode !== undefined);\n\n try {\n await this.#startSnap({ snapId, sourceCode });\n } catch {\n throw new Error(`Snap ${snapId} crashed with updated source code.`);\n }\n\n const truncatedSnap = this.getTruncatedExpect(snapId);\n this.messagingSystem.publish(\n 'SnapController:snapUpdated',\n truncatedSnap,\n snap.version,\n );\n\n return truncatedSnap;\n }\n\n /**\n * Returns a promise representing the complete installation of the requested snap.\n * If the snap is already being installed, the previously pending promise will be returned.\n *\n * @param args - Object containing the snap id and either the URL of the snap's manifest,\n * or the snap's manifest and source code. The object may also optionally contain a target\n * version.\n * @returns The resulting snap object.\n */\n async #add(args: AddSnapArgs): Promise<PersistedSnap> {\n const { id: snapId, location } = args;\n validateSnapId(snapId);\n\n this.#setupRuntime(snapId, { sourceCode: null, state: null });\n const runtime = this.#getRuntimeExpect(snapId);\n if (!runtime.installPromise) {\n console.info(`Adding snap: ${snapId}`);\n\n // If fetching and setting the snap succeeds, this property will be set\n // to null in the authorize() method.\n runtime.installPromise = (async () => {\n const fetchedSnap = await this.#fetchSnap(snapId, location);\n await this.#assertIsUnblocked(snapId, {\n version: fetchedSnap.manifest.result.version,\n shasum: fetchedSnap.manifest.result.source.shasum,\n });\n\n return this.#set({\n ...args,\n ...fetchedSnap,\n id: snapId,\n });\n })();\n }\n\n try {\n return await runtime.installPromise;\n } catch (error) {\n // Reset promise so users can retry installation in case the problem is\n // temporary.\n runtime.installPromise = null;\n throw error;\n }\n }\n\n async #startSnap(snapData: { snapId: string; sourceCode: string }) {\n const { snapId } = snapData;\n if (this.isRunning(snapId)) {\n throw new Error(`Snap \"${snapId}\" is already started.`);\n }\n\n try {\n const result = await this.#executeWithTimeout(\n snapId,\n this.messagingSystem.call('ExecutionService:executeSnap', {\n ...snapData,\n endowments: await this.#getEndowments(snapId),\n }),\n );\n this.#transition(snapId, SnapStatusEvents.Start);\n return result;\n } catch (error) {\n await this.#terminateSnap(snapId);\n throw error;\n }\n }\n\n /**\n * Gets the names of all endowments that will be added to the Snap's\n * Compartment when it executes. These should be the names of global\n * JavaScript APIs accessible in the root realm of the execution environment.\n *\n * Throws an error if the endowment getter for a permission returns a truthy\n * value that is not an array of strings.\n *\n * @param snapId - The id of the snap whose SES endowments to get.\n * @returns An array of the names of the endowments.\n */\n async #getEndowments(snapId: string): Promise<string[]> {\n let allEndowments: string[] = [];\n\n for (const permissionName of this.#environmentEndowmentPermissions) {\n if (\n this.messagingSystem.call(\n 'PermissionController:hasPermission',\n snapId,\n permissionName,\n )\n ) {\n const endowments = await this.messagingSystem.call(\n 'PermissionController:getEndowments',\n snapId,\n permissionName,\n );\n\n if (endowments) {\n // We don't have any guarantees about the type of the endowments\n // value, so we have to guard at runtime.\n if (\n !Array.isArray(endowments) ||\n endowments.some((value) => typeof value !== 'string')\n ) {\n throw new Error('Expected an array of string endowment names.');\n }\n\n allEndowments = allEndowments.concat(endowments as string[]);\n }\n }\n }\n\n const dedupedEndowments = [\n ...new Set([...DEFAULT_ENDOWMENTS, ...allEndowments]),\n ];\n\n if (\n dedupedEndowments.length <\n // This is a bug in TypeScript: https://github.com/microsoft/TypeScript/issues/48313\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n DEFAULT_ENDOWMENTS.length + allEndowments.length\n ) {\n console.error(\n 'Duplicate endowments found. Default endowments should not be requested.',\n allEndowments,\n );\n }\n return dedupedEndowments;\n }\n\n /**\n * Sets a snap in state. Called when a snap is installed or updated. Performs\n * various validation checks on the received arguments, and will throw if\n * validation fails.\n *\n * The snap will be enabled and unblocked by the time this method returns,\n * regardless of its previous state.\n *\n * See {@link SnapController.add} and {@link SnapController.updateSnap} for\n * usage.\n *\n * @param args - The add snap args.\n * @returns The resulting snap object.\n */\n #set(args: SetSnapArgs): PersistedSnap {\n const {\n id: snapId,\n origin,\n manifest,\n files,\n versionRange = DEFAULT_REQUESTED_SNAP_VERSION,\n isUpdate = false,\n } = args;\n\n assertIsSnapManifest(manifest.result);\n const { version } = manifest.result;\n\n if (!satisfiesVersionRange(version, versionRange)) {\n throw new Error(\n `Version mismatch. Manifest for \"${snapId}\" specifies version \"${version}\" which doesn't satisfy requested version range \"${versionRange}\"`,\n );\n }\n\n const sourceCode = files\n .find(\n (file) => file.path === manifest.result.source.location.npm.filePath,\n )\n ?.toString();\n const svgIcon = files.find(\n (file) =>\n manifest.result.source.location.npm.iconPath !== undefined &&\n file.path === manifest.result.source.location.npm.iconPath,\n );\n assert(sourceCode !== undefined);\n if (typeof sourceCode !== 'string' || sourceCode.length === 0) {\n throw new Error(`Invalid source code for snap \"${snapId}\".`);\n }\n\n const snapsState = this.state.snaps;\n\n const existingSnap = snapsState[snapId];\n\n const previousVersionHistory = existingSnap?.versionHistory ?? [];\n const versionHistory = [\n ...previousVersionHistory,\n {\n version,\n date: Date.now(),\n origin,\n },\n ];\n\n const snap: Snap = {\n // Restore relevant snap state if it exists\n ...existingSnap,\n\n // Note that the snap will be unblocked and enabled, regardless of its\n // previous state.\n blocked: false,\n enabled: true,\n\n // So we can easily correlate the snap with its permission\n permissionName: getSnapPermissionName(snapId),\n\n id: snapId,\n initialPermissions: manifest.result.initialPermissions,\n manifest: manifest.result,\n status: this.#statusMachine.config.initial as StatusStates['value'],\n version,\n versionHistory,\n };\n // If the snap was blocked, it isn't any longer\n delete snap.blockInformation;\n\n // store the snap back in state\n const { inversePatches } = this.update((state: any) => {\n state.snaps[snapId] = snap;\n });\n\n // checking for isUpdate here as this function is also used in\n // the install flow, we do not care to create snapshots for installs\n if (isUpdate) {\n const rollbackSnapshot = this.#getRollbackSnapshot(snapId);\n if (rollbackSnapshot !== undefined) {\n rollbackSnapshot.statePatches = inversePatches;\n }\n }\n\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.sourceCode = sourceCode;\n\n this.messagingSystem.publish(\n `SnapController:snapAdded`,\n snap,\n svgIcon?.toString(),\n );\n return { ...snap, sourceCode };\n }\n\n /**\n * Fetches the manifest and source code of a snap.\n *\n * This function is not hash private yet because of tests.\n *\n * @param snapId - The id of the Snap.\n * @param location - Source from which snap will be fetched.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\n async #fetchSnap(\n snapId: ValidatedSnapId,\n location: SnapLocation,\n ): Promise<FetchSnapResult> {\n try {\n const manifest = await location.manifest();\n const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\n );\n validateSnapShasum(manifest.result, sourceCode.toString());\n const { iconPath } = manifest.result.source.location.npm;\n\n const files = [sourceCode];\n if (iconPath) {\n files.push(await location.fetch(iconPath));\n }\n\n return { manifest, files, location };\n } catch (error) {\n // TODO(ritave): Export `getErrorMessage()` from @metamask/utils and use it here\n // https://github.com/MetaMask/utils/blob/62d022ef83c91fa4d150e51913be4441508a0ab1/src/assert.ts\n const message = error instanceof Error ? error.message : error.toString();\n throw new Error(`Failed to fetch Snap \"${snapId}\": ${message}.`);\n }\n }\n\n /**\n * Map initial permissions as defined in a Snap manifest to something that can\n * be processed by the PermissionsController. Each caveat mapping function\n * should return a valid permission caveat value.\n *\n * This function does not validate the caveat values, since that is done by\n * the PermissionsController itself, upon requesting the permissions.\n *\n * @param initialPermissions - The initial permissions to process.\n * @returns The processed permissions.\n * @private\n */\n #processSnapPermissions(\n initialPermissions: SnapPermissions,\n ): Record<string, Pick<PermissionConstraint, 'caveats'>> {\n return fromEntries(\n Object.entries(initialPermissions).map(([initialPermission, value]) => {\n if (hasProperty(caveatMappers, initialPermission)) {\n return [initialPermission, caveatMappers[initialPermission](value)];\n } else if (hasProperty(endowmentCaveatMappers, initialPermission)) {\n return [\n initialPermission,\n endowmentCaveatMappers[initialPermission](value),\n ];\n }\n\n // If we have no mapping, this may be a non-snap permission, return as-is\n return [\n initialPermission,\n value as Pick<PermissionConstraint, 'caveats'>,\n ];\n }),\n );\n }\n\n /**\n * Initiates a request for the given snap's initial permissions.\n * Must be called in order. See processRequestedSnap.\n *\n * This function is not hash private yet because of tests.\n *\n * @param origin - The origin of the install request.\n * @param snapId - The id of the Snap.\n * @returns The snap's approvedPermissions.\n */\n private async authorize(origin: string, snapId: SnapId): Promise<void> {\n console.info(`Authorizing snap: ${snapId}`);\n const snapsState = this.state.snaps;\n const snap = snapsState[snapId];\n const { initialPermissions } = snap;\n\n try {\n const processedPermissions =\n this.#processSnapPermissions(initialPermissions);\n const id = nanoid();\n const { permissions: approvedPermissions, ...requestData } =\n (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n origin,\n id,\n type: SNAP_APPROVAL_INSTALL,\n requestData: {\n // Mirror previous installation metadata\n metadata: { id, origin: snapId, dappOrigin: origin },\n permissions: processedPermissions,\n snapId,\n },\n },\n true,\n )) as PermissionsRequest;\n\n if (isNonEmptyArray(Object.keys(approvedPermissions))) {\n this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions,\n subject: { origin: snapId },\n requestData,\n });\n }\n } finally {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.installPromise = null;\n }\n }\n\n destroy() {\n super.destroy();\n\n if (this.#timeoutForLastRequestStatus) {\n clearTimeout(this.#timeoutForLastRequestStatus);\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'ExecutionService:unhandledError',\n this._onUnhandledSnapError,\n );\n\n this.messagingSystem.unsubscribe(\n 'ExecutionService:outboundRequest',\n this._onOutboundRequest,\n );\n\n this.messagingSystem.unsubscribe(\n 'ExecutionService:outboundResponse',\n this._onOutboundResponse,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n }\n\n /**\n * Passes a JSON-RPC request object to the RPC handler function of a snap.\n *\n * @param options - A bag of options.\n * @param options.snapId - The ID of the recipient snap.\n * @param options.origin - The origin of the RPC request.\n * @param options.handler - The handler to trigger on the snap for the request.\n * @param options.request - The JSON-RPC request object.\n * @returns The result of the JSON-RPC request.\n */\n async handleRequest({\n snapId,\n origin,\n handler: handlerType,\n request,\n }: SnapRpcHookArgs & { snapId: SnapId }): Promise<unknown> {\n const permissionName = handlerEndowments[handlerType];\n const hasPermission = this.messagingSystem.call(\n 'PermissionController:hasPermission',\n snapId,\n permissionName,\n );\n\n if (!hasPermission) {\n throw new Error(\n `Snap \"${snapId}\" is not permitted to use \"${permissionName}\".`,\n );\n }\n\n if (permissionName === SnapEndowments.Rpc) {\n const subject = this.messagingSystem.call(\n 'SubjectMetadataController:getSubjectMetadata',\n origin,\n );\n const isSnap = subject?.subjectType === SubjectType.Snap;\n\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const rpcPermission = permissions?.[SnapEndowments.Rpc];\n assert(rpcPermission);\n\n const origins = getRpcCaveatOrigins(rpcPermission);\n assert(origins);\n\n if ((isSnap && !origins.snaps) || (!isSnap && !origins.dapps)) {\n throw new Error(\n `Snap \"${snapId}\" is not permitted to handle JSON-RPC requests from \"${origin}\".`,\n );\n }\n }\n\n const handler = await this.#getRpcRequestHandler(snapId);\n if (!handler) {\n throw new Error(\n `Snap RPC message handler not found for snap \"${snapId}\".`,\n );\n }\n\n return handler({ origin, handler: handlerType, request });\n }\n\n /**\n * Gets the RPC message handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC handler for the given snap.\n */\n #getRpcRequestHandler(snapId: SnapId): SnapRpcHook {\n const runtime = this.#getRuntimeExpect(snapId);\n const existingHandler = runtime.rpcHandler;\n if (existingHandler) {\n return existingHandler;\n }\n\n const requestQueue = new RequestQueue(5);\n // We need to set up this promise map to map snapIds to their respective startPromises,\n // because otherwise we would lose context on the correct startPromise.\n const startPromises = new Map<string, Promise<void>>();\n\n const rpcHandler = async ({\n origin,\n handler: handlerType,\n request,\n }: SnapRpcHookArgs) => {\n if (this.state.snaps[snapId].enabled === false) {\n throw new Error(`Snap \"${snapId}\" is disabled.`);\n }\n\n if (this.state.snaps[snapId].status === SnapStatus.Installing) {\n throw new Error(\n `Snap \"${snapId}\" is currently being installed. Please try again later.`,\n );\n }\n\n if (!this.isRunning(snapId)) {\n let localStartPromise = startPromises.get(snapId);\n if (!localStartPromise) {\n localStartPromise = this.startSnap(snapId);\n startPromises.set(snapId, localStartPromise);\n } else if (requestQueue.get(origin) >= requestQueue.maxQueueSize) {\n throw new Error(\n 'Exceeds maximum number of requests waiting to be resolved, please try again.',\n );\n }\n\n requestQueue.increment(origin);\n try {\n await localStartPromise;\n } finally {\n requestQueue.decrement(origin);\n // Only delete startPromise for a snap if its value hasn't changed\n if (startPromises.get(snapId) === localStartPromise) {\n startPromises.delete(snapId);\n }\n }\n }\n\n let _request = request;\n if (!hasProperty(request, 'jsonrpc')) {\n _request = { ...request, jsonrpc: '2.0' };\n } else if (request.jsonrpc !== '2.0') {\n throw ethErrors.rpc.invalidRequest({\n message: 'Invalid \"jsonrpc\" property. Must be \"2.0\" if provided.',\n data: request.jsonrpc,\n });\n }\n\n const timer = new Timer(this.maxRequestTime);\n this.#recordSnapRpcRequestStart(snapId, request.id, timer);\n\n const handleRpcRequestPromise = this.messagingSystem.call(\n 'ExecutionService:handleRpcRequest',\n snapId,\n { origin, handler: handlerType, request: _request },\n );\n\n // This will either get the result or reject due to the timeout.\n try {\n const result = await this.#executeWithTimeout(\n snapId,\n handleRpcRequestPromise,\n timer,\n );\n this.#recordSnapRpcRequestFinish(snapId, request.id);\n return result;\n } catch (error) {\n await this.stopSnap(snapId, SnapStatusEvents.Crash);\n throw error;\n }\n };\n\n runtime.rpcHandler = rpcHandler;\n return rpcHandler;\n }\n\n /**\n * Awaits the specified promise and rejects if the promise doesn't resolve\n * before the timeout.\n *\n * @param snapId - The snap id.\n * @param promise - The promise to await.\n * @param timer - An optional timer object to control the timeout.\n * @returns The result of the promise or rejects if the promise times out.\n * @template PromiseValue - The value of the Promise.\n */\n async #executeWithTimeout<PromiseValue>(\n snapId: SnapId,\n promise: Promise<PromiseValue>,\n timer?: Timer,\n ): Promise<PromiseValue> {\n const isLongRunning = this.messagingSystem.call(\n 'PermissionController:hasPermission',\n snapId,\n SnapEndowments.LongRunning,\n );\n\n // Long running snaps have timeouts disabled\n if (isLongRunning) {\n return promise;\n }\n\n const result = await withTimeout(promise, timer ?? this.maxRequestTime);\n if (result === hasTimedOut) {\n throw new Error('The request timed out.');\n }\n return result;\n }\n\n #recordSnapRpcRequestStart(snapId: SnapId, requestId: unknown, timer: Timer) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.pendingInboundRequests.push({ requestId, timer });\n runtime.lastRequest = null;\n }\n\n #recordSnapRpcRequestFinish(snapId: SnapId, requestId: unknown) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.pendingInboundRequests = runtime.pendingInboundRequests.filter(\n (request) => request.requestId !== requestId,\n );\n\n if (runtime.pendingInboundRequests.length === 0) {\n runtime.lastRequest = Date.now();\n }\n }\n\n /**\n * Retrieves the rollback snapshot of a snap.\n *\n * @param snapId - The snap id.\n * @returns A `RollbackSnapshot` or `undefined` if one doesn't exist.\n */\n #getRollbackSnapshot(snapId: SnapId): RollbackSnapshot | undefined {\n return this.#rollbackSnapshots.get(snapId);\n }\n\n /**\n * Creates a `RollbackSnapshot` that is used to help ensure\n * atomicity in multiple snap updates.\n *\n * @param snapId - The snap id.\n * @throws {@link Error}. If the snap exists before creation or if creation fails.\n * @returns A `RollbackSnapshot`.\n */\n #createRollbackSnapshot(snapId: SnapId): RollbackSnapshot {\n assert(\n this.#rollbackSnapshots.get(snapId) === undefined,\n new Error(`Snap \"${snapId}\" rollback snapshot already exists.`),\n );\n\n this.#rollbackSnapshots.set(snapId, {\n statePatches: [],\n sourceCode: '',\n permissions: { revoked: null, granted: [], requestData: null },\n newVersion: '',\n });\n\n const newRollbackSnapshot = this.#rollbackSnapshots.get(snapId);\n\n assert(\n newRollbackSnapshot !== undefined,\n new Error(`Snapshot creation failed for ${snapId}.`),\n );\n return newRollbackSnapshot;\n }\n\n /**\n * Rolls back a snap to its previous state, permissions\n * and source code based on the `RollbackSnapshot` that\n * is captured during the update process. After rolling back,\n * the function also emits an event indicating that the\n * snap has been rolled back and it clears the snapshot\n * for that snap.\n *\n * @param snapId - The snap id.\n * @throws {@link Error}. If a snapshot does not exist.\n */\n async #rollbackSnap(snapId: SnapId) {\n const rollbackSnapshot = this.#getRollbackSnapshot(snapId);\n if (!rollbackSnapshot) {\n throw new Error('A snapshot does not exist for this snap.');\n }\n\n await this.stopSnap(snapId, SnapStatusEvents.Stop);\n\n const { statePatches, sourceCode, permissions } = rollbackSnapshot;\n\n if (statePatches?.length) {\n this.applyPatches(statePatches);\n }\n\n if (sourceCode) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.sourceCode = sourceCode;\n }\n\n if (permissions.revoked && Object.keys(permissions.revoked).length) {\n this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions: permissions.revoked as RequestedPermissions,\n subject: { origin: snapId },\n requestData: permissions.requestData as Record<string, unknown>,\n });\n }\n\n if (permissions.granted?.length) {\n this.messagingSystem.call('PermissionController:revokePermissions', {\n [snapId]: permissions.granted as NonEmptyArray<string>,\n });\n }\n\n const truncatedSnap = this.getTruncatedExpect(snapId);\n\n this.messagingSystem.publish(\n 'SnapController:snapRolledback',\n truncatedSnap,\n rollbackSnapshot.newVersion,\n );\n\n this.#rollbackSnapshots.delete(snapId);\n }\n\n /**\n * Iterates through an array of snap ids\n * and calls `rollbackSnap` on them.\n *\n * @param snapIds - An array of snap ids.\n */\n async #rollbackSnaps(snapIds: SnapId[]) {\n for (const snapId of snapIds) {\n await this.#rollbackSnap(snapId);\n }\n }\n\n #getRuntime(snapId: SnapId): SnapRuntimeData | undefined {\n return this.snapsRuntimeData.get(snapId);\n }\n\n #getRuntimeExpect(snapId: SnapId): SnapRuntimeData {\n const runtime = this.#getRuntime(snapId);\n assert(\n runtime !== undefined,\n new Error(`Snap \"${snapId}\" runtime data not found`),\n );\n return runtime;\n }\n\n #setupRuntime(\n snapId: SnapId,\n data: { sourceCode: string | null; state: string | null },\n ) {\n if (this.snapsRuntimeData.has(snapId)) {\n return;\n }\n\n const snap = this.get(snapId);\n const interpreter = interpret(this.#statusMachine);\n interpreter.start({\n context: { snapId },\n value:\n snap?.status ??\n (this.#statusMachine.config.initial as StatusStates['value']),\n });\n\n forceStrict(interpreter);\n\n this.snapsRuntimeData.set(snapId, {\n lastRequest: null,\n rpcHandler: null,\n installPromise: null,\n activeReferences: 0,\n pendingInboundRequests: [],\n pendingOutboundRequests: 0,\n interpreter,\n ...data,\n });\n }\n\n #calculatePermissionsChange(\n snapId: SnapId,\n desiredPermissionsSet: RequestedSnapPermissions,\n ): {\n newPermissions: RequestedSnapPermissions;\n unusedPermissions: SubjectPermissions<\n ValidPermission<string, Caveat<string, any>>\n >;\n approvedPermissions: SubjectPermissions<\n ValidPermission<string, Caveat<string, any>>\n >;\n } {\n const oldPermissions =\n this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n ) ?? {};\n\n const newPermissions = setDiff(desiredPermissionsSet, oldPermissions);\n // TODO(ritave): The assumption that these are unused only holds so long as we do not\n // permit dynamic permission requests.\n const unusedPermissions = setDiff(oldPermissions, desiredPermissionsSet);\n\n // It's a Set Intersection of oldPermissions and desiredPermissionsSet\n // oldPermissions ∖ (oldPermissions ∖ desiredPermissionsSet) ⟺ oldPermissions ∩ desiredPermissionsSet\n const approvedPermissions = setDiff(oldPermissions, unusedPermissions);\n\n return { newPermissions, unusedPermissions, approvedPermissions };\n }\n\n /**\n * Checks if a snap will pass version validation checks\n * with the new version range that is requested. The first\n * check that is done is to check if the existing snap version\n * falls inside the requested range. If it does, we want to return\n * false because we do not care to create a rollback snapshot in\n * that scenario. The second check is to ensure that the current\n * snap version is not greater than all possible versions in\n * the requested version range. If it is, then we also want\n * to return false in that scenario.\n *\n * @param snapId - The snap id.\n * @param newVersionRange - The new version range being requsted.\n * @returns `true` if validation checks pass and `false` if they do not.\n */\n #isValidUpdate(snapId: SnapId, newVersionRange: SemVerRange): boolean {\n const existingSnap = this.getExpect(snapId);\n\n if (satisfiesVersionRange(existingSnap.version, newVersionRange)) {\n return false;\n }\n\n if (gtRange(existingSnap.version, newVersionRange)) {\n return false;\n }\n\n return true;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-controllers",
3
- "version": "0.26.2",
3
+ "version": "0.27.1",
4
4
  "description": "Controllers for MetaMask Snaps.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -33,14 +33,12 @@
33
33
  "dependencies": {
34
34
  "@metamask/approval-controller": "^1.0.1",
35
35
  "@metamask/base-controller": "^1.1.1",
36
- "@metamask/browser-passworder": "^4.0.2",
37
36
  "@metamask/object-multiplex": "^1.1.0",
38
37
  "@metamask/permission-controller": "^1.0.1",
39
38
  "@metamask/post-message-stream": "^6.0.0",
40
- "@metamask/rpc-methods": "^0.26.2",
41
- "@metamask/snaps-execution-environments": "^0.26.2",
42
- "@metamask/snaps-types": "^0.26.2",
43
- "@metamask/snaps-utils": "^0.26.2",
39
+ "@metamask/rpc-methods": "^0.27.1",
40
+ "@metamask/snaps-execution-environments": "^0.27.1",
41
+ "@metamask/snaps-utils": "^0.27.1",
44
42
  "@metamask/subject-metadata-controller": "^1.0.1",
45
43
  "@metamask/utils": "^3.3.1",
46
44
  "@xstate/fsm": "^2.0.0",