@metamask/snaps-controllers 2.0.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,6 +18,7 @@ var SnapEndowments;
18
18
  SnapEndowments["WebAssemblyAccess"] = 'endowment:webassembly';
19
19
  SnapEndowments["NameLookup"] = 'endowment:name-lookup';
20
20
  SnapEndowments["LifecycleHooks"] = 'endowment:lifecycle-hooks';
21
+ SnapEndowments["Keyring"] = 'endowment:keyring';
21
22
  })(SnapEndowments || (SnapEndowments = {}));
22
23
 
23
24
  //# 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 TransactionInsight = 'endowment:transaction-insight',\n Cronjob = 'endowment:cronjob',\n EthereumProvider = 'endowment:ethereum-provider',\n Rpc = 'endowment:rpc',\n WebAssemblyAccess = 'endowment:webassembly',\n NameLookup = 'endowment:name-lookup',\n LifecycleHooks = 'endowment:lifecycle-hooks',\n}\n"],"names":["SnapEndowments","NetworkAccess","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","NameLookup","LifecycleHooks"],"mappings":";;;;;;;;;;IAAO;UAAKA,cAAc;IAAdA,eACVC,mBAAgB;IADND,eAEVE,wBAAqB;IAFXF,eAGVG,aAAU;IAHAH,eAIVI,sBAAmB;IAJTJ,eAKVK,SAAM;IALIL,eAMVM,uBAAoB;IANVN,eAOVO,gBAAa;IAPHP,eAQVQ,oBAAiB;GARPR,mBAAAA"}
1
+ {"version":3,"sources":["../../../../src/snaps/endowments/enum.ts"],"sourcesContent":["export enum SnapEndowments {\n NetworkAccess = 'endowment:network-access',\n TransactionInsight = 'endowment:transaction-insight',\n Cronjob = 'endowment:cronjob',\n EthereumProvider = 'endowment:ethereum-provider',\n Rpc = 'endowment:rpc',\n WebAssemblyAccess = 'endowment:webassembly',\n NameLookup = 'endowment:name-lookup',\n LifecycleHooks = 'endowment:lifecycle-hooks',\n Keyring = 'endowment:keyring',\n}\n"],"names":["SnapEndowments","NetworkAccess","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","NameLookup","LifecycleHooks","Keyring"],"mappings":";;;;;;;;;;IAAO;UAAKA,cAAc;IAAdA,eACVC,mBAAgB;IADND,eAEVE,wBAAqB;IAFXF,eAGVG,aAAU;IAHAH,eAIVI,sBAAmB;IAJTJ,eAKVK,SAAM;IALIL,eAMVM,uBAAoB;IANVN,eAOVO,gBAAa;IAPHP,eAQVQ,oBAAiB;IARPR,eASVS,aAAU;GATAT,mBAAAA"}
@@ -29,11 +29,15 @@ _export(exports, {
29
29
  },
30
30
  getChainIdsCaveat: function() {
31
31
  return _namelookup.getChainIdsCaveat;
32
+ },
33
+ getKeyringCaveatOrigins: function() {
34
+ return _keyring.getKeyringCaveatOrigins;
32
35
  }
33
36
  });
34
37
  const _snapsutils = require("@metamask/snaps-utils");
35
38
  const _cronjob = require("./cronjob");
36
39
  const _ethereumprovider = require("./ethereum-provider");
40
+ const _keyring = require("./keyring");
37
41
  const _lifecyclehooks = require("./lifecycle-hooks");
38
42
  const _namelookup = require("./name-lookup");
39
43
  const _networkaccess = require("./network-access");
@@ -62,19 +66,22 @@ const endowmentPermissionBuilders = {
62
66
  [_rpc.rpcEndowmentBuilder.targetName]: _rpc.rpcEndowmentBuilder,
63
67
  [_webassembly.webAssemblyEndowmentBuilder.targetName]: _webassembly.webAssemblyEndowmentBuilder,
64
68
  [_namelookup.nameLookupEndowmentBuilder.targetName]: _namelookup.nameLookupEndowmentBuilder,
65
- [_lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName]: _lifecyclehooks.lifecycleHooksEndowmentBuilder
69
+ [_lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName]: _lifecyclehooks.lifecycleHooksEndowmentBuilder,
70
+ [_keyring.keyringEndowmentBuilder.targetName]: _keyring.keyringEndowmentBuilder
66
71
  };
67
72
  const endowmentCaveatSpecifications = {
68
73
  ..._cronjob.cronjobCaveatSpecifications,
69
74
  ..._transactioninsight.transactionInsightCaveatSpecifications,
70
75
  ..._rpc.rpcCaveatSpecifications,
71
- ..._namelookup.nameLookupCaveatSpecifications
76
+ ..._namelookup.nameLookupCaveatSpecifications,
77
+ ..._keyring.keyringCaveatSpecifications
72
78
  };
73
79
  const endowmentCaveatMappers = {
74
80
  [_cronjob.cronjobEndowmentBuilder.targetName]: _cronjob.getCronjobCaveatMapper,
75
81
  [_transactioninsight.transactionInsightEndowmentBuilder.targetName]: _transactioninsight.getTransactionInsightCaveatMapper,
76
82
  [_rpc.rpcEndowmentBuilder.targetName]: _rpc.getRpcCaveatMapper,
77
- [_namelookup.nameLookupEndowmentBuilder.targetName]: _namelookup.getNameLookupCaveatMapper
83
+ [_namelookup.nameLookupEndowmentBuilder.targetName]: _namelookup.getNameLookupCaveatMapper,
84
+ [_keyring.keyringEndowmentBuilder.targetName]: _keyring.getKeyringCaveatMapper
78
85
  };
