@metamask/snaps-controllers 0.37.2-flask.1 → 0.38.1-flask.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -1
- package/dist/cjs/services/AbstractExecutionService.js +1 -19
- package/dist/cjs/services/AbstractExecutionService.js.map +1 -1
- package/dist/cjs/services/ExecutionService.js.map +1 -1
- package/dist/cjs/snaps/SnapController.js +66 -54
- package/dist/cjs/snaps/SnapController.js.map +1 -1
- package/dist/cjs/snaps/endowments/enum.js +1 -0
- package/dist/cjs/snaps/endowments/enum.js.map +1 -1
- package/dist/cjs/snaps/endowments/index.js +6 -2
- package/dist/cjs/snaps/endowments/index.js.map +1 -1
- package/dist/cjs/snaps/endowments/lifecycle-hooks.js +37 -0
- package/dist/cjs/snaps/endowments/lifecycle-hooks.js.map +1 -0
- package/dist/cjs/snaps/registry/json.js +33 -5
- package/dist/cjs/snaps/registry/json.js.map +1 -1
- package/dist/cjs/snaps/registry/registry.js.map +1 -1
- package/dist/esm/services/AbstractExecutionService.js +1 -19
- package/dist/esm/services/AbstractExecutionService.js.map +1 -1
- package/dist/esm/services/ExecutionService.js.map +1 -1
- package/dist/esm/snaps/SnapController.js +67 -55
- package/dist/esm/snaps/SnapController.js.map +1 -1
- package/dist/esm/snaps/endowments/enum.js +1 -0
- package/dist/esm/snaps/endowments/enum.js.map +1 -1
- package/dist/esm/snaps/endowments/index.js +6 -2
- package/dist/esm/snaps/endowments/index.js.map +1 -1
- package/dist/esm/snaps/endowments/lifecycle-hooks.js +27 -0
- package/dist/esm/snaps/endowments/lifecycle-hooks.js.map +1 -0
- package/dist/esm/snaps/registry/json.js +33 -5
- package/dist/esm/snaps/registry/json.js.map +1 -1
- package/dist/esm/snaps/registry/registry.js.map +1 -1
- package/dist/types/services/ExecutionService.d.ts +1 -1
- package/dist/types/snaps/SnapController.d.ts +5 -14
- package/dist/types/snaps/endowments/enum.d.ts +2 -1
- package/dist/types/snaps/endowments/index.d.ts +9 -0
- package/dist/types/snaps/endowments/lifecycle-hooks.d.ts +15 -0
- package/dist/types/snaps/registry/json.d.ts +5 -1
- package/dist/types/snaps/registry/registry.d.ts +1 -0
- package/package.json +12 -14
|
@@ -17,6 +17,7 @@ var SnapEndowments;
|
|
|
17
17
|
SnapEndowments["EthereumProvider"] = 'endowment:ethereum-provider';
|
|
18
18
|
SnapEndowments["Rpc"] = 'endowment:rpc';
|
|
19
19
|
SnapEndowments["WebAssemblyAccess"] = 'endowment:webassembly';
|
|
20
|
+
SnapEndowments["LifecycleHooks"] = 'endowment:lifecycle-hooks';
|
|
20
21
|
})(SnapEndowments || (SnapEndowments = {}));
|
|
21
22
|
|
|
22
23
|
//# sourceMappingURL=enum.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/endowments/enum.ts"],"sourcesContent":["export enum SnapEndowments {\n NetworkAccess = 'endowment:network-access',\n LongRunning = 'endowment:long-running',\n TransactionInsight = 'endowment:transaction-insight',\n Cronjob = 'endowment:cronjob',\n EthereumProvider = 'endowment:ethereum-provider',\n Rpc = 'endowment:rpc',\n WebAssemblyAccess = 'endowment:webassembly',\n}\n"],"names":["SnapEndowments","NetworkAccess","LongRunning","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess"],"mappings":";;;;;;;;;;IAAO;UAAKA,cAAc;IAAdA,eACVC,mBAAgB;IADND,eAEVE,iBAAc;IAFJF,eAGVG,wBAAqB;IAHXH,eAIVI,aAAU;IAJAJ,eAKVK,sBAAmB;IALTL,eAMVM,SAAM;IANIN,eAOVO,uBAAoB;
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/endowments/enum.ts"],"sourcesContent":["export enum SnapEndowments {\n NetworkAccess = 'endowment:network-access',\n LongRunning = 'endowment:long-running',\n TransactionInsight = 'endowment:transaction-insight',\n Cronjob = 'endowment:cronjob',\n EthereumProvider = 'endowment:ethereum-provider',\n Rpc = 'endowment:rpc',\n WebAssemblyAccess = 'endowment:webassembly',\n LifecycleHooks = 'endowment:lifecycle-hooks',\n}\n"],"names":["SnapEndowments","NetworkAccess","LongRunning","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","LifecycleHooks"],"mappings":";;;;;;;;;;IAAO;UAAKA,cAAc;IAAdA,eACVC,mBAAgB;IADND,eAEVE,iBAAc;IAFJF,eAGVG,wBAAqB;IAHXH,eAIVI,aAAU;IAJAJ,eAKVK,sBAAmB;IALTL,eAMVM,SAAM;IANIN,eAOVO,uBAAoB;IAPVP,eAQVQ,oBAAiB;GARPR,mBAAAA"}
|
|
@@ -31,6 +31,7 @@ _export(exports, {
|
|
|
31
31
|
const _snapsutils = require("@metamask/snaps-utils");
|
|
32
32
|
const _cronjob = require("./cronjob");
|
|
33
33
|
const _ethereumprovider = require("./ethereum-provider");
|
|
34
|
+
const _lifecyclehooks = require("./lifecycle-hooks");
|
|
34
35
|
const _longrunning = require("./long-running");
|
|
35
36
|
const _networkaccess = require("./network-access");
|
|
36
37
|
const _rpc = require("./rpc");
|
|
@@ -57,7 +58,8 @@ const endowmentPermissionBuilders = {
|
|
|
57
58
|
[_cronjob.cronjobEndowmentBuilder.targetName]: _cronjob.cronjobEndowmentBuilder,
|
|
58
59
|
[_ethereumprovider.ethereumProviderEndowmentBuilder.targetName]: _ethereumprovider.ethereumProviderEndowmentBuilder,
|
|
59
60
|
[_rpc.rpcEndowmentBuilder.targetName]: _rpc.rpcEndowmentBuilder,
|
|
60
|
-
[_webassembly.webAssemblyEndowmentBuilder.targetName]: _webassembly.webAssemblyEndowmentBuilder
|
|
61
|
+
[_webassembly.webAssemblyEndowmentBuilder.targetName]: _webassembly.webAssemblyEndowmentBuilder,
|
|
62
|
+
[_lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName]: _lifecyclehooks.lifecycleHooksEndowmentBuilder
|
|
61
63
|
};
|
|
62
64
|
const endowmentCaveatSpecifications = {
|
|
63
65
|
..._cronjob.cronjobCaveatSpecifications,
|
|
@@ -72,7 +74,9 @@ const endowmentCaveatMappers = {
|
|
|
72
74
|
const handlerEndowments = {
|
|
73
75
|
[_snapsutils.HandlerType.OnRpcRequest]: _rpc.rpcEndowmentBuilder.targetName,
|
|
74
76
|
[_snapsutils.HandlerType.OnTransaction]: _transactioninsight.transactionInsightEndowmentBuilder.targetName,
|
|
75
|
-
[_snapsutils.HandlerType.OnCronjob]: _cronjob.cronjobEndowmentBuilder.targetName
|
|
77
|
+
[_snapsutils.HandlerType.OnCronjob]: _cronjob.cronjobEndowmentBuilder.targetName,
|
|
78
|
+
[_snapsutils.HandlerType.OnInstall]: _lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName,
|
|
79
|
+
[_snapsutils.HandlerType.OnUpdate]: _lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName
|
|
76
80
|
};
|
|
77
81
|
|
|
78
82
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/endowments/index.ts"],"sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\n\nimport {\n cronjobCaveatSpecifications,\n cronjobEndowmentBuilder,\n getCronjobCaveatMapper,\n} from './cronjob';\nimport { ethereumProviderEndowmentBuilder } from './ethereum-provider';\nimport { longRunningEndowmentBuilder } from './long-running';\nimport { networkAccessEndowmentBuilder } from './network-access';\nimport {\n getRpcCaveatMapper,\n rpcCaveatSpecifications,\n rpcEndowmentBuilder,\n} from './rpc';\nimport {\n getTransactionInsightCaveatMapper,\n transactionInsightCaveatSpecifications,\n transactionInsightEndowmentBuilder,\n} from './transaction-insight';\nimport { webAssemblyEndowmentBuilder } from './web-assembly';\n\nexport const endowmentPermissionBuilders = {\n [networkAccessEndowmentBuilder.targetName]: networkAccessEndowmentBuilder,\n [longRunningEndowmentBuilder.targetName]: longRunningEndowmentBuilder,\n [transactionInsightEndowmentBuilder.targetName]:\n transactionInsightEndowmentBuilder,\n [cronjobEndowmentBuilder.targetName]: cronjobEndowmentBuilder,\n [ethereumProviderEndowmentBuilder.targetName]:\n ethereumProviderEndowmentBuilder,\n [rpcEndowmentBuilder.targetName]: rpcEndowmentBuilder,\n [webAssemblyEndowmentBuilder.targetName]: webAssemblyEndowmentBuilder,\n} as const;\n\nexport const endowmentCaveatSpecifications = {\n ...cronjobCaveatSpecifications,\n ...transactionInsightCaveatSpecifications,\n ...rpcCaveatSpecifications,\n};\n\nexport const endowmentCaveatMappers: Record<\n string,\n (value: Json) => Pick<PermissionConstraint, 'caveats'>\n> = {\n [cronjobEndowmentBuilder.targetName]: getCronjobCaveatMapper,\n [transactionInsightEndowmentBuilder.targetName]:\n getTransactionInsightCaveatMapper,\n [rpcEndowmentBuilder.targetName]: getRpcCaveatMapper,\n};\n\nexport const handlerEndowments: Record<HandlerType, string> = {\n [HandlerType.OnRpcRequest]: rpcEndowmentBuilder.targetName,\n [HandlerType.OnTransaction]: transactionInsightEndowmentBuilder.targetName,\n [HandlerType.OnCronjob]: cronjobEndowmentBuilder.targetName,\n};\n\nexport * from './enum';\nexport { getRpcCaveatOrigins } from './rpc';\nexport { getTransactionOriginCaveat } from './transaction-insight';\n"],"names":["endowmentPermissionBuilders","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","getRpcCaveatOrigins","getTransactionOriginCaveat","networkAccessEndowmentBuilder","targetName","longRunningEndowmentBuilder","transactionInsightEndowmentBuilder","cronjobEndowmentBuilder","ethereumProviderEndowmentBuilder","rpcEndowmentBuilder","webAssemblyEndowmentBuilder","cronjobCaveatSpecifications","transactionInsightCaveatSpecifications","rpcCaveatSpecifications","getCronjobCaveatMapper","getTransactionInsightCaveatMapper","getRpcCaveatMapper","HandlerType","OnRpcRequest","OnTransaction","OnCronjob"],"mappings":";;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/endowments/index.ts"],"sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\n\nimport {\n cronjobCaveatSpecifications,\n cronjobEndowmentBuilder,\n getCronjobCaveatMapper,\n} from './cronjob';\nimport { ethereumProviderEndowmentBuilder } from './ethereum-provider';\nimport { lifecycleHooksEndowmentBuilder } from './lifecycle-hooks';\nimport { longRunningEndowmentBuilder } from './long-running';\nimport { networkAccessEndowmentBuilder } from './network-access';\nimport {\n getRpcCaveatMapper,\n rpcCaveatSpecifications,\n rpcEndowmentBuilder,\n} from './rpc';\nimport {\n getTransactionInsightCaveatMapper,\n transactionInsightCaveatSpecifications,\n transactionInsightEndowmentBuilder,\n} from './transaction-insight';\nimport { webAssemblyEndowmentBuilder } from './web-assembly';\n\nexport const endowmentPermissionBuilders = {\n [networkAccessEndowmentBuilder.targetName]: networkAccessEndowmentBuilder,\n [longRunningEndowmentBuilder.targetName]: longRunningEndowmentBuilder,\n [transactionInsightEndowmentBuilder.targetName]:\n transactionInsightEndowmentBuilder,\n [cronjobEndowmentBuilder.targetName]: cronjobEndowmentBuilder,\n [ethereumProviderEndowmentBuilder.targetName]:\n ethereumProviderEndowmentBuilder,\n [rpcEndowmentBuilder.targetName]: rpcEndowmentBuilder,\n [webAssemblyEndowmentBuilder.targetName]: webAssemblyEndowmentBuilder,\n [lifecycleHooksEndowmentBuilder.targetName]: lifecycleHooksEndowmentBuilder,\n} as const;\n\nexport const endowmentCaveatSpecifications = {\n ...cronjobCaveatSpecifications,\n ...transactionInsightCaveatSpecifications,\n ...rpcCaveatSpecifications,\n};\n\nexport const endowmentCaveatMappers: Record<\n string,\n (value: Json) => Pick<PermissionConstraint, 'caveats'>\n> = {\n [cronjobEndowmentBuilder.targetName]: getCronjobCaveatMapper,\n [transactionInsightEndowmentBuilder.targetName]:\n getTransactionInsightCaveatMapper,\n [rpcEndowmentBuilder.targetName]: getRpcCaveatMapper,\n};\n\nexport const handlerEndowments: Record<HandlerType, string> = {\n [HandlerType.OnRpcRequest]: rpcEndowmentBuilder.targetName,\n [HandlerType.OnTransaction]: transactionInsightEndowmentBuilder.targetName,\n [HandlerType.OnCronjob]: cronjobEndowmentBuilder.targetName,\n [HandlerType.OnInstall]: lifecycleHooksEndowmentBuilder.targetName,\n [HandlerType.OnUpdate]: lifecycleHooksEndowmentBuilder.targetName,\n};\n\nexport * from './enum';\nexport { getRpcCaveatOrigins } from './rpc';\nexport { getTransactionOriginCaveat } from './transaction-insight';\n"],"names":["endowmentPermissionBuilders","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","getRpcCaveatOrigins","getTransactionOriginCaveat","networkAccessEndowmentBuilder","targetName","longRunningEndowmentBuilder","transactionInsightEndowmentBuilder","cronjobEndowmentBuilder","ethereumProviderEndowmentBuilder","rpcEndowmentBuilder","webAssemblyEndowmentBuilder","lifecycleHooksEndowmentBuilder","cronjobCaveatSpecifications","transactionInsightCaveatSpecifications","rpcCaveatSpecifications","getCronjobCaveatMapper","getTransactionInsightCaveatMapper","getRpcCaveatMapper","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate"],"mappings":";;;;;;;;;;;IAyBaA,2BAA2B;eAA3BA;;IAaAC,6BAA6B;eAA7BA;;IAMAC,sBAAsB;eAAtBA;;IAUAC,iBAAiB;eAAjBA;;IASJC,mBAAmB;eAAnBA,wBAAmB;;IACnBC,0BAA0B;eAA1BA,8CAA0B;;;4BA/DP;yBAOrB;kCAC0C;gCACF;6BACH;+BACE;qBAKvC;oCAKA;6BACqC;qBAuC9B;;;;;;;;;;;;;;AArCP,MAAML,8BAA8B;IACzC,CAACM,4CAA6B,CAACC,UAAU,CAAC,EAAED,4CAA6B;IACzE,CAACE,wCAA2B,CAACD,UAAU,CAAC,EAAEC,wCAA2B;IACrE,CAACC,sDAAkC,CAACF,UAAU,CAAC,EAC7CE,sDAAkC;IACpC,CAACC,gCAAuB,CAACH,UAAU,CAAC,EAAEG,gCAAuB;IAC7D,CAACC,kDAAgC,CAACJ,UAAU,CAAC,EAC3CI,kDAAgC;IAClC,CAACC,wBAAmB,CAACL,UAAU,CAAC,EAAEK,wBAAmB;IACrD,CAACC,wCAA2B,CAACN,UAAU,CAAC,EAAEM,wCAA2B;IACrE,CAACC,8CAA8B,CAACP,UAAU,CAAC,EAAEO,8CAA8B;AAC7E;AAEO,MAAMb,gCAAgC;IAC3C,GAAGc,oCAA2B;IAC9B,GAAGC,0DAAsC;IACzC,GAAGC,4BAAuB;AAC5B;AAEO,MAAMf,yBAGT;IACF,CAACQ,gCAAuB,CAACH,UAAU,CAAC,EAAEW,+BAAsB;IAC5D,CAACT,sDAAkC,CAACF,UAAU,CAAC,EAC7CY,qDAAiC;IACnC,CAACP,wBAAmB,CAACL,UAAU,CAAC,EAAEa,uBAAkB;AACtD;AAEO,MAAMjB,oBAAiD;IAC5D,CAACkB,uBAAW,CAACC,YAAY,CAAC,EAAEV,wBAAmB,CAACL,UAAU;IAC1D,CAACc,uBAAW,CAACE,aAAa,CAAC,EAAEd,sDAAkC,CAACF,UAAU;IAC1E,CAACc,uBAAW,CAACG,SAAS,CAAC,EAAEd,gCAAuB,CAACH,UAAU;IAC3D,CAACc,uBAAW,CAACI,SAAS,CAAC,EAAEX,8CAA8B,CAACP,UAAU;IAClE,CAACc,uBAAW,CAACK,QAAQ,CAAC,EAAEZ,8CAA8B,CAACP,UAAU;AACnE"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "lifecycleHooksEndowmentBuilder", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return lifecycleHooksEndowmentBuilder;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
const _permissioncontroller = require("@metamask/permission-controller");
|
|
12
|
+
const _enum = require("./enum");
|
|
13
|
+
const permissionName = _enum.SnapEndowments.LifecycleHooks;
|
|
14
|
+
/**
|
|
15
|
+
* `endowment:lifecycle-hooks` returns nothing; it is intended to be used as a
|
|
16
|
+
* flag by the snap controller to detect whether the snap has the capability to
|
|
17
|
+
* use lifecycle hooks.
|
|
18
|
+
*
|
|
19
|
+
* @param _builderOptions - Optional specification builder options.
|
|
20
|
+
* @returns The specification for the `lifecycle-hooks` endowment.
|
|
21
|
+
*/ const specificationBuilder = (_builderOptions)=>{
|
|
22
|
+
return {
|
|
23
|
+
permissionType: _permissioncontroller.PermissionType.Endowment,
|
|
24
|
+
targetName: permissionName,
|
|
25
|
+
allowedCaveats: null,
|
|
26
|
+
endowmentGetter: (_getterOptions)=>undefined,
|
|
27
|
+
subjectTypes: [
|
|
28
|
+
_permissioncontroller.SubjectType.Snap
|
|
29
|
+
]
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
const lifecycleHooksEndowmentBuilder = Object.freeze({
|
|
33
|
+
targetName: permissionName,
|
|
34
|
+
specificationBuilder
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
//# sourceMappingURL=lifecycle-hooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/endowments/lifecycle-hooks.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n EndowmentGetterParams,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport type { NonEmptyArray } from '@metamask/utils';\n\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.LifecycleHooks;\n\ntype LifecycleHooksEndowmentSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.Endowment;\n targetName: typeof permissionName;\n endowmentGetter: (_options?: EndowmentGetterParams) => undefined;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * `endowment:lifecycle-hooks` returns nothing; it is intended to be used as a\n * flag by the snap controller to detect whether the snap has the capability to\n * use lifecycle hooks.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the `lifecycle-hooks` endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n LifecycleHooksEndowmentSpecification\n> = (_builderOptions?: unknown) => {\n return {\n permissionType: PermissionType.Endowment,\n targetName: permissionName,\n allowedCaveats: null,\n endowmentGetter: (_getterOptions?: EndowmentGetterParams) => undefined,\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nexport const lifecycleHooksEndowmentBuilder = Object.freeze({\n targetName: permissionName,\n specificationBuilder,\n} as const);\n"],"names":["lifecycleHooksEndowmentBuilder","permissionName","SnapEndowments","LifecycleHooks","specificationBuilder","_builderOptions","permissionType","PermissionType","Endowment","targetName","allowedCaveats","endowmentGetter","_getterOptions","undefined","subjectTypes","SubjectType","Snap","Object","freeze"],"mappings":";;;;+BAyCaA;;;eAAAA;;;sCApC+B;sBAGb;AAE/B,MAAMC,iBAAiBC,oBAAc,CAACC,cAAc;AASpD;;;;;;;CAOC,GACD,MAAMC,uBAIF,CAACC;IACH,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,SAAS;QACxCC,YAAYR;QACZS,gBAAgB;QAChBC,iBAAiB,CAACC,iBAA2CC;QAC7DC,cAAc;YAACC,iCAAW,CAACC,IAAI;SAAC;IAClC;AACF;AAEO,MAAMhB,iCAAiCiB,OAAOC,MAAM,CAAC;IAC1DT,YAAYR;IACZG;AACF"}
|
|
@@ -70,7 +70,7 @@ const defaultState = {
|
|
|
70
70
|
database: null,
|
|
71
71
|
lastUpdated: null
|
|
72
72
|
};
|
|
73
|
-
var _url = /*#__PURE__*/ new WeakMap(), _publicKey = /*#__PURE__*/ new WeakMap(), _fetchFunction = /*#__PURE__*/ new WeakMap(), _recentFetchThreshold = /*#__PURE__*/ new WeakMap(), _refetchOnAllowlistMiss = /*#__PURE__*/ new WeakMap(), _failOnUnavailableRegistry = /*#__PURE__*/ new WeakMap(), _wasRecentlyFetched = /*#__PURE__*/ new WeakSet(),
|
|
73
|
+
var _url = /*#__PURE__*/ new WeakMap(), _publicKey = /*#__PURE__*/ new WeakMap(), _fetchFunction = /*#__PURE__*/ new WeakMap(), _recentFetchThreshold = /*#__PURE__*/ new WeakMap(), _refetchOnAllowlistMiss = /*#__PURE__*/ new WeakMap(), _failOnUnavailableRegistry = /*#__PURE__*/ new WeakMap(), _currentUpdate = /*#__PURE__*/ new WeakMap(), _wasRecentlyFetched = /*#__PURE__*/ new WeakSet(), _triggerUpdate = /*#__PURE__*/ new WeakSet(), _update = /*#__PURE__*/ new WeakSet(), _getDatabase = /*#__PURE__*/ new WeakSet(), _getSingle = /*#__PURE__*/ new WeakSet(), _get = /*#__PURE__*/ new WeakSet(), _getMetadata = /*#__PURE__*/ new WeakSet(), _verifySignature = /*#__PURE__*/ new WeakSet(), _safeFetch = /*#__PURE__*/ new WeakSet();
|
|
74
74
|
class JsonSnapsRegistry extends _basecontroller.BaseControllerV2 {
|
|
75
75
|
constructor({ messenger, state, url = {
|
|
76
76
|
registry: SNAP_REGISTRY_URL,
|
|
@@ -95,7 +95,16 @@ class JsonSnapsRegistry extends _basecontroller.BaseControllerV2 {
|
|
|
95
95
|
}
|
|
96
96
|
});
|
|
97
97
|
_class_private_method_init(this, _wasRecentlyFetched);
|
|
98
|
-
|
|
98
|
+
/**
|
|
99
|
+
* Triggers an update of the registry database.
|
|
100
|
+
*
|
|
101
|
+
* If an existing update is in progress this function will await that update.
|
|
102
|
+
*/ _class_private_method_init(this, _triggerUpdate);
|
|
103
|
+
/**
|
|
104
|
+
* Updates the registry database if the registry hasn't been updated recently.
|
|
105
|
+
*
|
|
106
|
+
* NOTE: SHOULD NOT be called directly, instead `triggerUpdate` should be used.
|
|
107
|
+
*/ _class_private_method_init(this, _update);
|
|
99
108
|
_class_private_method_init(this, _getDatabase);
|
|
100
109
|
_class_private_method_init(this, _getSingle);
|
|
101
110
|
_class_private_method_init(this, _get);
|
|
@@ -145,20 +154,39 @@ class JsonSnapsRegistry extends _basecontroller.BaseControllerV2 {
|
|
|
145
154
|
writable: true,
|
|
146
155
|
value: void 0
|
|
147
156
|
});
|
|
157
|
+
_class_private_field_init(this, _currentUpdate, {
|
|
158
|
+
writable: true,
|
|
159
|
+
value: void 0
|
|
160
|
+
});
|
|
148
161
|
_class_private_field_set(this, _url, url);
|
|
149
162
|
_class_private_field_set(this, _publicKey, publicKey);
|
|
150
163
|
_class_private_field_set(this, _fetchFunction, fetchFunction);
|
|
151
164
|
_class_private_field_set(this, _recentFetchThreshold, recentFetchThreshold);
|
|
152
165
|
_class_private_field_set(this, _refetchOnAllowlistMiss, refetchOnAllowlistMiss);
|
|
153
166
|
_class_private_field_set(this, _failOnUnavailableRegistry, failOnUnavailableRegistry);
|
|
167
|
+
_class_private_field_set(this, _currentUpdate, null);
|
|
154
168
|
this.messagingSystem.registerActionHandler('SnapsRegistry:get', async (...args)=>_class_private_method_get(this, _get, get).call(this, ...args));
|
|
155
169
|
this.messagingSystem.registerActionHandler('SnapsRegistry:getMetadata', async (...args)=>_class_private_method_get(this, _getMetadata, getMetadata).call(this, ...args));
|
|
170
|
+
this.messagingSystem.registerActionHandler('SnapsRegistry:update', async ()=>_class_private_method_get(this, _triggerUpdate, triggerUpdate).call(this));
|
|
156
171
|
}
|
|
157
172
|
}
|
|
158
173
|
function wasRecentlyFetched() {
|
|
159
174
|
return this.state.lastUpdated && Date.now() - this.state.lastUpdated < _class_private_field_get(this, _recentFetchThreshold);
|
|
160
175
|
}
|
|
161
|
-
async function
|
|
176
|
+
async function triggerUpdate() {
|
|
177
|
+
// If an update is ongoing, wait for that.
|
|
178
|
+
if (_class_private_field_get(this, _currentUpdate)) {
|
|
179
|
+
await _class_private_field_get(this, _currentUpdate);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
// If no update exists, create promise and store globally.
|
|
183
|
+
if (_class_private_field_get(this, _currentUpdate) === null) {
|
|
184
|
+
_class_private_field_set(this, _currentUpdate, _class_private_method_get(this, _update, update).call(this));
|
|
185
|
+
}
|
|
186
|
+
await _class_private_field_get(this, _currentUpdate);
|
|
187
|
+
_class_private_field_set(this, _currentUpdate, null);
|
|
188
|
+
}
|
|
189
|
+
async function update() {
|
|
162
190
|
// No-op if we recently fetched the registry.
|
|
163
191
|
if (_class_private_method_get(this, _wasRecentlyFetched, wasRecentlyFetched).call(this)) {
|
|
164
192
|
return;
|
|
@@ -179,7 +207,7 @@ async function updateDatabase() {
|
|
|
179
207
|
}
|
|
180
208
|
async function getDatabase() {
|
|
181
209
|
if (this.state.database === null) {
|
|
182
|
-
await _class_private_method_get(this,
|
|
210
|
+
await _class_private_method_get(this, _triggerUpdate, triggerUpdate).call(this);
|
|
183
211
|
}
|
|
184
212
|
// If the database is still null and we require it, throw.
|
|
185
213
|
if (_class_private_field_get(this, _failOnUnavailableRegistry) && this.state.database === null) {
|
|
@@ -210,7 +238,7 @@ async function getSingle(snapId, snapInfo, refetch = false) {
|
|
|
210
238
|
}
|
|
211
239
|
// For now, if we have an allowlist miss, we can refetch once and try again.
|
|
212
240
|
if (_class_private_field_get(this, _refetchOnAllowlistMiss) && !refetch) {
|
|
213
|
-
await _class_private_method_get(this,
|
|
241
|
+
await _class_private_method_get(this, _triggerUpdate, triggerUpdate).call(this);
|
|
214
242
|
return _class_private_method_get(this, _getSingle, getSingle).call(this, snapId, snapInfo, true);
|
|
215
243
|
}
|
|
216
244
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/registry/json.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 as BaseController } from '@metamask/base-controller';\nimport type { SnapsRegistryDatabase } from '@metamask/snaps-registry';\nimport { verify } from '@metamask/snaps-registry';\nimport type { SnapId } from '@metamask/snaps-utils';\nimport type { Hex } from '@metamask/utils';\nimport {\n assert,\n Duration,\n inMilliseconds,\n satisfiesVersionRange,\n} from '@metamask/utils';\n\nimport type {\n SnapsRegistry,\n SnapsRegistryInfo,\n SnapsRegistryMetadata,\n SnapsRegistryRequest,\n SnapsRegistryResult,\n} from './registry';\nimport { SnapsRegistryStatus } from './registry';\n\n// TODO: Replace with a Codefi URL\nconst SNAP_REGISTRY_URL =\n 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/registry.json';\n\nconst SNAP_REGISTRY_SIGNATURE_URL =\n 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/signature.json';\n\ntype JsonSnapsRegistryUrl = {\n registry: string;\n signature: string;\n};\n\nexport type JsonSnapsRegistryArgs = {\n messenger: SnapsRegistryMessenger;\n state?: SnapsRegistryState;\n fetchFunction?: typeof fetch;\n url?: JsonSnapsRegistryUrl;\n recentFetchThreshold?: number;\n refetchOnAllowlistMiss?: boolean;\n failOnUnavailableRegistry?: boolean;\n publicKey?: Hex;\n};\n\nexport type GetResult = {\n type: `${typeof controllerName}:get`;\n handler: SnapsRegistry['get'];\n};\n\nexport type GetMetadata = {\n type: `${typeof controllerName}:getMetadata`;\n handler: SnapsRegistry['getMetadata'];\n};\n\nexport type SnapsRegistryActions = GetResult | GetMetadata;\n\nexport type SnapsRegistryEvents = never;\n\nexport type SnapsRegistryMessenger = RestrictedControllerMessenger<\n 'SnapsRegistry',\n SnapsRegistryActions,\n SnapsRegistryEvents,\n SnapsRegistryActions['type'],\n SnapsRegistryEvents['type']\n>;\n\nexport type SnapsRegistryState = {\n database: SnapsRegistryDatabase | null;\n lastUpdated: number | null;\n};\n\nconst controllerName = 'SnapsRegistry';\n\nconst defaultState = {\n database: null,\n lastUpdated: null,\n};\n\nexport class JsonSnapsRegistry extends BaseController<\n typeof controllerName,\n SnapsRegistryState,\n SnapsRegistryMessenger\n> {\n #url: JsonSnapsRegistryUrl;\n\n #publicKey?: Hex;\n\n #fetchFunction: typeof fetch;\n\n #recentFetchThreshold: number;\n\n #refetchOnAllowlistMiss: boolean;\n\n #failOnUnavailableRegistry: boolean;\n\n constructor({\n messenger,\n state,\n url = {\n registry: SNAP_REGISTRY_URL,\n signature: SNAP_REGISTRY_SIGNATURE_URL,\n },\n publicKey,\n fetchFunction = globalThis.fetch.bind(globalThis),\n recentFetchThreshold = inMilliseconds(5, Duration.Minute),\n failOnUnavailableRegistry = true,\n refetchOnAllowlistMiss = true,\n }: JsonSnapsRegistryArgs) {\n super({\n messenger,\n metadata: {\n database: { persist: true, anonymous: false },\n lastUpdated: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n ...defaultState,\n ...state,\n },\n });\n this.#url = url;\n this.#publicKey = publicKey;\n this.#fetchFunction = fetchFunction;\n this.#recentFetchThreshold = recentFetchThreshold;\n this.#refetchOnAllowlistMiss = refetchOnAllowlistMiss;\n this.#failOnUnavailableRegistry = failOnUnavailableRegistry;\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:get',\n async (...args) => this.#get(...args),\n );\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:getMetadata',\n async (...args) => this.#getMetadata(...args),\n );\n }\n\n #wasRecentlyFetched() {\n return (\n this.state.lastUpdated &&\n Date.now() - this.state.lastUpdated < this.#recentFetchThreshold\n );\n }\n\n async #updateDatabase() {\n // No-op if we recently fetched the registry.\n if (this.#wasRecentlyFetched()) {\n return;\n }\n\n try {\n const database = await this.#safeFetch(this.#url.registry);\n\n if (this.#publicKey) {\n const signature = await this.#safeFetch(this.#url.signature);\n await this.#verifySignature(database, signature);\n }\n\n this.update((state) => {\n state.database = JSON.parse(database);\n state.lastUpdated = Date.now();\n });\n } catch {\n // Ignore\n }\n }\n\n async #getDatabase(): Promise<SnapsRegistryDatabase | null> {\n if (this.state.database === null) {\n await this.#updateDatabase();\n }\n\n // If the database is still null and we require it, throw.\n if (this.#failOnUnavailableRegistry && this.state.database === null) {\n throw new Error('Snaps registry is unavailable, installation blocked.');\n }\n return this.state.database;\n }\n\n async #getSingle(\n snapId: SnapId,\n snapInfo: SnapsRegistryInfo,\n refetch = false,\n ): Promise<SnapsRegistryResult> {\n const database = await this.#getDatabase();\n\n const blockedEntry = database?.blockedSnaps.find((blocked) => {\n if ('id' in blocked) {\n return (\n blocked.id === snapId &&\n satisfiesVersionRange(snapInfo.version, blocked.versionRange)\n );\n }\n\n return blocked.checksum === snapInfo.checksum;\n });\n\n if (blockedEntry) {\n return {\n status: SnapsRegistryStatus.Blocked,\n reason: blockedEntry.reason,\n };\n }\n\n const verified = database?.verifiedSnaps[snapId];\n const version = verified?.versions?.[snapInfo.version];\n if (version && version.checksum === snapInfo.checksum) {\n return { status: SnapsRegistryStatus.Verified };\n }\n // For now, if we have an allowlist miss, we can refetch once and try again.\n if (this.#refetchOnAllowlistMiss && !refetch) {\n await this.#updateDatabase();\n return this.#getSingle(snapId, snapInfo, true);\n }\n return { status: SnapsRegistryStatus.Unverified };\n }\n\n async #get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<SnapId, SnapsRegistryResult>> {\n return Object.entries(snaps).reduce<\n Promise<Record<SnapId, SnapsRegistryResult>>\n >(async (previousPromise, [snapId, snapInfo]) => {\n const result = await this.#getSingle(snapId, snapInfo);\n const acc = await previousPromise;\n acc[snapId] = result;\n return acc;\n }, Promise.resolve({}));\n }\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n async #getMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null> {\n const database = await this.#getDatabase();\n return database?.verifiedSnaps[snapId]?.metadata ?? null;\n }\n\n /**\n * Verify the signature of the registry.\n *\n * @param database - The registry database.\n * @param signature - The signature of the registry.\n * @throws If the signature is invalid.\n * @private\n */\n async #verifySignature(database: string, signature: string) {\n assert(this.#publicKey, 'No public key provided.');\n\n const valid = await verify({\n registry: database,\n signature: JSON.parse(signature),\n publicKey: this.#publicKey,\n });\n\n assert(valid, 'Invalid registry signature.');\n }\n\n /**\n * Fetch the given URL, throwing if the response is not OK.\n *\n * @param url - The URL to fetch.\n * @returns The response body.\n * @private\n */\n async #safeFetch(url: string) {\n const response = await this.#fetchFunction(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}.`);\n }\n\n return await response.text();\n }\n}\n"],"names":["JsonSnapsRegistry","SNAP_REGISTRY_URL","SNAP_REGISTRY_SIGNATURE_URL","controllerName","defaultState","database","lastUpdated","BaseController","constructor","messenger","state","url","registry","signature","publicKey","fetchFunction","globalThis","fetch","bind","recentFetchThreshold","inMilliseconds","Duration","Minute","failOnUnavailableRegistry","refetchOnAllowlistMiss","metadata","persist","anonymous","name","messagingSystem","registerActionHandler","args","get","getMetadata","Date","now","wasRecentlyFetched","safeFetch","verifySignature","update","JSON","parse","updateDatabase","Error","snapId","snapInfo","refetch","getDatabase","blockedEntry","blockedSnaps","find","blocked","id","satisfiesVersionRange","version","versionRange","checksum","status","SnapsRegistryStatus","Blocked","reason","verified","verifiedSnaps","versions","Verified","getSingle","Unverified","snaps","Object","entries","reduce","previousPromise","result","acc","Promise","resolve","assert","valid","verify","response","ok","text"],"mappings":";;;;+BA+EaA;;;eAAAA;;;gCA9EsC;+BAE5B;uBAQhB;0BAS6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpC,kCAAkC;AAClC,MAAMC,oBACJ;AAEF,MAAMC,8BACJ;AA6CF,MAAMC,iBAAiB;AAEvB,MAAMC,eAAe;IACnBC,UAAU;IACVC,aAAa;AACf;IAOE,oCAEA,0CAEA,8CAEA,qDAEA,uDAEA,0DA4CA,mDAOM,+CAuBA,4CAYA,0CAsCA,oCAoBA,4CAaA,gDAmBA;AA/LD,MAAMN,0BAA0BO,gCAAc;IAiBnDC,YAAY,EACVC,SAAS,EACTC,KAAK,EACLC,MAAM;QACJC,UAAUX;QACVY,WAAWX;IACb,CAAC,EACDY,SAAS,EACTC,gBAAgBC,WAAWC,KAAK,CAACC,IAAI,CAACF,WAAW,EACjDG,uBAAuBC,IAAAA,qBAAc,E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2B,KAAKC,KAAK,CAAC5B;QACtBC,SAAS,2BAAE,IAAI,EAAEA;IACnB;IAEA8D,IAAAA,aAAM,EAACC,OAAO;AAChB;AASA,eAAA,UAAiBlE,GAAW;IAC1B,MAAMoE,WAAW,MAAM,yBAAA,IAAI,EAAEhE,qBAAN,IAAI,EAAgBJ;IAC3C,IAAI,CAACoE,SAASC,EAAE,EAAE;QAChB,MAAM,IAAIrC,MAAM,CAAC,gBAAgB,EAAEhC,IAAI,CAAC,CAAC;IAC3C;IAEA,OAAO,MAAMoE,SAASE,IAAI;AAC5B"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/registry/json.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 as BaseController } from '@metamask/base-controller';\nimport type { SnapsRegistryDatabase } from '@metamask/snaps-registry';\nimport { verify } from '@metamask/snaps-registry';\nimport type { SnapId } from '@metamask/snaps-utils';\nimport type { Hex } from '@metamask/utils';\nimport {\n assert,\n Duration,\n inMilliseconds,\n satisfiesVersionRange,\n} from '@metamask/utils';\n\nimport type {\n SnapsRegistry,\n SnapsRegistryInfo,\n SnapsRegistryMetadata,\n SnapsRegistryRequest,\n SnapsRegistryResult,\n} from './registry';\nimport { SnapsRegistryStatus } from './registry';\n\n// TODO: Replace with a Codefi URL\nconst SNAP_REGISTRY_URL =\n 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/registry.json';\n\nconst SNAP_REGISTRY_SIGNATURE_URL =\n 'https://cdn.jsdelivr.net/gh/MetaMask/snaps-registry@gh-pages/latest/signature.json';\n\ntype JsonSnapsRegistryUrl = {\n registry: string;\n signature: string;\n};\n\nexport type JsonSnapsRegistryArgs = {\n messenger: SnapsRegistryMessenger;\n state?: SnapsRegistryState;\n fetchFunction?: typeof fetch;\n url?: JsonSnapsRegistryUrl;\n recentFetchThreshold?: number;\n refetchOnAllowlistMiss?: boolean;\n failOnUnavailableRegistry?: boolean;\n publicKey?: Hex;\n};\n\nexport type GetResult = {\n type: `${typeof controllerName}:get`;\n handler: SnapsRegistry['get'];\n};\n\nexport type GetMetadata = {\n type: `${typeof controllerName}:getMetadata`;\n handler: SnapsRegistry['getMetadata'];\n};\n\nexport type Update = {\n type: `${typeof controllerName}:update`;\n handler: SnapsRegistry['update'];\n};\n\nexport type SnapsRegistryActions = GetResult | GetMetadata | Update;\n\nexport type SnapsRegistryEvents = never;\n\nexport type SnapsRegistryMessenger = RestrictedControllerMessenger<\n 'SnapsRegistry',\n SnapsRegistryActions,\n SnapsRegistryEvents,\n SnapsRegistryActions['type'],\n SnapsRegistryEvents['type']\n>;\n\nexport type SnapsRegistryState = {\n database: SnapsRegistryDatabase | null;\n lastUpdated: number | null;\n};\n\nconst controllerName = 'SnapsRegistry';\n\nconst defaultState = {\n database: null,\n lastUpdated: null,\n};\n\nexport class JsonSnapsRegistry extends BaseController<\n typeof controllerName,\n SnapsRegistryState,\n SnapsRegistryMessenger\n> {\n #url: JsonSnapsRegistryUrl;\n\n #publicKey?: Hex;\n\n #fetchFunction: typeof fetch;\n\n #recentFetchThreshold: number;\n\n #refetchOnAllowlistMiss: boolean;\n\n #failOnUnavailableRegistry: boolean;\n\n #currentUpdate: Promise<void> | null;\n\n constructor({\n messenger,\n state,\n url = {\n registry: SNAP_REGISTRY_URL,\n signature: SNAP_REGISTRY_SIGNATURE_URL,\n },\n publicKey,\n fetchFunction = globalThis.fetch.bind(globalThis),\n recentFetchThreshold = inMilliseconds(5, Duration.Minute),\n failOnUnavailableRegistry = true,\n refetchOnAllowlistMiss = true,\n }: JsonSnapsRegistryArgs) {\n super({\n messenger,\n metadata: {\n database: { persist: true, anonymous: false },\n lastUpdated: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n ...defaultState,\n ...state,\n },\n });\n this.#url = url;\n this.#publicKey = publicKey;\n this.#fetchFunction = fetchFunction;\n this.#recentFetchThreshold = recentFetchThreshold;\n this.#refetchOnAllowlistMiss = refetchOnAllowlistMiss;\n this.#failOnUnavailableRegistry = failOnUnavailableRegistry;\n this.#currentUpdate = null;\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:get',\n async (...args) => this.#get(...args),\n );\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:getMetadata',\n async (...args) => this.#getMetadata(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SnapsRegistry:update',\n async () => this.#triggerUpdate(),\n );\n }\n\n #wasRecentlyFetched() {\n return (\n this.state.lastUpdated &&\n Date.now() - this.state.lastUpdated < this.#recentFetchThreshold\n );\n }\n\n /**\n * Triggers an update of the registry database.\n *\n * If an existing update is in progress this function will await that update.\n */\n async #triggerUpdate() {\n // If an update is ongoing, wait for that.\n if (this.#currentUpdate) {\n await this.#currentUpdate;\n return;\n }\n // If no update exists, create promise and store globally.\n if (this.#currentUpdate === null) {\n this.#currentUpdate = this.#update();\n }\n await this.#currentUpdate;\n this.#currentUpdate = null;\n }\n\n /**\n * Updates the registry database if the registry hasn't been updated recently.\n *\n * NOTE: SHOULD NOT be called directly, instead `triggerUpdate` should be used.\n */\n async #update() {\n // No-op if we recently fetched the registry.\n if (this.#wasRecentlyFetched()) {\n return;\n }\n\n try {\n const database = await this.#safeFetch(this.#url.registry);\n\n if (this.#publicKey) {\n const signature = await this.#safeFetch(this.#url.signature);\n await this.#verifySignature(database, signature);\n }\n\n this.update((state) => {\n state.database = JSON.parse(database);\n state.lastUpdated = Date.now();\n });\n } catch {\n // Ignore\n }\n }\n\n async #getDatabase(): Promise<SnapsRegistryDatabase | null> {\n if (this.state.database === null) {\n await this.#triggerUpdate();\n }\n\n // If the database is still null and we require it, throw.\n if (this.#failOnUnavailableRegistry && this.state.database === null) {\n throw new Error('Snaps registry is unavailable, installation blocked.');\n }\n return this.state.database;\n }\n\n async #getSingle(\n snapId: SnapId,\n snapInfo: SnapsRegistryInfo,\n refetch = false,\n ): Promise<SnapsRegistryResult> {\n const database = await this.#getDatabase();\n\n const blockedEntry = database?.blockedSnaps.find((blocked) => {\n if ('id' in blocked) {\n return (\n blocked.id === snapId &&\n satisfiesVersionRange(snapInfo.version, blocked.versionRange)\n );\n }\n\n return blocked.checksum === snapInfo.checksum;\n });\n\n if (blockedEntry) {\n return {\n status: SnapsRegistryStatus.Blocked,\n reason: blockedEntry.reason,\n };\n }\n\n const verified = database?.verifiedSnaps[snapId];\n const version = verified?.versions?.[snapInfo.version];\n if (version && version.checksum === snapInfo.checksum) {\n return { status: SnapsRegistryStatus.Verified };\n }\n // For now, if we have an allowlist miss, we can refetch once and try again.\n if (this.#refetchOnAllowlistMiss && !refetch) {\n await this.#triggerUpdate();\n return this.#getSingle(snapId, snapInfo, true);\n }\n return { status: SnapsRegistryStatus.Unverified };\n }\n\n async #get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<SnapId, SnapsRegistryResult>> {\n return Object.entries(snaps).reduce<\n Promise<Record<SnapId, SnapsRegistryResult>>\n >(async (previousPromise, [snapId, snapInfo]) => {\n const result = await this.#getSingle(snapId, snapInfo);\n const acc = await previousPromise;\n acc[snapId] = result;\n return acc;\n }, Promise.resolve({}));\n }\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n async #getMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null> {\n const database = await this.#getDatabase();\n return database?.verifiedSnaps[snapId]?.metadata ?? null;\n }\n\n /**\n * Verify the signature of the registry.\n *\n * @param database - The registry database.\n * @param signature - The signature of the registry.\n * @throws If the signature is invalid.\n * @private\n */\n async #verifySignature(database: string, signature: string) {\n assert(this.#publicKey, 'No public key provided.');\n\n const valid = await verify({\n registry: database,\n signature: JSON.parse(signature),\n publicKey: this.#publicKey,\n });\n\n assert(valid, 'Invalid registry signature.');\n }\n\n /**\n * Fetch the given URL, throwing if the response is not OK.\n *\n * @param url - The URL to fetch.\n * @returns The response body.\n * @private\n */\n async #safeFetch(url: string) {\n const response = await this.#fetchFunction(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}.`);\n }\n\n return await response.text();\n }\n}\n"],"names":["JsonSnapsRegistry","SNAP_REGISTRY_URL","SNAP_REGISTRY_SIGNATURE_URL","controllerName","defaultState","database","lastUpdated","BaseController","constructor","messenger","state","url","registry","signature","publicKey","fetchFunction","globalThis","fetch","bind","recentFetchThreshold","inMilliseconds","Duration","Minute","failOnUnavailableRegistry","refetchOnAllowlistMiss","metadata","persist","anonymous","name","currentUpdate","messagingSystem","registerActionHandler","args","get","getMetadata","triggerUpdate","Date","now","update","wasRecentlyFetched","safeFetch","verifySignature","JSON","parse","Error","snapId","snapInfo","refetch","getDatabase","blockedEntry","blockedSnaps","find","blocked","id","satisfiesVersionRange","version","versionRange","checksum","status","SnapsRegistryStatus","Blocked","reason","verified","verifiedSnaps","versions","Verified","getSingle","Unverified","snaps","Object","entries","reduce","previousPromise","result","acc","Promise","resolve","assert","valid","verify","response","ok","text"],"mappings":";;;;+BAoFaA;;;eAAAA;;;gCAnFsC;+BAE5B;uBAQhB;0BAS6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpC,kCAAkC;AAClC,MAAMC,oBACJ;AAEF,MAAMC,8BACJ;AAkDF,MAAMC,iBAAiB;AAEvB,MAAMC,eAAe;IACnBC,UAAU;IACVC,aAAa;AACf;IAOE,oCAEA,0CAEA,8CAEA,qDAEA,uDAEA,0DAEA,8CAkDA,mDAYM,8CAmBA,uCAuBA,4CAYA,0CAsCA,oCAoBA,4CAaA,gDAmBA;AA/ND,MAAMN,0BAA0BO,gCAAc;IAmBnDC,YAAY,EACVC,SAAS,EACTC,KAAK,EACLC,MAAM;QACJC,UAAUX;QACVY,WAAWX;IACb,CAAC,EACDY,SAAS,EACTC,gBAAgBC,WAAWC,KAAK,CAACC,IAAI,CAACF,WAAW,EACjDG,uBAAuBC,IAAAA,qBAAc,EAAC,GAAGC,eAAQ,CAACC,MAA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AAMF;QAClBE,GAAG,CAAC7B,OAAO,GAAG4B;QACd,OAAOC;IACT,GAAGC,QAAQC,OAAO,CAAC,CAAC;AACtB;AASA,eAAA,YAAmB/B,MAAc;IAC/B,MAAMxC,WAAW,MAAM,0BAAA,IAAI,EAAE2C,cAAAA,kBAAN,IAAI;IAC3B,OAAO3C,UAAU0D,aAAa,CAAClB,OAAO,EAAEpB,YAAY;AACtD;AAUA,eAAA,gBAAuBpB,QAAgB,EAAEQ,SAAiB;IACxDgE,IAAAA,aAAM,2BAAC,IAAI,EAAE/D,aAAW;IAExB,MAAMgE,QAAQ,MAAMC,IAAAA,qBAAM,EAAC;QACzBnE,UAAUP;QACVQ,WAAW6B,KAAKC,KAAK,CAAC9B;QACtBC,SAAS,2BAAE,IAAI,EAAEA;IACnB;IAEA+D,IAAAA,aAAM,EAACC,OAAO;AAChB;AASA,eAAA,UAAiBnE,GAAW;IAC1B,MAAMqE,WAAW,MAAM,yBAAA,IAAI,EAAEjE,qBAAN,IAAI,EAAgBJ;IAC3C,IAAI,CAACqE,SAASC,EAAE,EAAE;QAChB,MAAM,IAAIrC,MAAM,CAAC,gBAAgB,EAAEjC,IAAI,CAAC,CAAC;IAC3C;IAEA,OAAO,MAAMqE,SAASE,IAAI;AAC5B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/snaps/registry/registry.ts"],"sourcesContent":["import type {\n BlockReason,\n SnapsRegistryDatabase,\n} from '@metamask/snaps-registry';\nimport type { SnapId, ValidatedSnapId } from '@metamask/snaps-utils';\nimport type { SemVerVersion } from '@metamask/utils';\n\nexport type SnapsRegistryInfo = { version: SemVerVersion; checksum: string };\nexport type SnapsRegistryRequest = Record<SnapId, SnapsRegistryInfo>;\nexport type SnapsRegistryMetadata =\n SnapsRegistryDatabase['verifiedSnaps'][ValidatedSnapId]['metadata'];\n\n// TODO: Decide on names for these\nexport enum SnapsRegistryStatus {\n Unverified = 0,\n Blocked = 1,\n Verified = 2,\n}\n\nexport type SnapsRegistryResult = {\n status: SnapsRegistryStatus;\n reason?: BlockReason;\n};\n\nexport type SnapsRegistry = {\n get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<ValidatedSnapId, SnapsRegistryResult>>;\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n getMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null>;\n};\n"],"names":["SnapsRegistryStatus","Unverified","Blocked","Verified"],"mappings":";;;;;;;;;;IAaO;UAAKA,mBAAmB;IAAnBA,oBAAAA,oBACVC,gBAAa,KAAbA;IADUD,oBAAAA,oBAEVE,aAAU,KAAVA;IAFUF,oBAAAA,oBAGVG,cAAW,KAAXA;GAHUH,wBAAAA"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/snaps/registry/registry.ts"],"sourcesContent":["import type {\n BlockReason,\n SnapsRegistryDatabase,\n} from '@metamask/snaps-registry';\nimport type { SnapId, ValidatedSnapId } from '@metamask/snaps-utils';\nimport type { SemVerVersion } from '@metamask/utils';\n\nexport type SnapsRegistryInfo = { version: SemVerVersion; checksum: string };\nexport type SnapsRegistryRequest = Record<SnapId, SnapsRegistryInfo>;\nexport type SnapsRegistryMetadata =\n SnapsRegistryDatabase['verifiedSnaps'][ValidatedSnapId]['metadata'];\n\n// TODO: Decide on names for these\nexport enum SnapsRegistryStatus {\n Unverified = 0,\n Blocked = 1,\n Verified = 2,\n}\n\nexport type SnapsRegistryResult = {\n status: SnapsRegistryStatus;\n reason?: BlockReason;\n};\n\nexport type SnapsRegistry = {\n get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<ValidatedSnapId, SnapsRegistryResult>>;\n\n update(): Promise<void>;\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n getMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null>;\n};\n"],"names":["SnapsRegistryStatus","Unverified","Blocked","Verified"],"mappings":";;;;;;;;;;IAaO;UAAKA,mBAAmB;IAAnBA,oBAAAA,oBACVC,gBAAa,KAAbA;IADUD,oBAAAA,oBAEVE,aAAU,KAAVA;IAFUF,oBAAAA,oBAGVG,cAAW,KAAXA;GAHUH,wBAAAA"}
|
|
@@ -71,17 +71,7 @@ import pump from 'pump';
|
|
|
71
71
|
import { log } from '../logging';
|
|
72
72
|
import { hasTimedOut, withTimeout } from '../utils';
|
|
73
73
|
const controllerName = 'ExecutionService';
|
|
74
|
-
var _snapRpcHooks = /*#__PURE__*/ new WeakMap(), _snapToJobMap = /*#__PURE__*/ new WeakMap(), _jobToSnapMap = /*#__PURE__*/ new WeakMap(), _messenger = /*#__PURE__*/ new WeakMap(), _terminationTimeout = /*#__PURE__*/ new WeakMap(), _removeSnapHooks = /*#__PURE__*/ new WeakSet(), _createSnapHooks = /*#__PURE__*/ new WeakSet(),
|
|
75
|
-
* Gets the job id for a given snap.
|
|
76
|
-
*
|
|
77
|
-
* @param snapId - A given snap id.
|
|
78
|
-
* @returns The ID of the snap's job.
|
|
79
|
-
*/ _getJobForSnap = /*#__PURE__*/ new WeakSet(), /**
|
|
80
|
-
* Gets the snap id for a given job.
|
|
81
|
-
*
|
|
82
|
-
* @param jobId - A given job id.
|
|
83
|
-
* @returns The ID of the snap that is running the job.
|
|
84
|
-
*/ _getSnapForJob = /*#__PURE__*/ new WeakSet(), _mapSnapAndJob = /*#__PURE__*/ new WeakSet(), _removeSnapAndJobMapping = /*#__PURE__*/ new WeakSet();
|
|
74
|
+
var _snapRpcHooks = /*#__PURE__*/ new WeakMap(), _snapToJobMap = /*#__PURE__*/ new WeakMap(), _jobToSnapMap = /*#__PURE__*/ new WeakMap(), _messenger = /*#__PURE__*/ new WeakMap(), _terminationTimeout = /*#__PURE__*/ new WeakMap(), _removeSnapHooks = /*#__PURE__*/ new WeakSet(), _createSnapHooks = /*#__PURE__*/ new WeakSet(), _mapSnapAndJob = /*#__PURE__*/ new WeakSet(), _removeSnapAndJobMapping = /*#__PURE__*/ new WeakSet();
|
|
85
75
|
export class AbstractExecutionService {
|
|
86
76
|
/**
|
|
87
77
|
* Constructor helper for registering the controller's messaging system
|
|
@@ -291,8 +281,6 @@ export class AbstractExecutionService {
|
|
|
291
281
|
constructor({ setupSnapProvider, messenger, terminationTimeout = Duration.Second }){
|
|
292
282
|
_class_private_method_init(this, _removeSnapHooks);
|
|
293
283
|
_class_private_method_init(this, _createSnapHooks);
|
|
294
|
-
_class_private_method_init(this, _getJobForSnap);
|
|
295
|
-
_class_private_method_init(this, _getSnapForJob);
|
|
296
284
|
_class_private_method_init(this, _mapSnapAndJob);
|
|
297
285
|
_class_private_method_init(this, _removeSnapAndJobMapping);
|
|
298
286
|
_class_private_field_init(this, _snapRpcHooks, {
|
|
@@ -348,12 +336,6 @@ function createSnapHooks(snapId, workerId) {
|
|
|
348
336
|
};
|
|
349
337
|
_class_private_field_get(this, _snapRpcHooks).set(snapId, rpcHook);
|
|
350
338
|
}
|
|
351
|
-
function getJobForSnap(snapId) {
|
|
352
|
-
return _class_private_field_get(this, _snapToJobMap).get(snapId);
|
|
353
|
-
}
|
|
354
|
-
function getSnapForJob(jobId) {
|
|
355
|
-
return _class_private_field_get(this, _jobToSnapMap).get(jobId);
|
|
356
|
-
}
|
|
357
339
|
function mapSnapAndJob(snapId, jobId) {
|
|
358
340
|
_class_private_field_get(this, _snapToJobMap).set(snapId, jobId);
|
|
359
341
|
_class_private_field_get(this, _jobToSnapMap).set(jobId, snapId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/AbstractExecutionService.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcNotification } from '@metamask/utils';\nimport { Duration, isJsonRpcNotification, isObject } from '@metamask/utils';\nimport type {\n // TODO: Replace with @metamask/utils version after bumping json-rpc-engine\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from 'json-rpc-engine';\nimport { JsonRpcEngine } from 'json-rpc-engine';\nimport { createStreamMiddleware } from 'json-rpc-middleware-stream';\nimport { nanoid } from 'nanoid';\nimport pump from 'pump';\nimport type { Duplex } from 'stream';\n\nimport { log } from '../logging';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\n\nconst controllerName = 'ExecutionService';\n\nexport type SetupSnapProvider = (snapId: string, stream: Duplex) => void;\n\nexport type ExecutionServiceArgs = {\n setupSnapProvider: SetupSnapProvider;\n messenger: ExecutionServiceMessenger;\n terminationTimeout?: number;\n};\n\nexport type JobStreams = {\n command: Duplex;\n rpc: Duplex;\n _connection: BasePostMessageStream;\n};\n\nexport type Job<WorkerType> = {\n id: string;\n streams: JobStreams;\n rpcEngine: JsonRpcEngine;\n worker: WorkerType;\n};\n\nexport abstract class AbstractExecutionService<WorkerType>\n implements ExecutionService\n{\n #snapRpcHooks: Map<string, SnapRpcHook>;\n\n // Cannot be hash private yet because of tests.\n protected jobs: Map<string, Job<WorkerType>>;\n\n // Cannot be hash private yet because of tests.\n private readonly setupSnapProvider: SetupSnapProvider;\n\n #snapToJobMap: Map<string, string>;\n\n #jobToSnapMap: Map<string, string>;\n\n #messenger: ExecutionServiceMessenger;\n\n #terminationTimeout: number;\n\n constructor({\n setupSnapProvider,\n messenger,\n terminationTimeout = Duration.Second,\n }: ExecutionServiceArgs) {\n this.#snapRpcHooks = new Map();\n this.jobs = new Map();\n this.setupSnapProvider = setupSnapProvider;\n this.#snapToJobMap = new Map();\n this.#jobToSnapMap = new Map();\n this.#messenger = messenger;\n this.#terminationTimeout = terminationTimeout;\n\n this.registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.#messenger.registerActionHandler(\n `${controllerName}:handleRpcRequest`,\n async (snapId: string, options: SnapRpcHookArgs) =>\n this.handleRpcRequest(snapId, options),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:executeSnap`,\n async (snapData: SnapExecutionData) => this.executeSnap(snapData),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateSnap`,\n async (snapId: string) => this.terminateSnap(snapId),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateAllSnaps`,\n async () => this.terminateAllSnaps(),\n );\n }\n\n /**\n * Performs additional necessary work during job termination. **MUST** be\n * implemented by concrete implementations. See\n * {@link AbstractExecutionService.terminate} for details.\n *\n * @param job - The object corresponding to the job to be terminated.\n */\n protected abstract terminateJob(job: Job<WorkerType>): void;\n\n /**\n * Terminates the job with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the job will fail with an error.\n * Throws an error if the specified job does not exist, or if termination\n * fails unexpectedly.\n *\n * @param jobId - The id of the job to be terminated.\n */\n public async terminate(jobId: string): Promise<void> {\n const jobWrapper = this.jobs.get(jobId);\n if (!jobWrapper) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n // Ping worker and tell it to run teardown, continue with termination if it takes too long\n const result = await withTimeout(\n this.command(jobId, {\n jsonrpc: '2.0',\n method: 'terminate',\n params: [],\n id: nanoid(),\n }),\n this.#terminationTimeout,\n );\n\n if (result === hasTimedOut || result !== 'OK') {\n // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and\n // hogging down the whole JS process.\n // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour\n // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same\n // JS process.\n logError(`Job \"${jobId}\" failed to terminate gracefully.`, result);\n }\n\n Object.values(jobWrapper.streams).forEach((stream) => {\n try {\n !stream.destroyed && stream.destroy();\n stream.removeAllListeners();\n } catch (error) {\n logError('Error while destroying stream', error);\n }\n });\n\n this.terminateJob(jobWrapper);\n\n this.#removeSnapAndJobMapping(jobId);\n this.jobs.delete(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @returns Information regarding the created job.\n */\n protected async initJob(): Promise<Job<WorkerType>> {\n const jobId = nanoid();\n const { streams, worker } = await this.initStreams(jobId);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pump(jsonRpcConnection.stream, streams.command, jsonRpcConnection.stream);\n\n rpcEngine.push(jsonRpcConnection.middleware);\n\n const envMetadata = {\n id: jobId,\n streams,\n rpcEngine,\n worker,\n };\n this.jobs.set(jobId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param jobId - The id of the job.\n * @returns The streams to communicate with the worker and the worker itself.\n */\n protected async initStreams(\n jobId: string,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const { worker, stream: envStream } = await this.initEnvStream(jobId);\n // Typecast justification: stream type mismatch\n const mux = setupMultiplex(\n envStream as unknown as Duplex,\n `Job: \"${jobId}\"`,\n );\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n\n // Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.\n // Also keep track of outbound request/responses\n const notificationHandler = (\n message:\n | JsonRpcRequest<unknown>\n | JsonRpcNotification<Json[] | Record<string, Json>>,\n ) => {\n if (!isJsonRpcNotification(message)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const snapId = this.#jobToSnapMap.get(jobId)!;\n if (message.method === 'OutboundRequest') {\n this.#messenger.publish('ExecutionService:outboundRequest', snapId);\n } else if (message.method === 'OutboundResponse') {\n this.#messenger.publish('ExecutionService:outboundResponse', snapId);\n } else if (message.method === 'UnhandledError') {\n if (isObject(message.params) && message.params.error) {\n this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n message.params.error as SnapErrorJson,\n );\n commandStream.removeListener('data', notificationHandler);\n } else {\n logError(\n new Error(\n `Received malformed \"${message.method}\" command stream notification.`,\n ),\n );\n }\n } else {\n logError(\n new Error(\n `Received unexpected command stream notification \"${message.method}\".`,\n ),\n );\n }\n };\n\n commandStream.on('data', notificationHandler);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n // Typecast: stream type mismatch\n return {\n streams: {\n command: commandStream as unknown as Duplex,\n rpc: rpcStream,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n _connection: envStream,\n },\n worker,\n };\n }\n\n /**\n * Abstract function implemented by implementing class that spins up a new worker for a job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n */\n protected abstract initEnvStream(jobId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n /**\n * Terminates the Snap with the specified ID. May throw an error if\n * termination unexpectedly fails, but will not fail if no job for the snap\n * with the specified ID is found.\n *\n * @param snapId - The ID of the snap to terminate.\n */\n async terminateSnap(snapId: string) {\n const jobId = this.#snapToJobMap.get(snapId);\n if (jobId) {\n await this.terminate(jobId);\n }\n }\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)),\n );\n this.#snapRpcHooks.clear();\n }\n\n /**\n * Gets the RPC request handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC request handler for the snap.\n */\n private getRpcRequestHandler(snapId: string) {\n return this.#snapRpcHooks.get(snapId);\n }\n\n /**\n * Initializes and executes a snap, setting up the communication channels to the snap etc.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param snapData - Data needed for Snap execution.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error.\n */\n async executeSnap(snapData: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapData.snapId)) {\n throw new Error(`Snap \"${snapData.snapId}\" is already being executed.`);\n }\n\n const job = await this.initJob();\n this.#mapSnapAndJob(snapData.snapId, job.id);\n\n // Ping the worker to ensure that it started up\n await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n });\n\n const rpcStream = job.streams.rpc as unknown as Duplex;\n\n this.setupSnapProvider(snapData.snapId, rpcStream);\n\n const result = await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: snapData,\n id: nanoid(),\n });\n this.#createSnapHooks(snapData.snapId, job.id);\n return result as string;\n }\n\n // Cannot be hash private yet because of tests.\n private async command(\n jobId: string,\n message: JsonRpcRequest<unknown>,\n ): Promise<unknown> {\n if (typeof message !== 'object') {\n throw new Error('Must send object.');\n }\n\n const job = this.jobs.get(jobId);\n if (!job) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n log('Parent: Sending Command', message);\n const response: PendingJsonRpcResponse<unknown> =\n await job.rpcEngine.handle(message);\n if (response.error) {\n throw new Error(response.error.message);\n }\n return response.result;\n }\n\n #removeSnapHooks(snapId: string) {\n this.#snapRpcHooks.delete(snapId);\n }\n\n #createSnapHooks(snapId: string, workerId: string) {\n const rpcHook = async ({ origin, handler, request }: SnapRpcHookArgs) => {\n return await this.command(workerId, {\n id: nanoid(),\n jsonrpc: '2.0',\n method: 'snapRpc',\n params: {\n origin,\n handler,\n request,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n /**\n * Gets the job id for a given snap.\n *\n * @param snapId - A given snap id.\n * @returns The ID of the snap's job.\n */\n #getJobForSnap(snapId: string): string | undefined {\n return this.#snapToJobMap.get(snapId);\n }\n\n /**\n * Gets the snap id for a given job.\n *\n * @param jobId - A given job id.\n * @returns The ID of the snap that is running the job.\n */\n #getSnapForJob(jobId: string): string | undefined {\n return this.#jobToSnapMap.get(jobId);\n }\n\n #mapSnapAndJob(snapId: string, jobId: string): void {\n this.#snapToJobMap.set(snapId, jobId);\n this.#jobToSnapMap.set(jobId, snapId);\n }\n\n #removeSnapAndJobMapping(jobId: string): void {\n const snapId = this.#jobToSnapMap.get(jobId);\n if (!snapId) {\n throw new Error(`job: \"${jobId}\" has no mapped snap.`);\n }\n\n this.#jobToSnapMap.delete(jobId);\n this.#snapToJobMap.delete(snapId);\n this.#removeSnapHooks(snapId);\n }\n\n /**\n * Handle RPC request.\n *\n * @param snapId - The ID of the recipient snap.\n * @param options - Bag of options to pass to the RPC handler.\n * @returns Promise that can handle the request.\n */\n public async handleRpcRequest(\n snapId: string,\n options: SnapRpcHookArgs,\n ): Promise<unknown> {\n const rpcRequestHandler = await this.getRpcRequestHandler(snapId);\n\n if (!rpcRequestHandler) {\n throw new Error(\n `Snap execution service returned no RPC handler for running snap \"${snapId}\".`,\n );\n }\n\n return rpcRequestHandler(options);\n }\n}\n\n/**\n * Sets up stream multiplexing for the given stream.\n *\n * @param connectionStream - The stream to mux.\n * @param streamName - The name of the stream, for identification in errors.\n * @returns The multiplexed stream.\n */\nexport function setupMultiplex(\n connectionStream: Duplex,\n streamName: string,\n): ObjectMultiplex {\n const mux = new ObjectMultiplex();\n pump(\n connectionStream,\n // Typecast: stream type mismatch\n mux as unknown as Duplex,\n connectionStream,\n (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n },\n );\n return mux;\n}\n"],"names":["ObjectMultiplex","SNAP_STREAM_NAMES","logError","Duration","isJsonRpcNotification","isObject","JsonRpcEngine","createStreamMiddleware","nanoid","pump","log","hasTimedOut","withTimeout","controllerName","AbstractExecutionService","registerMessageHandlers","messenger","registerActionHandler","snapId","options","handleRpcRequest","snapData","executeSnap","terminateSnap","terminateAllSnaps","terminate","jobId","jobWrapper","jobs","get","Error","result","command","jsonrpc","method","params","id","terminationTimeout","Object","values","streams","forEach","stream","destroyed","destroy","removeAllListeners","error","terminateJob","removeSnapAndJobMapping","delete","initJob","worker","initStreams","rpcEngine","jsonRpcConnection","push","middleware","envMetadata","set","envStream","initEnvStream","mux","setupMultiplex","commandStream","createStream","COMMAND","notificationHandler","message","jobToSnapMap","publish","removeListener","on","rpcStream","JSON_RPC","rpc","_connection","snapToJobMap","Promise","all","keys","map","snapRpcHooks","clear","getRpcRequestHandler","has","job","mapSnapAndJob","setupSnapProvider","createSnapHooks","response","handle","rpcRequestHandler","constructor","Second","Map","workerId","rpcHook","origin","handler","request","target","removeSnapHooks","connectionStream","streamName"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,qBAAqB,6BAA6B;AAGzD,SAASC,iBAAiB,EAAEC,QAAQ,QAAQ,wBAAwB;AAEpE,SAASC,QAAQ,EAAEC,qBAAqB,EAAEC,QAAQ,QAAQ,kBAAkB;AAM5E,SAASC,aAAa,QAAQ,kBAAkB;AAChD,SAASC,sBAAsB,QAAQ,6BAA6B;AACpE,SAASC,MAAM,QAAQ,SAAS;AAChC,OAAOC,UAAU,OAAO;AAGxB,SAASC,GAAG,QAAQ,aAAa;AACjC,SAASC,WAAW,EAAEC,WAAW,QAAQ,WAAW;AAQpD,MAAMC,iBAAiB;IA0BrB,6CAQA,6CAEA,6CAEA,0CAEA,mDAuTA,gDAIA,gDAkBA;;;;;GAKC,GACD,8CAIA;;;;;GAKC,GACD,8CAIA,8CAKA;AAvXF,OAAO,MAAeC;IAmCpB;;;GAGC,GACD,AAAQC,0BAAgC;QACtC,yBAAA,IAAI,EAAEC,YAAUC,qBAAqB,CACnC,CAAC,EAAEJ,eAAe,iBAAiB,CAAC,EACpC,OAAOK,QAAgBC,UACrB,IAAI,CAACC,gBAAgB,C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JyB,SAAS;YACTC,QAAQ;YACRC,QAAQ;gBACN8D;gBACAC;gBACAC;gBACAC,QAAQlF;YACV;QACF;IACF;IAEA,yBAAA,IAAI,EAAE+D,eAAavB,GAAG,CAACxC,QAAQ8E;AACjC;AAQA,SAAA,cAAe9E,MAAc;IAC3B,OAAO,yBAAA,IAAI,EAAE0D,eAAa/C,GAAG,CAACX;AAChC;AAQA,SAAA,cAAeQ,KAAa;IAC1B,OAAO,yBAAA,IAAI,EAAE0C,eAAavC,GAAG,CAACH;AAChC;AAEA,SAAA,cAAeR,MAAc,EAAEQ,KAAa;IAC1C,yBAAA,IAAI,EAAEkD,eAAalB,GAAG,CAACxC,QAAQQ;IAC/B,yBAAA,IAAI,EAAE0C,eAAaV,GAAG,CAAChC,OAAOR;AAChC;AAEA,SAAA,wBAAyBQ,KAAa;IACpC,MAAMR,SAAS,yBAAA,IAAI,EAAEkD,eAAavC,GAAG,CAACH;IACtC,IAAI,CAACR,QAAQ;QACX,MAAM,IAAIY,MAAM,CAAC,MAAM,EAAEJ,MAAM,qBAAqB,CAAC;IACvD;IAEA,yBAAA,IAAI,EAAE0C,eAAanB,MAAM,CAACvB;IAC1B,yBAAA,IAAI,EAAEkD,eAAa3B,MAAM,CAAC/B;IAC1B,0BAAA,IAAI,EAAEmF,kBAAAA,sBAAN,IAAI,EAAkBnF;AACxB;AAyBF;;;;;;CAMC,GACD,OAAO,SAAS4C,eACdwC,gBAAwB,EACxBC,UAAkB;IAElB,MAAM1C,MAAM,IAAI7D;IAChBS,KACE6F,kBACA,iCAAiC;IACjCzC,KACAyC,kBACA,CAACxD;QACC,IAAIA,OAAO;YACTyD,aACIrG,SAAS,CAAC,CAAC,EAAEqG,WAAW,iBAAiB,CAAC,EAAEzD,SAC5C5C,SAAS4C;QACf;IACF;IAEF,OAAOe;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../src/services/AbstractExecutionService.ts"],"sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcNotification } from '@metamask/utils';\nimport { Duration, isJsonRpcNotification, isObject } from '@metamask/utils';\nimport type {\n // TODO: Replace with @metamask/utils version after bumping json-rpc-engine\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from 'json-rpc-engine';\nimport { JsonRpcEngine } from 'json-rpc-engine';\nimport { createStreamMiddleware } from 'json-rpc-middleware-stream';\nimport { nanoid } from 'nanoid';\nimport pump from 'pump';\nimport type { Duplex } from 'stream';\n\nimport { log } from '../logging';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\n\nconst controllerName = 'ExecutionService';\n\nexport type SetupSnapProvider = (snapId: string, stream: Duplex) => void;\n\nexport type ExecutionServiceArgs = {\n setupSnapProvider: SetupSnapProvider;\n messenger: ExecutionServiceMessenger;\n terminationTimeout?: number;\n};\n\nexport type JobStreams = {\n command: Duplex;\n rpc: Duplex;\n _connection: BasePostMessageStream;\n};\n\nexport type Job<WorkerType> = {\n id: string;\n streams: JobStreams;\n rpcEngine: JsonRpcEngine;\n worker: WorkerType;\n};\n\nexport abstract class AbstractExecutionService<WorkerType>\n implements ExecutionService\n{\n #snapRpcHooks: Map<string, SnapRpcHook>;\n\n // Cannot be hash private yet because of tests.\n protected jobs: Map<string, Job<WorkerType>>;\n\n // Cannot be hash private yet because of tests.\n private readonly setupSnapProvider: SetupSnapProvider;\n\n #snapToJobMap: Map<string, string>;\n\n #jobToSnapMap: Map<string, string>;\n\n #messenger: ExecutionServiceMessenger;\n\n #terminationTimeout: number;\n\n constructor({\n setupSnapProvider,\n messenger,\n terminationTimeout = Duration.Second,\n }: ExecutionServiceArgs) {\n this.#snapRpcHooks = new Map();\n this.jobs = new Map();\n this.setupSnapProvider = setupSnapProvider;\n this.#snapToJobMap = new Map();\n this.#jobToSnapMap = new Map();\n this.#messenger = messenger;\n this.#terminationTimeout = terminationTimeout;\n\n this.registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.#messenger.registerActionHandler(\n `${controllerName}:handleRpcRequest`,\n async (snapId: string, options: SnapRpcHookArgs) =>\n this.handleRpcRequest(snapId, options),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:executeSnap`,\n async (snapData: SnapExecutionData) => this.executeSnap(snapData),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateSnap`,\n async (snapId: string) => this.terminateSnap(snapId),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateAllSnaps`,\n async () => this.terminateAllSnaps(),\n );\n }\n\n /**\n * Performs additional necessary work during job termination. **MUST** be\n * implemented by concrete implementations. See\n * {@link AbstractExecutionService.terminate} for details.\n *\n * @param job - The object corresponding to the job to be terminated.\n */\n protected abstract terminateJob(job: Job<WorkerType>): void;\n\n /**\n * Terminates the job with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the job will fail with an error.\n * Throws an error if the specified job does not exist, or if termination\n * fails unexpectedly.\n *\n * @param jobId - The id of the job to be terminated.\n */\n public async terminate(jobId: string): Promise<void> {\n const jobWrapper = this.jobs.get(jobId);\n if (!jobWrapper) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n // Ping worker and tell it to run teardown, continue with termination if it takes too long\n const result = await withTimeout(\n this.command(jobId, {\n jsonrpc: '2.0',\n method: 'terminate',\n params: [],\n id: nanoid(),\n }),\n this.#terminationTimeout,\n );\n\n if (result === hasTimedOut || result !== 'OK') {\n // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and\n // hogging down the whole JS process.\n // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour\n // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same\n // JS process.\n logError(`Job \"${jobId}\" failed to terminate gracefully.`, result);\n }\n\n Object.values(jobWrapper.streams).forEach((stream) => {\n try {\n !stream.destroyed && stream.destroy();\n stream.removeAllListeners();\n } catch (error) {\n logError('Error while destroying stream', error);\n }\n });\n\n this.terminateJob(jobWrapper);\n\n this.#removeSnapAndJobMapping(jobId);\n this.jobs.delete(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @returns Information regarding the created job.\n */\n protected async initJob(): Promise<Job<WorkerType>> {\n const jobId = nanoid();\n const { streams, worker } = await this.initStreams(jobId);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pump(jsonRpcConnection.stream, streams.command, jsonRpcConnection.stream);\n\n rpcEngine.push(jsonRpcConnection.middleware);\n\n const envMetadata = {\n id: jobId,\n streams,\n rpcEngine,\n worker,\n };\n this.jobs.set(jobId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param jobId - The id of the job.\n * @returns The streams to communicate with the worker and the worker itself.\n */\n protected async initStreams(\n jobId: string,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const { worker, stream: envStream } = await this.initEnvStream(jobId);\n // Typecast justification: stream type mismatch\n const mux = setupMultiplex(\n envStream as unknown as Duplex,\n `Job: \"${jobId}\"`,\n );\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n\n // Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.\n // Also keep track of outbound request/responses\n const notificationHandler = (\n message:\n | JsonRpcRequest<unknown>\n | JsonRpcNotification<Json[] | Record<string, Json>>,\n ) => {\n if (!isJsonRpcNotification(message)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const snapId = this.#jobToSnapMap.get(jobId)!;\n if (message.method === 'OutboundRequest') {\n this.#messenger.publish('ExecutionService:outboundRequest', snapId);\n } else if (message.method === 'OutboundResponse') {\n this.#messenger.publish('ExecutionService:outboundResponse', snapId);\n } else if (message.method === 'UnhandledError') {\n if (isObject(message.params) && message.params.error) {\n this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n message.params.error as SnapErrorJson,\n );\n commandStream.removeListener('data', notificationHandler);\n } else {\n logError(\n new Error(\n `Received malformed \"${message.method}\" command stream notification.`,\n ),\n );\n }\n } else {\n logError(\n new Error(\n `Received unexpected command stream notification \"${message.method}\".`,\n ),\n );\n }\n };\n\n commandStream.on('data', notificationHandler);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n // Typecast: stream type mismatch\n return {\n streams: {\n command: commandStream as unknown as Duplex,\n rpc: rpcStream,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n _connection: envStream,\n },\n worker,\n };\n }\n\n /**\n * Abstract function implemented by implementing class that spins up a new worker for a job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n */\n protected abstract initEnvStream(jobId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n /**\n * Terminates the Snap with the specified ID. May throw an error if\n * termination unexpectedly fails, but will not fail if no job for the snap\n * with the specified ID is found.\n *\n * @param snapId - The ID of the snap to terminate.\n */\n async terminateSnap(snapId: string) {\n const jobId = this.#snapToJobMap.get(snapId);\n if (jobId) {\n await this.terminate(jobId);\n }\n }\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)),\n );\n this.#snapRpcHooks.clear();\n }\n\n /**\n * Gets the RPC request handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC request handler for the snap.\n */\n private getRpcRequestHandler(snapId: string) {\n return this.#snapRpcHooks.get(snapId);\n }\n\n /**\n * Initializes and executes a snap, setting up the communication channels to the snap etc.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param snapData - Data needed for Snap execution.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error.\n */\n async executeSnap(snapData: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapData.snapId)) {\n throw new Error(`Snap \"${snapData.snapId}\" is already being executed.`);\n }\n\n const job = await this.initJob();\n this.#mapSnapAndJob(snapData.snapId, job.id);\n\n // Ping the worker to ensure that it started up\n await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n });\n\n const rpcStream = job.streams.rpc as unknown as Duplex;\n\n this.setupSnapProvider(snapData.snapId, rpcStream);\n\n const result = await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: snapData,\n id: nanoid(),\n });\n this.#createSnapHooks(snapData.snapId, job.id);\n return result as string;\n }\n\n // Cannot be hash private yet because of tests.\n private async command(\n jobId: string,\n message: JsonRpcRequest<unknown>,\n ): Promise<unknown> {\n if (typeof message !== 'object') {\n throw new Error('Must send object.');\n }\n\n const job = this.jobs.get(jobId);\n if (!job) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n log('Parent: Sending Command', message);\n const response: PendingJsonRpcResponse<unknown> =\n await job.rpcEngine.handle(message);\n if (response.error) {\n throw new Error(response.error.message);\n }\n return response.result;\n }\n\n #removeSnapHooks(snapId: string) {\n this.#snapRpcHooks.delete(snapId);\n }\n\n #createSnapHooks(snapId: string, workerId: string) {\n const rpcHook = async ({ origin, handler, request }: SnapRpcHookArgs) => {\n return await this.command(workerId, {\n id: nanoid(),\n jsonrpc: '2.0',\n method: 'snapRpc',\n params: {\n origin,\n handler,\n request,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n #mapSnapAndJob(snapId: string, jobId: string): void {\n this.#snapToJobMap.set(snapId, jobId);\n this.#jobToSnapMap.set(jobId, snapId);\n }\n\n #removeSnapAndJobMapping(jobId: string): void {\n const snapId = this.#jobToSnapMap.get(jobId);\n if (!snapId) {\n throw new Error(`job: \"${jobId}\" has no mapped snap.`);\n }\n\n this.#jobToSnapMap.delete(jobId);\n this.#snapToJobMap.delete(snapId);\n this.#removeSnapHooks(snapId);\n }\n\n /**\n * Handle RPC request.\n *\n * @param snapId - The ID of the recipient snap.\n * @param options - Bag of options to pass to the RPC handler.\n * @returns Promise that can handle the request.\n */\n public async handleRpcRequest(\n snapId: string,\n options: SnapRpcHookArgs,\n ): Promise<unknown> {\n const rpcRequestHandler = await this.getRpcRequestHandler(snapId);\n\n if (!rpcRequestHandler) {\n throw new Error(\n `Snap execution service returned no RPC handler for running snap \"${snapId}\".`,\n );\n }\n\n return rpcRequestHandler(options);\n }\n}\n\n/**\n * Sets up stream multiplexing for the given stream.\n *\n * @param connectionStream - The stream to mux.\n * @param streamName - The name of the stream, for identification in errors.\n * @returns The multiplexed stream.\n */\nexport function setupMultiplex(\n connectionStream: Duplex,\n streamName: string,\n): ObjectMultiplex {\n const mux = new ObjectMultiplex();\n pump(\n connectionStream,\n // Typecast: stream type mismatch\n mux as unknown as Duplex,\n connectionStream,\n (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n },\n );\n return mux;\n}\n"],"names":["ObjectMultiplex","SNAP_STREAM_NAMES","logError","Duration","isJsonRpcNotification","isObject","JsonRpcEngine","createStreamMiddleware","nanoid","pump","log","hasTimedOut","withTimeout","controllerName","AbstractExecutionService","registerMessageHandlers","messenger","registerActionHandler","snapId","options","handleRpcRequest","snapData","executeSnap","terminateSnap","terminateAllSnaps","terminate","jobId","jobWrapper","jobs","get","Error","result","command","jsonrpc","method","params","id","terminationTimeout","Object","values","streams","forEach","stream","destroyed","destroy","removeAllListeners","error","terminateJob","removeSnapAndJobMapping","delete","initJob","worker","initStreams","rpcEngine","jsonRpcConnection","push","middleware","envMetadata","set","envStream","initEnvStream","mux","setupMultiplex","commandStream","createStream","COMMAND","notificationHandler","message","jobToSnapMap","publish","removeListener","on","rpcStream","JSON_RPC","rpc","_connection","snapToJobMap","Promise","all","keys","map","snapRpcHooks","clear","getRpcRequestHandler","has","job","mapSnapAndJob","setupSnapProvider","createSnapHooks","response","handle","rpcRequestHandler","constructor","Second","Map","workerId","rpcHook","origin","handler","request","target","removeSnapHooks","connectionStream","streamName"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,qBAAqB,6BAA6B;AAGzD,SAASC,iBAAiB,EAAEC,QAAQ,QAAQ,wBAAwB;AAEpE,SAASC,QAAQ,EAAEC,qBAAqB,EAAEC,QAAQ,QAAQ,kBAAkB;AAM5E,SAASC,aAAa,QAAQ,kBAAkB;AAChD,SAASC,sBAAsB,QAAQ,6BAA6B;AACpE,SAASC,MAAM,QAAQ,SAAS;AAChC,OAAOC,UAAU,OAAO;AAGxB,SAASC,GAAG,QAAQ,aAAa;AACjC,SAASC,WAAW,EAAEC,WAAW,QAAQ,WAAW;AAQpD,MAAMC,iBAAiB;IA0BrB,6CAQA,6CAEA,6CAEA,0CAEA,mDAuTA,gDAIA,gDAkBA,8CAKA;AAnWF,OAAO,MAAeC;IAmCpB;;;GAGC,GACD,AAAQC,0BAAgC;QACtC,yBAAA,IAAI,EAAEC,YAAUC,qBAAqB,CACnC,CAAC,EAAEJ,eAAe,iBAAiB,CAAC,EACpC,OAAOK,QAAgBC,UACrB,IAAI,CAACC,gBAAgB,CAACF,QAAQC;QAGlC,yBAAA,IAAI,EAAEH,YAAUC,qBAAqB,CACnC,CAAC,EAAEJ,eAAe,YAAY,CAAC,EAC/B,OAAOQ,WAAgC,IAAI,CAACC,WAAW,CAACD;QAG1D,yBAAA,IAAI,EAAEL,YAAUC,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,yBAAA,IAAI,EAAEkD,eAAalB,GAAG,CAACxC,QAAQQ;IAC/B,yBAAA,IAAI,EAAE0C,eAAaV,GAAG,CAAChC,OAAOR;AAChC;AAEA,SAAA,wBAAyBQ,KAAa;IACpC,MAAMR,SAAS,yBAAA,IAAI,EAAEkD,eAAavC,GAAG,CAACH;IACtC,IAAI,CAACR,QAAQ;QACX,MAAM,IAAIY,MAAM,CAAC,MAAM,EAAEJ,MAAM,qBAAqB,CAAC;IACvD;IAEA,yBAAA,IAAI,EAAE0C,eAAanB,MAAM,CAACvB;IAC1B,yBAAA,IAAI,EAAEkD,eAAa3B,MAAM,CAAC/B;IAC1B,0BAAA,IAAI,EAAEmF,kBAAAA,sBAAN,IAAI,EAAkBnF;AACxB;AAyBF;;;;;;CAMC,GACD,OAAO,SAAS4C,eACdwC,gBAAwB,EACxBC,UAAkB;IAElB,MAAM1C,MAAM,IAAI7D;IAChBS,KACE6F,kBACA,iCAAiC;IACjCzC,KACAyC,kBACA,CAACxD;QACC,IAAIA,OAAO;YACTyD,aACIrG,SAAS,CAAC,CAAC,EAAEqG,WAAW,iBAAiB,CAAC,EAAEzD,SAC5C5C,SAAS4C;QACf;IACF;IAEF,OAAOe;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/ExecutionService.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport type { SnapId, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/
|
|
1
|
+
{"version":3,"sources":["../../../src/services/ExecutionService.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport type { SnapId, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\n\ntype TerminateSnap = (snapId: string) => Promise<void>;\ntype TerminateAll = () => Promise<void>;\ntype ExecuteSnap = (snapData: SnapExecutionData) => Promise<unknown>;\n\ntype HandleRpcRequest = (\n snapId: string,\n options: SnapRpcHookArgs,\n) => Promise<unknown>;\n\nexport interface ExecutionService {\n terminateSnap: TerminateSnap;\n terminateAllSnaps: TerminateAll;\n executeSnap: ExecuteSnap;\n handleRpcRequest: HandleRpcRequest;\n}\n\nexport type SnapExecutionData = {\n snapId: string;\n sourceCode: string;\n endowments?: Json;\n};\n\nexport type SnapErrorJson = {\n message: string;\n code: number;\n data?: Json;\n};\n\nconst controllerName = 'ExecutionService';\n\nexport type ErrorMessageEvent = {\n type: 'ExecutionService:unhandledError';\n payload: [SnapId, SnapErrorJson];\n};\n\nexport type OutboundRequest = {\n type: 'ExecutionService:outboundRequest';\n payload: [SnapId];\n};\n\nexport type OutboundResponse = {\n type: 'ExecutionService:outboundResponse';\n payload: [SnapId];\n};\n\nexport type ExecutionServiceEvents =\n | ErrorMessageEvent\n | OutboundRequest\n | OutboundResponse;\n\n/**\n * Handles RPC request.\n */\nexport type HandleRpcRequestAction = {\n type: `${typeof controllerName}:handleRpcRequest`;\n handler: ExecutionService['handleRpcRequest'];\n};\n\n/**\n * Executes a given snap.\n */\nexport type ExecuteSnapAction = {\n type: `${typeof controllerName}:executeSnap`;\n handler: ExecutionService['executeSnap'];\n};\n\n/**\n * Terminates a given snap.\n */\nexport type TerminateSnapAction = {\n type: `${typeof controllerName}:terminateSnap`;\n handler: ExecutionService['terminateSnap'];\n};\n\n/**\n * Terminates all snaps.\n */\nexport type TerminateAllSnapsAction = {\n type: `${typeof controllerName}:terminateAllSnaps`;\n handler: ExecutionService['terminateAllSnaps'];\n};\n\nexport type ExecutionServiceActions =\n | HandleRpcRequestAction\n | ExecuteSnapAction\n | TerminateSnapAction\n | TerminateAllSnapsAction;\n\nexport type ExecutionServiceMessenger = RestrictedControllerMessenger<\n 'ExecutionService',\n ExecutionServiceActions,\n ExecutionServiceEvents,\n ExecutionServiceActions['type'],\n ExecutionServiceEvents['type']\n>;\n"],"names":["controllerName"],"mappings":"AAgCA,MAAMA,iBAAiB;AAhCvB,WAkGE"}
|