79
86
  const handlerEndowments = {
80
87
  [_snapsutils.HandlerType.OnRpcRequest]: _rpc.rpcEndowmentBuilder.targetName,
@@ -82,7 +89,8 @@ const handlerEndowments = {
82
89
  [_snapsutils.HandlerType.OnCronjob]: _cronjob.cronjobEndowmentBuilder.targetName,
83
90
  [_snapsutils.HandlerType.OnNameLookup]: _namelookup.nameLookupEndowmentBuilder.targetName,
84
91
  [_snapsutils.HandlerType.OnInstall]: _lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName,
85
- [_snapsutils.HandlerType.OnUpdate]: _lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName
92
+ [_snapsutils.HandlerType.OnUpdate]: _lifecyclehooks.lifecycleHooksEndowmentBuilder.targetName,
93
+ [_snapsutils.HandlerType.OnKeyringRequest]: _keyring.keyringEndowmentBuilder.targetName
86
94
  };
87
95
 
88
96
  //# 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 { lifecycleHooksEndowmentBuilder } from './lifecycle-hooks';\nimport {\n getNameLookupCaveatMapper,\n nameLookupCaveatSpecifications,\n nameLookupEndowmentBuilder,\n} from './name-lookup';\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 [transactionInsightEndowmentBuilder.targetName]:\n transactionInsightEndowmentBuilder,\n [cronjobEndowmentBuilder.targetName]: cronjobEndowmentBuilder,\n [ethereumProviderEndowmentBuilder.targetName]:\n ethereumProviderEndowmentBuilder,\n [rpcEndowmentBuilder.targetName]: rpcEndowmentBuilder,\n [webAssemblyEndowmentBuilder.targetName]: webAssemblyEndowmentBuilder,\n [nameLookupEndowmentBuilder.targetName]: nameLookupEndowmentBuilder,\n [lifecycleHooksEndowmentBuilder.targetName]: lifecycleHooksEndowmentBuilder,\n} as const;\n\nexport const endowmentCaveatSpecifications = {\n ...cronjobCaveatSpecifications,\n ...transactionInsightCaveatSpecifications,\n ...rpcCaveatSpecifications,\n ...nameLookupCaveatSpecifications,\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 [nameLookupEndowmentBuilder.targetName]: getNameLookupCaveatMapper,\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.OnNameLookup]: nameLookupEndowmentBuilder.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';\nexport { getChainIdsCaveat } from './name-lookup';\n"],"names":["endowmentPermissionBuilders","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","getRpcCaveatOrigins","getTransactionOriginCaveat","getChainIdsCaveat","networkAccessEndowmentBuilder","targetName","transactionInsightEndowmentBuilder","cronjobEndowmentBuilder","ethereumProviderEndowmentBuilder","rpcEndowmentBuilder","webAssemblyEndowmentBuilder","nameLookupEndowmentBuilder","lifecycleHooksEndowmentBuilder","cronjobCaveatSpecifications","transactionInsightCaveatSpecifications","rpcCaveatSpecifications","nameLookupCaveatSpecifications","getCronjobCaveatMapper","getTransactionInsightCaveatMapper","getRpcCaveatMapper","getNameLookupCaveatMapper","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate"],"mappings":";;;;;;;;;;;IA6BaA,2BAA2B;eAA3BA;;IAaAC,6BAA6B;eAA7BA;;IAOAC,sBAAsB;eAAtBA;;IAWAC,iBAAiB;eAAjBA;;IAUJC,mBAAmB;eAAnBA,wBAAmB;;IACnBC,0BAA0B;eAA1BA,8CAA0B;;IAC1BC,iBAAiB;eAAjBA,6BAAiB;;;4BAvEE;yBA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,CAACK,SAAS,CAAC,EAAEd,8CAA8B,CAACP,UAAU;IAClE,CAACgB,uBAAW,CAACM,QAAQ,CAAC,EAAEf,8CAA8B,CAACP,UAAU;AACnE"}
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 {\n getKeyringCaveatMapper,\n keyringCaveatSpecifications,\n keyringEndowmentBuilder,\n} from './keyring';\nimport { lifecycleHooksEndowmentBuilder } from './lifecycle-hooks';\nimport {\n getNameLookupCaveatMapper,\n nameLookupCaveatSpecifications,\n nameLookupEndowmentBuilder,\n} from './name-lookup';\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 [transactionInsightEndowmentBuilder.targetName]:\n transactionInsightEndowmentBuilder,\n [cronjobEndowmentBuilder.targetName]: cronjobEndowmentBuilder,\n [ethereumProviderEndowmentBuilder.targetName]:\n ethereumProviderEndowmentBuilder,\n [rpcEndowmentBuilder.targetName]: rpcEndowmentBuilder,\n [webAssemblyEndowmentBuilder.targetName]: webAssemblyEndowmentBuilder,\n [nameLookupEndowmentBuilder.targetName]: nameLookupEndowmentBuilder,\n [lifecycleHooksEndowmentBuilder.targetName]: lifecycleHooksEndowmentBuilder,\n [keyringEndowmentBuilder.targetName]: keyringEndowmentBuilder,\n} as const;\n\nexport const endowmentCaveatSpecifications = {\n ...cronjobCaveatSpecifications,\n ...transactionInsightCaveatSpecifications,\n ...rpcCaveatSpecifications,\n ...nameLookupCaveatSpecifications,\n ...keyringCaveatSpecifications,\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 [nameLookupEndowmentBuilder.targetName]: getNameLookupCaveatMapper,\n [keyringEndowmentBuilder.targetName]: getKeyringCaveatMapper,\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.OnNameLookup]: nameLookupEndowmentBuilder.targetName,\n [HandlerType.OnInstall]: lifecycleHooksEndowmentBuilder.targetName,\n [HandlerType.OnUpdate]: lifecycleHooksEndowmentBuilder.targetName,\n [HandlerType.OnKeyringRequest]: keyringEndowmentBuilder.targetName,\n};\n\nexport * from './enum';\nexport { getRpcCaveatOrigins } from './rpc';\nexport { getTransactionOriginCaveat } from './transaction-insight';\nexport { getChainIdsCaveat } from './name-lookup';\nexport { getKeyringCaveatOrigins } from './keyring';\n"],"names":["endowmentPermissionBuilders","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","getRpcCaveatOrigins","getTransactionOriginCaveat","getChainIdsCaveat","getKeyringCaveatOrigins","networkAccessEndowmentBuilder","targetName","transactionInsightEndowmentBuilder","cronjobEndowmentBuilder","ethereumProviderEndowmentBuilder","rpcEndowmentBuilder","webAssemblyEndowmentBuilder","nameLookupEndowmentBuilder","lifecycleHooksEndowmentBuilder","keyringEndowmentBuilder","cronjobCaveatSpecifications","transactionInsightCaveatSpecifications","rpcCaveatSpecifications","nameLookupCaveatSpecifications","keyringCaveatSpecifications","getCronjobCaveatMapper","getTransactionInsightCaveatMapper","getRpcCaveatMapper","getNameLookupCaveatMapper","getKeyringCaveatMapper","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest"],"mappings":";;;;;;;;;;;IAkCaA,2BAA2B;eAA3BA;;IAcAC,6BAA6B;eAA7BA;;IAQAC,sBAAsB;eAAtBA;;IAYAC,iBAAiB;eAAjBA;;IAWJC,mBAAmB;eAAnBA,wBAAmB;;IACnBC,0BAA0B;eAA1BA,8CAA0B;;IAC1BC,iBAAiB;eAAjBA,6BAAiB;;IACjBC,uBAAuB;eAAvBA,gCAAuB;;;4BAjFJ;yBAOrB;kCAC0C;yBAK1C;gCACwC;4BAKxC;+BACuC;qBAKvC;oCAKA;6BACqC;qBA8C9B;;;;;;;;;;;;;;AA5CP,MAAMP,8BAA8B;IACzC,CAACQ,4CAA6B,CAACC,UAAU,CAAC,EAAED,4CAA6B;IACzE,CAACE,sDAAkC,CAACD,UAAU,CAAC,EAC7CC,sDAAkC;IACpC,CAACC,gCAAuB,CAACF,UAAU,CAAC,EAAEE,gCAAuB;IAC7D,CAACC,kDAAgC,CAACH,UAAU,CAAC,EAC3CG,kDAAgC;IAClC,CAACC,wBAAmB,CAACJ,UAAU,CAAC,EAAEI,wBAAmB;IACrD,CAACC,wCAA2B,CAACL,UAAU,CAAC,EAAEK,wCAA2B;IACrE,CAACC,sCAA0B,CAACN,UAAU,CAAC,EAAEM,sCAA0B;IACnE,CAACC,8CAA8B,CAACP,UAAU,CAAC,EAAEO,8CAA8B;IAC3E,CAACC,gCAAuB,CAACR,UAAU,CAAC,EAAEQ,gCAAuB;AAC/D;AAEO,MAAMhB,gCAAgC;IAC3C,GAAGiB,oCAA2B;IAC9B,GAAGC,0DAAsC;IACzC,GAAGC,4BAAuB;IAC1B,GAAGC,0CAA8B;IACjC,GAAGC,oCAA2B;AAChC;AAEO,MAAMpB,yBAGT;IACF,CAACS,gCAAuB,CAACF,UAAU,CAAC,EAAEc,+BAAsB;IAC5D,CAACb,sDAAkC,CAACD,UAAU,CAAC,EAC7Ce,qDAAiC;IACnC,CAACX,wBAAmB,CAACJ,UAAU,CAAC,EAAEgB,uBAAkB;IACpD,CAACV,sCAA0B,CAACN,UAAU,CAAC,EAAEiB,qCAAyB;IAClE,CAACT,gCAAuB,CAACR,UAAU,CAAC,EAAEkB,+BAAsB;AAC9D;AAEO,MAAMxB,oBAAiD;IAC5D,CAACyB,uBAAW,CAACC,YAAY,CAAC,EAAEhB,wBAAmB,CAACJ,UAAU;IAC1D,CAACmB,uBAAW,CAACE,aAAa,CAAC,EAAEpB,sDAAkC,CAACD,UAAU;IAC1E,CAACmB,uBAAW,CAACG,SAAS,CAAC,EAAEpB,gCAAuB,CAACF,UAAU;IAC3D,CAACmB,uBAAW,CAACI,YAAY,CAAC,EAAEjB,sCAA0B,CAACN,UAAU;IACjE,CAACmB,uBAAW,CAACK,SAAS,CAAC,EAAEjB,8CAA8B,CAACP,UAAU;IAClE,CAACmB,uBAAW,CAACM,QAAQ,CAAC,EAAElB,8CAA8B,CAACP,UAAU;IACjE,CAACmB,uBAAW,CAACO,gBAAgB,CAAC,EAAElB,gCAAuB,CAACR,UAAU;AACpE"}
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ keyringEndowmentBuilder: function() {
13
+ return keyringEndowmentBuilder;
14
+ },
15
+ getKeyringCaveatMapper: function() {
16
+ return getKeyringCaveatMapper;
17
+ },
18
+ getKeyringCaveatOrigins: function() {
19
+ return getKeyringCaveatOrigins;
20
+ },
21
+ keyringCaveatSpecifications: function() {
22
+ return keyringCaveatSpecifications;
23
+ }
24
+ });
25
+ const _permissioncontroller = require("@metamask/permission-controller");
26
+ const _snapsutils = require("@metamask/snaps-utils");
27
+ const _utils = require("@metamask/utils");
28
+ const _ethrpcerrors = require("eth-rpc-errors");
29
+ const _enum = require("./enum");
30
+ const permissionName = _enum.SnapEndowments.Keyring;
31
+ /**
32
+ * `endowment:keyring` returns nothing; it is intended to be used as a flag
33
+ * by the client to detect whether the snap has keyring capabilities.
34
+ *
35
+ * @param _builderOptions - Optional specification builder options.
36
+ * @returns The specification for the keyring endowment.
37
+ */ const specificationBuilder = (_builderOptions)=>{
38
+ return {
39
+ permissionType: _permissioncontroller.PermissionType.Endowment,
40
+ targetName: permissionName,
41
+ allowedCaveats: [
42
+ _snapsutils.SnapCaveatType.KeyringOrigin
43
+ ],
44
+ endowmentGetter: (_getterOptions)=>undefined,
45
+ validator: ({ caveats })=>{
46
+ if (caveats?.length !== 1 || caveats[0].type !== _snapsutils.SnapCaveatType.KeyringOrigin) {
47
+ throw _ethrpcerrors.ethErrors.rpc.invalidParams({
48
+ message: `Expected a single "${_snapsutils.SnapCaveatType.KeyringOrigin}" caveat.`
49
+ });
50
+ }
51
+ },
52
+ subjectTypes: [
53
+ _permissioncontroller.SubjectType.Snap
54
+ ]
55
+ };
56
+ };
57
+ const keyringEndowmentBuilder = Object.freeze({
58
+ targetName: permissionName,
59
+ specificationBuilder
60
+ });
61
+ /**
62
+ * Validate the value of a caveat. This does not validate the type of the
63
+ * caveat itself, only the value of the caveat.
64
+ *
65
+ * @param caveat - The caveat to validate.
66
+ * @throws If the caveat value is invalid.
67
+ */ function validateCaveatOrigins(caveat) {
68
+ if (!(0, _utils.hasProperty)(caveat, 'value') || !(0, _utils.isPlainObject)(caveat.value)) {
69
+ throw _ethrpcerrors.ethErrors.rpc.invalidParams({
70
+ message: 'Invalid keyring origins: Expected a plain object.'
71
+ });
72
+ }
73
+ const { value } = caveat;
74
+ (0, _snapsutils.assertIsKeyringOrigins)(value, _ethrpcerrors.ethErrors.rpc.invalidParams);
75
+ }
76
+ function getKeyringCaveatMapper(value) {
77
+ return {
78
+ caveats: [
79
+ {
80
+ type: _snapsutils.SnapCaveatType.KeyringOrigin,
81
+ value
82
+ }
83
+ ]
84
+ };
85
+ }
86
+ function getKeyringCaveatOrigins(permission) {
87
+ (0, _utils.assert)(permission?.caveats);
88
+ (0, _utils.assert)(permission.caveats.length === 1);
89
+ (0, _utils.assert)(permission.caveats[0].type === _snapsutils.SnapCaveatType.KeyringOrigin);
90
+ const caveat = permission.caveats[0];
91
+ return caveat.value;
92
+ }
93
+ const keyringCaveatSpecifications = {
94
+ [_snapsutils.SnapCaveatType.KeyringOrigin]: Object.freeze({
95
+ type: _snapsutils.SnapCaveatType.KeyringOrigin,
96
+ validator: (caveat)=>validateCaveatOrigins(caveat)
97
+ })
98
+ };
99
+
100
+ //# sourceMappingURL=keyring.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/snaps/endowments/keyring.ts"],"sourcesContent":["import type {\n Caveat,\n CaveatSpecificationConstraint,\n EndowmentGetterParams,\n PermissionConstraint,\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport type { KeyringOrigins } from '@metamask/snaps-utils';\nimport { assertIsKeyringOrigins, SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { assert, hasProperty, isPlainObject } from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.Keyring;\n\ntype KeyringEndowmentSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.Endowment;\n targetName: typeof permissionName;\n endowmentGetter: (_options?: EndowmentGetterParams) => undefined;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n subjectTypes: readonly SubjectType[];\n}>;\n\n/**\n * `endowment:keyring` returns nothing; it is intended to be used as a flag\n * by the client to detect whether the snap has keyring capabilities.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the keyring endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n KeyringEndowmentSpecification\n> = (_builderOptions?: unknown) => {\n return {\n permissionType: PermissionType.Endowment,\n targetName: permissionName,\n allowedCaveats: [SnapCaveatType.KeyringOrigin],\n endowmentGetter: (_getterOptions?: EndowmentGetterParams) => undefined,\n validator: ({ caveats }) => {\n if (\n caveats?.length !== 1 ||\n caveats[0].type !== SnapCaveatType.KeyringOrigin\n ) {\n throw ethErrors.rpc.invalidParams({\n message: `Expected a single \"${SnapCaveatType.KeyringOrigin}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nexport const keyringEndowmentBuilder = Object.freeze({\n targetName: permissionName,\n specificationBuilder,\n} as const);\n\n/**\n * Validate the value of a caveat. This does not validate the type of the\n * caveat itself, only the value of the caveat.\n *\n * @param caveat - The caveat to validate.\n * @throws If the caveat value is invalid.\n */\nfunction validateCaveatOrigins(caveat: Caveat<string, any>) {\n if (!hasProperty(caveat, 'value') || !isPlainObject(caveat.value)) {\n throw ethErrors.rpc.invalidParams({\n message: 'Invalid keyring origins: Expected a plain object.',\n });\n }\n\n const { value } = caveat;\n assertIsKeyringOrigins(value, ethErrors.rpc.invalidParams);\n}\n\n/**\n * Map a raw value from the `initialPermissions` to a caveat specification.\n * Note that this function does not do any validation, that's handled by the\n * PermissionsController when the permission is requested.\n *\n * @param value - The raw value from the `initialPermissions`.\n * @returns The caveat specification.\n */\nexport function getKeyringCaveatMapper(\n value: Json,\n): Pick<PermissionConstraint, 'caveats'> {\n return {\n caveats: [\n {\n type: SnapCaveatType.KeyringOrigin,\n value,\n },\n ],\n };\n}\n\n/**\n * Getter function to get the {@link KeyringOrigins} caveat value from a\n * permission.\n *\n * @param permission - The permission to get the caveat value from.\n * @returns The caveat value.\n * @throws If the permission does not have a valid {@link KeyringOrigins}\n * caveat.\n */\nexport function getKeyringCaveatOrigins(\n permission?: PermissionConstraint,\n): KeyringOrigins | null {\n assert(permission?.caveats);\n assert(permission.caveats.length === 1);\n assert(permission.caveats[0].type === SnapCaveatType.KeyringOrigin);\n\n const caveat = permission.caveats[0] as Caveat<string, KeyringOrigins>;\n return caveat.value;\n}\n\nexport const keyringCaveatSpecifications: Record<\n SnapCaveatType.KeyringOrigin,\n CaveatSpecificationConstraint\n> = {\n [SnapCaveatType.KeyringOrigin]: Object.freeze({\n type: SnapCaveatType.KeyringOrigin,\n validator: (caveat: Caveat<string, any>) => validateCaveatOrigins(caveat),\n }),\n};\n"],"names":["keyringEndowmentBuilder","getKeyringCaveatMapper","getKeyringCaveatOrigins","keyringCaveatSpecifications","permissionName","SnapEndowments","Keyring","specificationBuilder","_builderOptions","permissionType","PermissionType","Endowment","targetName","allowedCaveats","SnapCaveatType","KeyringOrigin","endowmentGetter","_getterOptions","undefined","validator","caveats","length","type","ethErrors","rpc","invalidParams","message","subjectTypes","SubjectType","Snap","Object","freeze","validateCaveatOrigins","caveat","hasProperty","isPlainObject","value","assertIsKeyringOrigins","permission","assert"],"mappings":";;;;;;;;;;;IA4DaA,uBAAuB;eAAvBA;;IA+BGC,sBAAsB;eAAtBA;;IAsBAC,uBAAuB;eAAvBA;;IAWHC,2BAA2B;eAA3BA;;;sCAnH+B;4BAEW;uBAEJ;8BACzB;sBAEK;AAE/B,MAAMC,iBAAiBC,oBAAc,CAACC,OAAO;AAW7C;;;;;;CAMC,GACD,MAAMC,uBAIF,CAACC;IACH,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,SAAS;QACxCC,YAAYR;QACZS,gBAAgB;YAACC,0BAAc,CAACC,aAAa;SAAC;QAC9CC,iBAAiB,CAACC,iBAA2CC;QAC7DC,WAAW,CAAC,EAAEC,OAAO,EAAE;YACrB,IACEA,SAASC,WAAW,KACpBD,OAAO,CAA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AACF"}
@@ -120,7 +120,9 @@ _snapIds = /*#__PURE__*/ new WeakMap();
120
120
  _class_private_field_get(this, _timers).delete(job.id);
121
121
  this.schedule(job);
122
122
  });
123
- this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually
123
+ if (!this.state.jobs[job.id]?.lastRun) {
124
+ this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually
125
+ }
124
126
  _class_private_field_get(this, _timers).set(job.id, timer);
125
127
  _class_private_field_get(this, _snapIds).set(job.id, job.snapId);
126
128
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/cronjob/CronjobController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 as BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport type {\n SnapId,\n ValidatedSnapId,\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapRemoved,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps, SnapEndowments } from '..';\nimport { getCronjobCaveatJobs } from '../snaps/endowments/cronjob';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapRemoved\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedControllerMessenger<\n 'CronjobController',\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: ValidatedSnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #messenger: CronjobControllerMessenger;\n\n #dailyTimer!: Timer;\n\n #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n #snapIds: Map<string, string>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n this.#messenger = messenger;\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapRemoved',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.getSnapJobs(snap.id));\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n private getSnapJobs(snapId: ValidatedSnapId): Cronjob[] | undefined {\n const permissions = this.#messenger.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: ValidatedSnapId) {\n const jobs = this.getSnapJobs(snapId);\n jobs?.forEach((job) => this.schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n private schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.schedule(job);\n });\n\n this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n private async executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n await this.#messenger.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Unregister all jobs related to the given snapId.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: SnapId) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n }\n });\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n private updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necesary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapRemoved',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => {\n this.unregister(snapId);\n });\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"],"names":["BaseControllerV2","BaseController","HandlerType","parseCronExpression","logError","Duration","inMilliseconds","getRunnableSnaps","SnapEndowments","getCronjobCaveatJobs","Timer","DAILY_TIMEOUT","Hour","controllerName","CronjobController","getAllJobs","snaps","messagingSystem","call","filteredSnaps","jobs","map","snap","getSnapJobs","id","flat","filter","job","undefined","snapId","permissions","messenger","permission","Cronjob","definitions","definition","idx","register","forEach","schedule","timers","has","parsed","expression","next","now","Date","ms","getTime","timer","start","executeCronjob","catch","error","delete","updateJobLastRunState","set","snapIds","origin","handler","OnCronjob","request","unregister","entries","_","jobSnapId","length","get","cancel","jobId","lastRun","update","state","dailyCheckIn","hasPrev","prev","dailyTimer","destroy","unsubscribe","_handleSnapRegisterEvent","_handleSnapUnregisterEvent","_handleEventSnapUpdated","constructor","metadata","persist","anonymous","name","Map","bind","subscribe"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,oBAAoBC,cAAc,QAAQ,4BAA4B;AAQ/E,SACEC,WAAW,EACXC,mBAAmB,EACnBC,QAAQ,QACH,wBAAwB;AAC/B,SAASC,QAAQ,EAAEC,cAAc,QAAQ,kBAAkB;AAW3D,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,KAAK;AACtD,SAASC,oBAAoB,QAAQ,8BAA8B;AACnE,SAASC,KAAK,QAAQ,iBAAiB;AAsBvC,OAAO,MAAMC,gBAAgBL,eAAe,IAAID,SAASO,IAAI,EAAE;AAwB/D,MAAMC,iBAAiB;IAWrB,0CAEA,2CAEA,uCAEA,+BAA+B;AAC/B;AAhBF;;;CAGC,GACD,OAAO,MAAMC,0BAA0Bb;IAoErC;;;;GAIC,GACD,AAAQc,aAAwB;QAC9B,MAAMC,QAAQ,IAAI,CAACC,eAAe,CAACC,IAAI,CAAC;QACxC,MAAMC,gBAAgBZ,iBAAiBS;QAEvC,MAAMI,OAAOD,cAAcE,GAAG,CAAC,CAACC,OAAS,IAAI,CAACC,WAAW,CAACD,KAAKE,EAAE;QACjE,4EAA4E;QAC5E,OAAOJ,KAAKK,IAAI,GAAGC,MAAM,CAAC,CAACC,MAAQA,QAAQC;IAC7C;IAEA;;;;;GAKC,GACD,AAAQL,YAAYM,MAAuB,EAAyB;QAClE,MAAMC,cAAc,yBAAA,IAAI,EAAEC,YAAUb,IAAI,CACtC,uCACAW;QAGF,MAAMG,aAAaF,aAAa,CAACtB,eAAeyB,OAAO,CAAC;QACxD,MAAMC,cAAczB,qBAAqBuB;QAEzC,OAAOE,aAAab,IAAI,CAACc,YAAYC;YACnC,OAAO;gBAAE,GAAGD,UAAU;gBAAEX,IAAI,CAAC,EAAEK,OAAO,CAAC,EAAEO,IAAI,CAAC;gBAAEP;YAAO;QACzD;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D,KAAK;YACV;QACF;QApBF,gCAAA;;mBAAA,KAAA;;QAEA,gCAAA;;mBAAA,KAAA;;QAEA,gCAAA;;mBAAA,KAAA;;QAGA,gCAAA;;mBAAA,KAAA;;uCAcQhC,SAAS,IAAI+C;uCACb9B,UAAU,IAAI8B;uCACdxD,YAAYA;QAElB,IAAI,CAACgD,wBAAwB,GAAG,IAAI,CAACA,wBAAwB,CAACS,IAAI,CAAC,IAAI;QACvE,IAAI,CAACR,0BAA0B,GAC7B,IAAI,CAACA,0BAA0B,CAACQ,IAAI,CAAC,IAAI;QAC3C,IAAI,CAACP,uBAAuB,GAAG,IAAI,CAACA,uBAAuB,CAACO,IAAI,CAAC,IAAI;QAErE,2BAA2B;QAC3B,oDAAoD,GACpD,IAAI,CAACvE,eAAe,CAACwE,SAAS,CAC5B,gCACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAAC9D,eAAe,CAACwE,SAAS,CAC5B,8BACA,IAAI,CAACT,0BAA0B;QAGjC,IAAI,CAAC/D,eAAe,CAACwE,SAAS,CAC5B,8BACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAAC9D,eAAe,CAACwE,SAAS,CAC5B,+BACA,IAAI,CAACT,0BAA0B;QAGjC,IAAI,CAAC/D,eAAe,CAACwE,SAAS,CAC5B,8BACA,IAAI,CAACR,uBAAuB;QAE9B,mDAAmD,GAEnD,IAAI,CAACR,YAAY,GAAGrB,KAAK,CAAC,CAACC;YACzBjD,SAASiD;QACX;IACF;AA8OF"}
1
+ {"version":3,"sources":["../../../src/cronjob/CronjobController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 as BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport type {\n SnapId,\n ValidatedSnapId,\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapRemoved,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps, SnapEndowments } from '..';\nimport { getCronjobCaveatJobs } from '../snaps/endowments/cronjob';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapRemoved\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedControllerMessenger<\n 'CronjobController',\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: ValidatedSnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #messenger: CronjobControllerMessenger;\n\n #dailyTimer!: Timer;\n\n #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n #snapIds: Map<string, string>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n this.#messenger = messenger;\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapRemoved',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.getSnapJobs(snap.id));\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n private getSnapJobs(snapId: ValidatedSnapId): Cronjob[] | undefined {\n const permissions = this.#messenger.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: ValidatedSnapId) {\n const jobs = this.getSnapJobs(snapId);\n jobs?.forEach((job) => this.schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n private schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.schedule(job);\n });\n\n if (!this.state.jobs[job.id]?.lastRun) {\n this.updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n }\n\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n private async executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n await this.#messenger.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Unregister all jobs related to the given snapId.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: SnapId) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n }\n });\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n private updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necesary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapRemoved',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => {\n this.unregister(snapId);\n });\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"],"names":["BaseControllerV2","BaseController","HandlerType","parseCronExpression","logError","Duration","inMilliseconds","getRunnableSnaps","SnapEndowments","getCronjobCaveatJobs","Timer","DAILY_TIMEOUT","Hour","controllerName","CronjobController","getAllJobs","snaps","messagingSystem","call","filteredSnaps","jobs","map","snap","getSnapJobs","id","flat","filter","job","undefined","snapId","permissions","messenger","permission","Cronjob","definitions","definition","idx","register","forEach","schedule","timers","has","parsed","expression","next","now","Date","ms","getTime","timer","start","executeCronjob","catch","error","delete","state","lastRun","updateJobLastRunState","set","snapIds","origin","handler","OnCronjob","request","unregister","entries","_","jobSnapId","length","get","cancel","jobId","update","dailyCheckIn","hasPrev","prev","dailyTimer","destroy","unsubscribe","_handleSnapRegisterEvent","_handleSnapUnregisterEvent","_handleEventSnapUpdated","constructor","metadata","persist","anonymous","name","Map","bind","subscribe"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,oBAAoBC,cAAc,QAAQ,4BAA4B;AAQ/E,SACEC,WAAW,EACXC,mBAAmB,EACnBC,QAAQ,QACH,wBAAwB;AAC/B,SAASC,QAAQ,EAAEC,cAAc,QAAQ,kBAAkB;AAW3D,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,KAAK;AACtD,SAASC,oBAAoB,QAAQ,8BAA8B;AACnE,SAASC,KAAK,QAAQ,iBAAiB;AAsBvC,OAAO,MAAMC,gBAAgBL,eAAe,IAAID,SAASO,IAAI,EAAE;AAwB/D,MAAMC,iBAAiB;IAWrB,0CAEA,2CAEA,uCAEA,+BAA+B;AAC/B;AAhBF;;;CAGC,GACD,OAAO,MAAMC,0BAA0Bb;IAoErC;;;;GAIC,GACD,AAAQc,aAA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B,gCACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAAC9D,eAAe,CAACwE,SAAS,CAC5B,8BACA,IAAI,CAACT,0BAA0B;QAGjC,IAAI,CAAC/D,eAAe,CAACwE,SAAS,CAC5B,8BACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAAC9D,eAAe,CAACwE,SAAS,CAC5B,+BACA,IAAI,CAACT,0BAA0B;QAGjC,IAAI,CAAC/D,eAAe,CAACwE,SAAS,CAC5B,8BACA,IAAI,CAACR,uBAAuB;QAE9B,mDAAmD,GAEnD,IAAI,CAACR,YAAY,GAAGrB,KAAK,CAAC,CAACC;YACzBjD,SAASiD;QACX;IACF;AAiPF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/fsm.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\nimport type { EventObject, StateMachine, Typestate } from '@xstate/fsm';\nimport { InterpreterStatus } from '@xstate/fsm';\n\n/**\n * Validates the set-up of a @xstate/fsm machine.\n *\n * 1. Ensures that all named actions in the config have a provided implementation.\n *\n * @param machine - The machine to validate.\n * @throws {@link AssertionError}. If the validation fails.\n */\nexport function validateMachine<\n TContext extends object,\n TEvent extends EventObject,\n TState extends Typestate<TContext>,\n>(machine: StateMachine.Machine<TContext, TEvent, TState>) {\n assert('_options' in machine, 'The machine is not an @xstate/fsm machine');\n const typed = machine as StateMachine.Machine<TContext, TEvent, TState> & {\n _options: { actions?: StateMachine.ActionMap<TContext, TEvent> };\n };\n\n // 1.\n const toArray = <Type>(obj: Type | Type[]): Type[] => {\n if (Array.isArray(obj)) {\n return obj;\n } else if (obj === undefined || obj === null) {\n return [];\n }\n return [obj];\n };\n\n const allActions = new Set<string>();\n const addActions = (actions: any) =>\n toArray(actions)\n .flatMap((action) => {\n if (typeof action === 'string') {\n return [action];\n }\n assert(typeof action === 'function');\n return [];\n })\n .forEach(allActions.add.bind(allActions));\n\n for (const state of Object.values<typeof typed.config.states[string]>(\n typed.config.states,\n )) {\n addActions(state.entry);\n addActions(state.exit);\n for (const transition of Object.values<any>(state.on ?? {})) {\n addActions(transition.actions);\n }\n }\n\n allActions.forEach((action) =>\n assert(\n typed._options.actions !== undefined && action in typed._options.actions,\n `Action \"${action}\" doesn't have an implementation`,\n ),\n );\n}\n\n/**\n * Ensure that the interpreter is strict.\n * Strict means that the transition must occur.\n * The event must exist in .on {} state config and it's guard must succeed.\n *\n * The error will be thrown when an invalid `interpreter.send()` is called\n * and will be bubbled there.\n *\n * TODO(ritave): Doesn't support self transitions.\n *\n * @param interpreter - The interpreter that will be force into strict mode.\n * @throws {@link Error} Thrown when the transition is invalid.\n */\nexport function forceStrict(interpreter: StateMachine.Service<any, any, any>) {\n // As soon as a listener subscribes, it is called. It might be called in\n // an initial state which doesn't have the .changed property\n let onInitialCalled = false;\n interpreter.subscribe((state) => {\n assert(!onInitialCalled || state.changed, 'Invalid state transition');\n onInitialCalled = true;\n });\n\n const ogSend = interpreter.send.bind(interpreter);\n interpreter.send = (...args) => {\n assert(\n interpreter.status === InterpreterStatus.Running,\n 'Interpreter is stopped',\n );\n return ogSend(...args);\n };\n}\n"],"names":["assert","InterpreterStatus","validateMachine","machine","typed","toArray","obj","Array","isArray","undefined","allActions","Set","addActions","actions","flatMap","action","forEach","add","bind","state","Object","values","config","states","entry","exit","transition","on","_options","forceStrict","interpreter","onInitialCalled","subscribe","changed","ogSend","send","args","status","Running"],"mappings":"AAAA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC,SAASC,iBAAiB,QAAQ,cAAc;AAEhD;;;;;;;CAOC,GACD,OAAO,SAASC,gBAIdC,OAAuD;IACvDH,OAAO,cAAcG,SAAS;IAC9B,MAAMC,QAAQD;IAId,KAAK;IACL,MAAME,UAAU,CAAOC;QACrB,IAAIC,MAAMC,OAAO,CAACF,MAAM;YACtB,OAAOA;QACT,OAAO,IAAIA,QAAQG,aAAaH,QAAQ,MAAM;YAC5C,OAAO,EAAE;QACX;QACA,OAAO;YAACA;SAAI;IACd;IAEA,MAAMI,aAAa,IAAIC;IACvB,MAAMC,aAAa,CAACC,UAClBR,QAAQQ,SACLC,OAAO,CAAC,CAACC;YACR,IAAI,OAAOA,WAAW,UAAU;gBAC9B,OAAO;oBAACA;iBAAO;YACjB;YACAf,OAAO,OAAOe,WAAW;YACzB,OAAO,EAAE;QACX,GACCC,OAAO,CAACN,WAAWO,GAAG,CAACC,IAAI,CAACR;IAEjC,KAAK,MAAMS,SAASC,OAAOC,MAAM,CAC/BjB,MAAMkB,MAAM,CAACC,MAAM,EAClB;QACDX,WAAWO,MAAMK,KAAK;QACtBZ,WAAWO,MAAMM,IAAI;QACrB,KAAK,MAAMC,cAAcN,OAAOC,MAAM,CAAMF,MAAMQ,EAAE,IAAI,CAAC,GAAI;YAC3Df,WAAWc,WAAWb,OAAO;QAC/B;IACF;IAEAH,WAAWM,OAAO,CAAC,CAACD,SAClBf,OACEI,MAAMwB,QAAQ,CAACf,OAAO,KAAKJ,aAAaM,UAAUX,MAAMwB,QAAQ,CAACf,OAAO,EACxE,CAAC,QAAQ,EAAEE,OAAO,gCAAgC,CAAC;AAGzD;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,SAASc,YAAYC,WAAgD;IAC1E,wEAAwE;IACxE,4DAA4D;IAC5D,IAAIC,kBAAkB;IACtBD,YAAYE,SAAS,CAAC,CAACb;QACrBnB,OAAO,CAAC+B,mBAAmBZ,MAAMc,OAAO,EAAE;QAC1CF,kBAAkB;IACpB;IAEA,MAAMG,SAASJ,YAAYK,IAAI,CAACjB,IAAI,CAACY;IACrCA,YAAYK,IAAI,GAAG,CAAC,GAAGC;QACrBpC,OACE8B,YAAYO,MAAM,KAAKpC,kBAAkBqC,OAAO,EAChD;QAEF,OAAOJ,UAAUE;IACnB;AACF"}
1
+ {"version":3,"sources":["../../src/fsm.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\nimport type { EventObject, StateMachine, Typestate } from '@xstate/fsm';\nimport { InterpreterStatus } from '@xstate/fsm';\n\n/**\n * Validates the set-up of a @xstate/fsm machine.\n *\n * 1. Ensures that all named actions in the config have a provided implementation.\n *\n * @param machine - The machine to validate.\n * @throws {@link AssertionError}. If the validation fails.\n */\nexport function validateMachine<\n TContext extends object,\n TEvent extends EventObject,\n TState extends Typestate<TContext>,\n>(machine: StateMachine.Machine<TContext, TEvent, TState>) {\n assert('_options' in machine, 'The machine is not an @xstate/fsm machine');\n const typed = machine as StateMachine.Machine<TContext, TEvent, TState> & {\n _options: { actions?: StateMachine.ActionMap<TContext, TEvent> };\n };\n\n // 1.\n const toArray = <Type>(obj: Type | Type[]): Type[] => {\n if (Array.isArray(obj)) {\n return obj;\n } else if (obj === undefined || obj === null) {\n return [];\n }\n return [obj];\n };\n\n const allActions = new Set<string>();\n const addActions = (actions: any) =>\n toArray(actions)\n .flatMap((action) => {\n if (typeof action === 'string') {\n return [action];\n }\n assert(typeof action === 'function');\n return [];\n })\n .forEach(allActions.add.bind(allActions));\n\n for (const state of Object.values<(typeof typed.config.states)[string]>(\n typed.config.states,\n )) {\n addActions(state.entry);\n addActions(state.exit);\n for (const transition of Object.values<any>(state.on ?? {})) {\n addActions(transition.actions);\n }\n }\n\n allActions.forEach((action) =>\n assert(\n typed._options.actions !== undefined && action in typed._options.actions,\n `Action \"${action}\" doesn't have an implementation`,\n ),\n );\n}\n\n/**\n * Ensure that the interpreter is strict.\n * Strict means that the transition must occur.\n * The event must exist in .on {} state config and it's guard must succeed.\n *\n * The error will be thrown when an invalid `interpreter.send()` is called\n * and will be bubbled there.\n *\n * TODO(ritave): Doesn't support self transitions.\n *\n * @param interpreter - The interpreter that will be force into strict mode.\n * @throws {@link Error} Thrown when the transition is invalid.\n */\nexport function forceStrict(interpreter: StateMachine.Service<any, any, any>) {\n // As soon as a listener subscribes, it is called. It might be called in\n // an initial state which doesn't have the .changed property\n let onInitialCalled = false;\n interpreter.subscribe((state) => {\n assert(!onInitialCalled || state.changed, 'Invalid state transition');\n onInitialCalled = true;\n });\n\n const ogSend = interpreter.send.bind(interpreter);\n interpreter.send = (...args) => {\n assert(\n interpreter.status === InterpreterStatus.Running,\n 'Interpreter is stopped',\n );\n return ogSend(...args);\n };\n}\n"],"names":["assert","InterpreterStatus","validateMachine","machine","typed","toArray","obj","Array","isArray","undefined","allActions","Set","addActions","actions","flatMap","action","forEach","add","bind","state","Object","values","config","states","entry","exit","transition","on","_options","forceStrict","interpreter","onInitialCalled","subscribe","changed","ogSend","send","args","status","Running"],"mappings":"AAAA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC,SAASC,iBAAiB,QAAQ,cAAc;AAEhD;;;;;;;CAOC,GACD,OAAO,SAASC,gBAIdC,OAAuD;IACvDH,OAAO,cAAcG,SAAS;IAC9B,MAAMC,QAAQD;IAId,KAAK;IACL,MAAME,UAAU,CAAOC;QACrB,IAAIC,MAAMC,OAAO,CAACF,MAAM;YACtB,OAAOA;QACT,OAAO,IAAIA,QAAQG,aAAaH,QAAQ,MAAM;YAC5C,OAAO,EAAE;QACX;QACA,OAAO;YAACA;SAAI;IACd;IAEA,MAAMI,aAAa,IAAIC;IACvB,MAAMC,aAAa,CAACC,UAClBR,QAAQQ,SACLC,OAAO,CAAC,CAACC;YACR,IAAI,OAAOA,WAAW,UAAU;gBAC9B,OAAO;oBAACA;iBAAO;YACjB;YACAf,OAAO,OAAOe,WAAW;YACzB,OAAO,EAAE;QACX,GACCC,OAAO,CAACN,WAAWO,GAAG,CAACC,IAAI,CAACR;IAEjC,KAAK,MAAMS,SAASC,OAAOC,MAAM,CAC/BjB,MAAMkB,MAAM,CAACC,MAAM,EAClB;QACDX,WAAWO,MAAMK,KAAK;QACtBZ,WAAWO,MAAMM,IAAI;QACrB,KAAK,MAAMC,cAAcN,OAAOC,MAAM,CAAMF,MAAMQ,EAAE,IAAI,CAAC,GAAI;YAC3Df,WAAWc,WAAWb,OAAO;QAC/B;IACF;IAEAH,WAAWM,OAAO,CAAC,CAACD,SAClBf,OACEI,MAAMwB,QAAQ,CAACf,OAAO,KAAKJ,aAAaM,UAAUX,MAAMwB,QAAQ,CAACf,OAAO,EACxE,CAAC,QAAQ,EAAEE,OAAO,gCAAgC,CAAC;AAGzD;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,SAASc,YAAYC,WAAgD;IAC1E,wEAAwE;IACxE,4DAA4D;IAC5D,IAAIC,kBAAkB;IACtBD,YAAYE,SAAS,CAAC,CAACb;QACrBnB,OAAO,CAAC+B,mBAAmBZ,MAAMc,OAAO,EAAE;QAC1CF,kBAAkB;IACpB;IAEA,MAAMG,SAASJ,YAAYK,IAAI,CAACjB,IAAI,CAACY;IACrCA,YAAYK,IAAI,GAAG,CAAC,GAAGC;QACrBpC,OACE8B,YAAYO,MAAM,KAAKpC,kBAAkBqC,OAAO,EAChD;QAEF,OAAOJ,UAAUE;IACnB;AACF"}
@@ -64,7 +64,7 @@ function _define_property(obj, key, value) {
64
64
  import { BaseControllerV2 as BaseController } from '@metamask/base-controller';
65
65
  import { SubjectType } from '@metamask/permission-controller';
66
66
  import { WALLET_SNAP_PERMISSION_KEY } from '@metamask/rpc-methods';
67
- import { assertIsSnapManifest, assertIsValidSnapId, DEFAULT_ENDOWMENTS, DEFAULT_REQUESTED_SNAP_VERSION, getErrorMessage, HandlerType, logError, normalizeRelative, resolveVersionRange, SnapCaveatType, SnapStatus, SnapStatusEvents, validateFetchedSnap } from '@metamask/snaps-utils';
67
+ import { assertIsSnapManifest, assertIsValidSnapId, DEFAULT_ENDOWMENTS, DEFAULT_REQUESTED_SNAP_VERSION, getErrorMessage, HandlerType, isOriginAllowed, logError, normalizeRelative, resolveVersionRange, SnapCaveatType, SnapStatus, SnapStatusEvents, validateFetchedSnap } from '@metamask/snaps-utils';
68
68
  import { assert, assertIsJsonRpcRequest, Duration, gtRange, gtVersion, hasProperty, inMilliseconds, isNonEmptyArray, isValidSemVerRange, satisfiesVersionRange, timeSince } from '@metamask/utils';
69
69
  import { createMachine, interpret } from '@xstate/fsm';
70
70
  import { ethErrors } from 'eth-rpc-errors';
@@ -73,6 +73,7 @@ import { forceStrict, validateMachine } from '../fsm';
73
73
  import { log } from '../logging';
74
74
  import { hasTimedOut, setDiff, withTimeout } from '../utils';
75
75
  import { handlerEndowments, SnapEndowments } from './endowments';
76
+ import { getKeyringCaveatOrigins } from './endowments/keyring';
76
77
  import { getRpcCaveatOrigins } from './endowments/rpc';
77
78
  import { detectSnapLocation } from './location';
78
79
  import { processSnapPermissions } from './permissions';
@@ -471,6 +472,7 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
471
472
  throw new Error('Expected array of snap ids.');
472
473
  }
473
474
  await Promise.all(snapIds.map(async (snapId)=>{
475
+ const snap = this.getExpect(snapId);
474
476
  const truncated = this.getTruncatedExpect(snapId);
475
477
  // Disable the snap and revoke all of its permissions before deleting
476
478
  // it. This ensures that the snap will not be restarted or otherwise
@@ -484,6 +486,10 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
484
486
  delete state.snapStates[snapId];
485
487
  });
486
488
  this.messagingSystem.publish(`SnapController:snapRemoved`, truncated);
489
+ // If the snap has been fully installed before, also emit snapUninstalled.
490
+ if (snap.status !== SnapStatus.Installing) {
491
+ this.messagingSystem.publish(`SnapController:snapUninstalled`, truncated);
492
+ }
487
493
  }));
488
494
  }
489
495
  /**
@@ -597,7 +603,11 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
597
603
  // Everything else is treated as an install
598
604
  const isUpdate = this.has(snapId) && !location.shouldAlwaysReload;
599
605
  if (isUpdate && _class_private_method_get(this, _isValidUpdate, isValidUpdate).call(this, snapId, version)) {
600
- pendingUpdates.push(snapId);
606
+ const existingSnap = this.getExpect(snapId);
607
+ pendingUpdates.push({
608
+ snapId,
609
+ oldVersion: existingSnap.version
610
+ });
601
611
  let rollbackSnapshot = _class_private_method_get(this, _getRollbackSnapshot, getRollbackSnapshot).call(this, snapId);
602
612
  if (rollbackSnapshot === undefined) {
603
613
  rollbackSnapshot = _class_private_method_get(this, _createRollbackSnapshot, createRollbackSnapshot).call(this, snapId);
@@ -610,6 +620,9 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
610
620
  }
611
621
  result[snapId] = await this.processRequestedSnap(origin, snapId, location, version);
612
622
  }
623
+ // Once we finish all installs / updates, emit events.
624
+ pendingInstalls.forEach((snapId)=>this.messagingSystem.publish(`SnapController:snapInstalled`, this.getTruncatedExpect(snapId)));
625
+ pendingUpdates.forEach(({ snapId, oldVersion })=>this.messagingSystem.publish(`SnapController:snapUpdated`, this.getTruncatedExpect(snapId), oldVersion));
613
626
  snapIds.forEach((snapId)=>_class_private_field_get(this, _rollbackSnapshots).delete(snapId));
614
627
  } catch (error) {
615
628
  const installed = pendingInstalls.filter((snapId)=>this.has(snapId));
@@ -617,7 +630,7 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
617
630
  const snapshottedSnaps = [
618
631
  ..._class_private_field_get(this, _rollbackSnapshots).keys()
619
632
  ];
620
- const snapsToRollback = pendingUpdates.filter((snapId)=>snapshottedSnaps.includes(snapId));
633
+ const snapsToRollback = pendingUpdates.map(({ snapId })=>snapId).filter((snapId)=>snapshottedSnaps.includes(snapId));
621
634
  await _class_private_method_get(this, _rollbackSnaps, rollbackSnaps).call(this, snapsToRollback);
622
635
  throw error;
623
636
  }
@@ -639,10 +652,12 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
639
652
  if (satisfiesVersionRange(existingSnap.version, versionRange)) {
640
653
  return existingSnap;
641
654
  }
642
- if (_class_private_field_get(this, _featureFlags).dappsCanUpdateSnaps === true) {
643
- return await this.updateSnap(origin, snapId, location, versionRange);
644
- }
645
- throw ethErrors.rpc.invalidParams(`Version mismatch with already installed snap. ${snapId}@${existingSnap.version} doesn't satisfy requested version ${versionRange}.`);
655
+ return await this.updateSnap(origin, snapId, location, versionRange, // Since we are requesting an update from within processRequestedSnap,
656
+ // we disable the emitting of the snapUpdated event and rely on the caller
657
+ // to publish this event after the update is complete.
658
+ // This is necesary as installSnaps may be installing multiple snaps
659
+ // and we don't want to emit events prematurely.
660
+ false);
646
661
  }
647
662
  let pendingApproval = _class_private_method_get(this, _createApproval, createApproval).call(this, {
648
663
  origin,
@@ -679,7 +694,6 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
679
694
  loading: false,
680
695
  type: SNAP_APPROVAL_INSTALL
681
696
  });
682
- this.messagingSystem.publish(`SnapController:snapInstalled`, truncated);
683
697
  return truncated;
684
698
  } catch (error) {
685
699
  logError(`Error when adding ${snapId}.`, error);
@@ -707,8 +721,9 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
707
721
  * @param snapId - The id of the Snap to be updated.
708
722
  * @param location - The location implementation of the snap.
709
723
  * @param newVersionRange - A semver version range in which the maximum version will be chosen.
724
+ * @param emitEvent - An optional boolean flag to indicate whether this update should emit an event.
710
725
  * @returns The snap metadata if updated, `null` otherwise.
711
- */ async updateSnap(origin, snapId, location, newVersionRange = DEFAULT_REQUESTED_SNAP_VERSION) {
726
+ */ async updateSnap(origin, snapId, location, newVersionRange = DEFAULT_REQUESTED_SNAP_VERSION, emitEvent = true) {
712
727
  if (!isValidSemVerRange(newVersionRange)) {
713
728
  throw new Error(`Received invalid snap version range: "${newVersionRange}".`);
714
729
  }
@@ -792,7 +807,9 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
792
807
  throw new Error(`Snap ${snapId} crashed with updated source code.`);
793
808
  }
794
809
  const truncatedSnap = this.getTruncatedExpect(snapId);
795
- this.messagingSystem.publish('SnapController:snapUpdated', truncatedSnap, snap.version);
810
+ if (emitEvent) {
811
+ this.messagingSystem.publish('SnapController:snapUpdated', truncatedSnap, snap.version);
812
+ }
796
813
  _class_private_method_get(this, _updateApproval, updateApproval).call(this, pendingApproval.id, {
797
814
  loading: false,
798
815
  type: SNAP_APPROVAL_UPDATE
@@ -883,16 +900,15 @@ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
883
900
  if (!hasPermission) {
884
901
  throw new Error(`Snap "${snapId}" is not permitted to use "${permissionName}".`);
885
902
  }
886
- if (permissionName === SnapEndowments.Rpc) {
903
+ if (permissionName === SnapEndowments.Rpc || permissionName === SnapEndowments.Keyring) {
887
904
  const subject = this.messagingSystem.call('SubjectMetadataController:getSubjectMetadata', origin);
888
- const isSnap = subject?.subjectType === SubjectType.Snap;
889
905
  const permissions = this.messagingSystem.call('PermissionController:getPermissions', snapId);
890
- const rpcPermission = permissions?.[SnapEndowments.Rpc];
891
- assert(rpcPermission);
892
- const origins = getRpcCaveatOrigins(rpcPermission);
906
+ const handlerPermissions = permissions?.[permissionName];
907
+ assert(handlerPermissions);
908
+ const origins = permissionName === SnapEndowments.Rpc ? getRpcCaveatOrigins(handlerPermissions) : getKeyringCaveatOrigins(handlerPermissions);
893
909
  assert(origins);
894
- if (isSnap && !origins.snaps || !isSnap && !origins.dapps) {
895
- throw new Error(`Snap "${snapId}" is not permitted to handle JSON-RPC requests from "${origin}".`);
910
+ if (!isOriginAllowed(origins, subject?.subjectType ?? SubjectType.Website, origin)) {
911
+ throw new Error(`Snap "${snapId}" is not permitted to handle requests from "${origin}".`);
896
912
  }
897
913
  }
898
914
  const handler = await _class_private_method_get(this, _getRpcRequestHandler, getRpcRequestHandler).call(this, snapId);