@metamask/snaps-controllers 0.38.2-flask.1 → 0.39.0-flask.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/dist/cjs/cronjob/CronjobController.js +14 -10
  3. package/dist/cjs/cronjob/CronjobController.js.map +1 -1
  4. package/dist/cjs/services/AbstractExecutionService.js +7 -3
  5. package/dist/cjs/services/AbstractExecutionService.js.map +1 -1
  6. package/dist/cjs/snaps/SnapController.js +3 -2
  7. package/dist/cjs/snaps/SnapController.js.map +1 -1
  8. package/dist/cjs/snaps/endowments/enum.js +1 -0
  9. package/dist/cjs/snaps/endowments/enum.js.map +1 -1
  10. package/dist/cjs/snaps/endowments/index.js +10 -2
  11. package/dist/cjs/snaps/endowments/index.js.map +1 -1
  12. package/dist/cjs/snaps/endowments/name-lookup.js +106 -0
  13. package/dist/cjs/snaps/endowments/name-lookup.js.map +1 -0
  14. package/dist/cjs/snaps/location/npm.js +5 -3
  15. package/dist/cjs/snaps/location/npm.js.map +1 -1
  16. package/dist/esm/cronjob/CronjobController.js +14 -10
  17. package/dist/esm/cronjob/CronjobController.js.map +1 -1
  18. package/dist/esm/services/AbstractExecutionService.js +7 -3
  19. package/dist/esm/services/AbstractExecutionService.js.map +1 -1
  20. package/dist/esm/snaps/SnapController.js +3 -2
  21. package/dist/esm/snaps/SnapController.js.map +1 -1
  22. package/dist/esm/snaps/endowments/enum.js +1 -0
  23. package/dist/esm/snaps/endowments/enum.js.map +1 -1
  24. package/dist/esm/snaps/endowments/index.js +8 -2
  25. package/dist/esm/snaps/endowments/index.js.map +1 -1
  26. package/dist/esm/snaps/endowments/name-lookup.js +98 -0
  27. package/dist/esm/snaps/endowments/name-lookup.js.map +1 -0
  28. package/dist/esm/snaps/location/npm.js +5 -3
  29. package/dist/esm/snaps/location/npm.js.map +1 -1
  30. package/dist/types/cronjob/CronjobController.d.ts +6 -6
  31. package/dist/types/snaps/SnapController.d.ts +16 -1
  32. package/dist/types/snaps/endowments/enum.d.ts +1 -0
  33. package/dist/types/snaps/endowments/index.d.ts +12 -0
  34. package/dist/types/snaps/endowments/name-lookup.d.ts +38 -0
  35. package/package.json +17 -19
@@ -7,6 +7,7 @@ export var SnapEndowments;
7
7
  SnapEndowments["EthereumProvider"] = 'endowment:ethereum-provider';
8
8
  SnapEndowments["Rpc"] = 'endowment:rpc';
9
9
  SnapEndowments["WebAssemblyAccess"] = 'endowment:webassembly';
10
+ SnapEndowments["NameLookup"] = 'endowment:name-lookup';
10
11
  SnapEndowments["LifecycleHooks"] = 'endowment:lifecycle-hooks';
11
12
  })(SnapEndowments || (SnapEndowments = {}));
12
13
 
@@ -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 LifecycleHooks = 'endowment:lifecycle-hooks',\n}\n"],"names":["SnapEndowments","NetworkAccess","LongRunning","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","LifecycleHooks"],"mappings":"WAAO;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"}
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 NameLookup = 'endowment:name-lookup',\n LifecycleHooks = 'endowment:lifecycle-hooks',\n}\n"],"names":["SnapEndowments","NetworkAccess","LongRunning","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","NameLookup","LifecycleHooks"],"mappings":"WAAO;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,gBAAa;IARHR,eASVS,oBAAiB;GATPT,mBAAAA"}
@@ -3,6 +3,7 @@ import { cronjobCaveatSpecifications, cronjobEndowmentBuilder, getCronjobCaveatM
3
3
  import { ethereumProviderEndowmentBuilder } from './ethereum-provider';
4
4
  import { lifecycleHooksEndowmentBuilder } from './lifecycle-hooks';
5
5
  import { longRunningEndowmentBuilder } from './long-running';
6
+ import { getNameLookupCaveatMapper, nameLookupCaveatSpecifications, nameLookupEndowmentBuilder } from './name-lookup';
6
7
  import { networkAccessEndowmentBuilder } from './network-access';
7
8
  import { getRpcCaveatMapper, rpcCaveatSpecifications, rpcEndowmentBuilder } from './rpc';
8
9
  import { getTransactionInsightCaveatMapper, transactionInsightCaveatSpecifications, transactionInsightEndowmentBuilder } from './transaction-insight';
@@ -15,27 +16,32 @@ export const endowmentPermissionBuilders = {
15
16
  [ethereumProviderEndowmentBuilder.targetName]: ethereumProviderEndowmentBuilder,
16
17
  [rpcEndowmentBuilder.targetName]: rpcEndowmentBuilder,
17
18
  [webAssemblyEndowmentBuilder.targetName]: webAssemblyEndowmentBuilder,
19
+ [nameLookupEndowmentBuilder.targetName]: nameLookupEndowmentBuilder,
18
20
  [lifecycleHooksEndowmentBuilder.targetName]: lifecycleHooksEndowmentBuilder
19
21
  };
20
22
  export const endowmentCaveatSpecifications = {
21
23
  ...cronjobCaveatSpecifications,
22
24
  ...transactionInsightCaveatSpecifications,
23
- ...rpcCaveatSpecifications
25
+ ...rpcCaveatSpecifications,
26
+ ...nameLookupCaveatSpecifications
24
27
  };
25
28
  export const endowmentCaveatMappers = {
26
29
  [cronjobEndowmentBuilder.targetName]: getCronjobCaveatMapper,
27
30
  [transactionInsightEndowmentBuilder.targetName]: getTransactionInsightCaveatMapper,
28
- [rpcEndowmentBuilder.targetName]: getRpcCaveatMapper
31
+ [rpcEndowmentBuilder.targetName]: getRpcCaveatMapper,
32
+ [nameLookupEndowmentBuilder.targetName]: getNameLookupCaveatMapper
29
33
  };
30
34
  export const handlerEndowments = {
31
35
  [HandlerType.OnRpcRequest]: rpcEndowmentBuilder.targetName,
32
36
  [HandlerType.OnTransaction]: transactionInsightEndowmentBuilder.targetName,
33
37
  [HandlerType.OnCronjob]: cronjobEndowmentBuilder.targetName,
38
+ [HandlerType.OnNameLookup]: nameLookupEndowmentBuilder.targetName,
34
39
  [HandlerType.OnInstall]: lifecycleHooksEndowmentBuilder.targetName,
35
40
  [HandlerType.OnUpdate]: lifecycleHooksEndowmentBuilder.targetName
36
41
  };
37
42
  export * from './enum';
38
43
  export { getRpcCaveatOrigins } from './rpc';
39
44
  export { getTransactionOriginCaveat } from './transaction-insight';
45
+ export { getChainIdsCaveat } from './name-lookup';
40
46
 
41
47
  //# 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 { 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":["HandlerType","cronjobCaveatSpecifications","cronjobEndowmentBuilder","getCronjobCaveatMapper","ethereumProviderEndowmentBuilder","lifecycleHooksEndowmentBuilder","longRunningEndowmentBuilder","networkAccessEndowmentBuilder","getRpcCaveatMapper","rpcCaveatSpecifications","rpcEndowmentBuilder","getTransactionInsightCaveatMapper","transactionInsightCaveatSpecifications","transactionInsightEndowmentBuilder","webAssemblyEndowmentBuilder","endowmentPermissionBuilders","targetName","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate","getRpcCaveatOrigins","getTransactionOriginCaveat"],"mappings":"AACA,SAASA,WAAW,QAAQ,wBAAwB;AAGpD,SACEC,2BAA2B,EAC3BC,uBAAuB,EACvBC,sBAAsB,QACjB,YAAY;AACnB,SAASC,gCAAgC,QAAQ,sBAAsB;AACvE,SAASC,8BAA8B,QAAQ,oBAAoB;AACnE,SAASC,2BAA2B,QAAQ,iBAAiB;AAC7D,SAASC,6BAA6B,QAAQ,mBAAmB;AACjE,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,mBAAmB,QACd,QAAQ;AACf,SACEC,iCAAiC,EACjCC,sCAAsC,EACtCC,kCAAkC,QAC7B,wBAAwB;AAC/B,SAASC,2BAA2B,QAAQ,iBAAiB;AAE7D,OAAO,MAAMC,8BAA8B;IACzC,CAACR,8BAA8BS,UAAU,CAAC,EAAET;IAC5C,CAACD,4BAA4BU,UAAU,CAAC,EAAEV;IAC1C,CAACO,mCAAmCG,UAAU,CAAC,EAC7CH;IACF,CAACX,wBAAwBc,UAAU,CAAC,EAAEd;IACtC,CAACE,iCAAiCY,UAAU,CAAC,EAC3CZ;IACF,CAACM,oBAAoBM,UAAU,CAAC,EAAEN;IAClC,CAACI,4BAA4BE,UAAU,CAAC,EAAEF;IAC1C,CAACT,+BAA+BW,UAAU,CAAC,EAAEX;AAC/C,EAAW;AAEX,OAAO,MAAMY,gCAAgC;IAC3C,GAAGhB,2BAA2B;IAC9B,GAAGW,sCAAsC;IACzC,GAAGH,uBAAuB;AAC5B,EAAE;AAEF,OAAO,MAAMS,yBAGT;IACF,CAAChB,wBAAwBc,UAAU,CAAC,EAAEb;IACtC,CAACU,mCAAmCG,UAAU,CAAC,EAC7CL;IACF,CAACD,oBAAoBM,UAAU,CAAC,EAAER;AACpC,EAAE;AAEF,OAAO,MAAMW,oBAAiD;IAC5D,CAACnB,YAAYoB,YAAY,CAAC,EAAEV,oBAAoBM,UAAU;IAC1D,CAAChB,YAAYqB,aAAa,CAAC,EAAER,mCAAmCG,UAAU;IAC1E,CAAChB,YAAYsB,SAAS,CAAC,EAAEpB,wBAAwBc,UAAU;IAC3D,CAAChB,YAAYuB,SAAS,CAAC,EAAElB,+BAA+BW,UAAU;IAClE,CAAChB,YAAYwB,QAAQ,CAAC,EAAEnB,+BAA+BW,UAAU;AACnE,EAAE;AAEF,cAAc,SAAS;AACvB,SAASS,mBAAmB,QAAQ,QAAQ;AAC5C,SAASC,0BAA0B,QAAQ,wBAAwB"}
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 {\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 [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 [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":["HandlerType","cronjobCaveatSpecifications","cronjobEndowmentBuilder","getCronjobCaveatMapper","ethereumProviderEndowmentBuilder","lifecycleHooksEndowmentBuilder","longRunningEndowmentBuilder","getNameLookupCaveatMapper","nameLookupCaveatSpecifications","nameLookupEndowmentBuilder","networkAccessEndowmentBuilder","getRpcCaveatMapper","rpcCaveatSpecifications","rpcEndowmentBuilder","getTransactionInsightCaveatMapper","transactionInsightCaveatSpecifications","transactionInsightEndowmentBuilder","webAssemblyEndowmentBuilder","endowmentPermissionBuilders","targetName","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","OnRpcRequest","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","getRpcCaveatOrigins","getTransactionOriginCaveat","getChainIdsCaveat"],"mappings":"AACA,SAASA,WAAW,QAAQ,wBAAwB;AAGpD,SACEC,2BAA2B,EAC3BC,uBAAuB,EACvBC,sBAAsB,QACjB,YAAY;AACnB,SAASC,gCAAgC,QAAQ,sBAAsB;AACvE,SAASC,8BAA8B,QAAQ,oBAAoB;AACnE,SAASC,2BAA2B,QAAQ,iBAAiB;AAC7D,SACEC,yBAAyB,EACzBC,8BAA8B,EAC9BC,0BAA0B,QACrB,gBAAgB;AACvB,SAASC,6BAA6B,QAAQ,mBAAmB;AACjE,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,mBAAmB,QACd,QAAQ;AACf,SACEC,iCAAiC,EACjCC,sCAAsC,EACtCC,kCAAkC,QAC7B,wBAAwB;AAC/B,SAASC,2BAA2B,QAAQ,iBAAiB;AAE7D,OAAO,MAAMC,8BAA8B;IACzC,CAACR,8BAA8BS,UAAU,CAAC,EAAET;IAC5C,CAACJ,4BAA4Ba,UAAU,CAAC,EAAEb;IAC1C,CAACU,mCAAmCG,UAAU,CAAC,EAC7CH;IACF,CAACd,wBAAwBiB,UAAU,CAAC,EAAEjB;IACtC,CAACE,iCAAiCe,UAAU,CAAC,EAC3Cf;IACF,CAACS,oBAAoBM,UAAU,CAAC,EAAEN;IAClC,CAACI,4BAA4BE,UAAU,CAAC,EAAEF;IAC1C,CAACR,2BAA2BU,UAAU,CAAC,EAAEV;IACzC,CAACJ,+BAA+Bc,UAAU,CAAC,EAAEd;AAC/C,EAAW;AAEX,OAAO,MAAMe,gCAAgC;IAC3C,GAAGnB,2BAA2B;IAC9B,GAAGc,sCAAsC;IACzC,GAAGH,uBAAuB;IAC1B,GAAGJ,8BAA8B;AACnC,EAAE;AAEF,OAAO,MAAMa,yBAGT;IACF,CAACnB,wBAAwBiB,UAAU,CAAC,EAAEhB;IACtC,CAACa,mCAAmCG,UAAU,CAAC,EAC7CL;IACF,CAACD,oBAAoBM,UAAU,CAAC,EAAER;IAClC,CAACF,2BAA2BU,UAAU,CAAC,EAAEZ;AAC3C,EAAE;AAEF,OAAO,MAAMe,oBAAiD;IAC5D,CAACtB,YAAYuB,YAAY,CAAC,EAAEV,oBAAoBM,UAAU;IAC1D,CAACnB,YAAYwB,aAAa,CAAC,EAAER,mCAAmCG,UAAU;IAC1E,CAACnB,YAAYyB,SAAS,CAAC,EAAEvB,wBAAwBiB,UAAU;IAC3D,CAACnB,YAAY0B,YAAY,CAAC,EAAEjB,2BAA2BU,UAAU;IACjE,CAACnB,YAAY2B,SAAS,CAAC,EAAEtB,+BAA+Bc,UAAU;IAClE,CAACnB,YAAY4B,QAAQ,CAAC,EAAEvB,+BAA+Bc,UAAU;AACnE,EAAE;AAEF,cAAc,SAAS;AACvB,SAASU,mBAAmB,QAAQ,QAAQ;AAC5C,SAASC,0BAA0B,QAAQ,wBAAwB;AACnE,SAASC,iBAAiB,QAAQ,gBAAgB"}
@@ -0,0 +1,98 @@
1
+ import { PermissionType, SubjectType } from '@metamask/permission-controller';
2
+ import { SnapCaveatType, isChainId } from '@metamask/snaps-utils';
3
+ import { assert, hasProperty, isPlainObject } from '@metamask/utils';
4
+ import { ethErrors } from 'eth-rpc-errors';
5
+ import { SnapEndowments } from './enum';
6
+ const permissionName = SnapEndowments.NameLookup;
7
+ /**
8
+ * `endowment:name-lookup` returns nothing; it is intended to be used as a flag
9
+ * by the extension to detect whether the snap has the capability to resolve a domain/address.
10
+ *
11
+ * @param _builderOptions - Optional specification builder options.
12
+ * @returns The specification for the name-lookup endowment.
13
+ */ const specificationBuilder = (_builderOptions)=>{
14
+ return {
15
+ permissionType: PermissionType.Endowment,
16
+ targetName: permissionName,
17
+ allowedCaveats: [
18
+ SnapCaveatType.ChainIds
19
+ ],
20
+ endowmentGetter: (_getterOptions)=>undefined,
21
+ validator: ({ caveats })=>{
22
+ if (!caveats || caveats !== null && caveats?.length > 1 || caveats?.length === 1 && caveats[0].type !== SnapCaveatType.ChainIds) {
23
+ throw ethErrors.rpc.invalidParams({
24
+ message: `Expected a single "${SnapCaveatType.ChainIds}" caveat.`
25
+ });
26
+ }
27
+ },
28
+ subjectTypes: [
29
+ SubjectType.Snap
30
+ ]
31
+ };
32
+ };
33
+ export const nameLookupEndowmentBuilder = Object.freeze({
34
+ targetName: permissionName,
35
+ specificationBuilder
36
+ });
37
+ /**
38
+ * Validates the type of the caveat value.
39
+ *
40
+ * @param caveat - The caveat to validate.
41
+ * @throws If the caveat value is invalid.
42
+ */ function validateCaveat(caveat) {
43
+ if (!hasProperty(caveat, 'value') || !isPlainObject(caveat)) {
44
+ throw ethErrors.rpc.invalidParams({
45
+ message: 'Expected a plain object.'
46
+ });
47
+ }
48
+ const { value } = caveat;
49
+ assert(Array.isArray(value) && value.every((val)=>isChainId(val)), 'Expected caveat value to have type "string array"');
50
+ }
51
+ /**
52
+ * Map a raw value from the `initialPermissions` to a caveat specification.
53
+ * Note that this function does not do any validation, that's handled by the
54
+ * PermissionsController when the permission is requested.
55
+ *
56
+ * @param value - The raw value from the `initialPermissions`.
57
+ * @returns The caveat specification.
58
+ */ export function getNameLookupCaveatMapper(value) {
59
+ if (!value || !Array.isArray(value) || Array.isArray(value) && value.length === 0) {
60
+ return {
61
+ caveats: null
62
+ };
63
+ }
64
+ return {
65
+ caveats: [
66
+ {
67
+ type: SnapCaveatType.ChainIds,
68
+ value
69
+ }
70
+ ]
71
+ };
72
+ }
73
+ /**
74
+ * Getter function to get the chainIds caveat from a permission.
75
+ *
76
+ * This does basic validation of the caveat, but does not validate the type or
77
+ * value of the namespaces object itself, as this is handled by the
78
+ * `PermissionsController` when the permission is requested.
79
+ *
80
+ * @param permission - The permission to get the `chainIds` caveat from.
81
+ * @returns An array of `chainIds` that the snap supports.
82
+ */ export function getChainIdsCaveat(permission) {
83
+ if (!permission?.caveats) {
84
+ return null;
85
+ }
86
+ assert(permission.caveats.length === 1);
87
+ assert(permission.caveats[0].type === SnapCaveatType.ChainIds);
88
+ const caveat = permission.caveats[0];
89
+ return caveat.value ?? null;
90
+ }
91
+ export const nameLookupCaveatSpecifications = {
92
+ [SnapCaveatType.ChainIds]: Object.freeze({
93
+ type: SnapCaveatType.ChainIds,
94
+ validator: (caveat)=>validateCaveat(caveat)
95
+ })
96
+ };
97
+
98
+ //# sourceMappingURL=name-lookup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/snaps/endowments/name-lookup.ts"],"sourcesContent":["import type {\n EndowmentGetterParams,\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n ValidPermissionSpecification,\n Caveat,\n CaveatSpecificationConstraint,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { SnapCaveatType, isChainId } 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.NameLookup;\n\ntype NameLookupEndowmentSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.Endowment;\n targetName: typeof permissionName;\n endowmentGetter: (_options?: EndowmentGetterParams) => undefined;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\n/**\n * `endowment:name-lookup` returns nothing; it is intended to be used as a flag\n * by the extension to detect whether the snap has the capability to resolve a domain/address.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the name-lookup endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n NameLookupEndowmentSpecification\n> = (_builderOptions?: unknown) => {\n return {\n permissionType: PermissionType.Endowment,\n targetName: permissionName,\n allowedCaveats: [SnapCaveatType.ChainIds],\n endowmentGetter: (_getterOptions?: EndowmentGetterParams) => undefined,\n validator: ({ caveats }) => {\n if (\n !caveats ||\n (caveats !== null && caveats?.length > 1) ||\n (caveats?.length === 1 && caveats[0].type !== SnapCaveatType.ChainIds)\n ) {\n throw ethErrors.rpc.invalidParams({\n message: `Expected a single \"${SnapCaveatType.ChainIds}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nexport const nameLookupEndowmentBuilder = Object.freeze({\n targetName: permissionName,\n specificationBuilder,\n} as const);\n\n/**\n * Validates the type of the caveat value.\n *\n * @param caveat - The caveat to validate.\n * @throws If the caveat value is invalid.\n */\nfunction validateCaveat(caveat: Caveat<string, any>): void {\n if (!hasProperty(caveat, 'value') || !isPlainObject(caveat)) {\n throw ethErrors.rpc.invalidParams({\n message: 'Expected a plain object.',\n });\n }\n\n const { value } = caveat;\n\n assert(\n Array.isArray(value) && value.every((val) => isChainId(val)),\n 'Expected caveat value to have type \"string array\"',\n );\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 getNameLookupCaveatMapper(\n value: Json,\n): Pick<PermissionConstraint, 'caveats'> {\n if (\n !value ||\n !Array.isArray(value) ||\n (Array.isArray(value) && value.length === 0)\n ) {\n return { caveats: null };\n }\n return {\n caveats: [\n {\n type: SnapCaveatType.ChainIds,\n value,\n },\n ],\n };\n}\n\n/**\n * Getter function to get the chainIds caveat from a permission.\n *\n * This does basic validation of the caveat, but does not validate the type or\n * value of the namespaces object itself, as this is handled by the\n * `PermissionsController` when the permission is requested.\n *\n * @param permission - The permission to get the `chainIds` caveat from.\n * @returns An array of `chainIds` that the snap supports.\n */\nexport function getChainIdsCaveat(\n permission?: PermissionConstraint,\n): string[] | null {\n if (!permission?.caveats) {\n return null;\n }\n\n assert(permission.caveats.length === 1);\n assert(permission.caveats[0].type === SnapCaveatType.ChainIds);\n\n const caveat = permission.caveats[0] as Caveat<string, string[]>;\n\n return caveat.value ?? null;\n}\n\nexport const nameLookupCaveatSpecifications: Record<\n SnapCaveatType.ChainIds,\n CaveatSpecificationConstraint\n> = {\n [SnapCaveatType.ChainIds]: Object.freeze({\n type: SnapCaveatType.ChainIds,\n validator: (caveat: Caveat<string, any>) => validateCaveat(caveat),\n }),\n};\n"],"names":["PermissionType","SubjectType","SnapCaveatType","isChainId","assert","hasProperty","isPlainObject","ethErrors","SnapEndowments","permissionName","NameLookup","specificationBuilder","_builderOptions","permissionType","Endowment","targetName","allowedCaveats","ChainIds","endowmentGetter","_getterOptions","undefined","validator","caveats","length","type","rpc","invalidParams","message","subjectTypes","Snap","nameLookupEndowmentBuilder","Object","freeze","validateCaveat","caveat","value","Array","isArray","every","val","getNameLookupCaveatMapper","getChainIdsCaveat","permission","nameLookupCaveatSpecifications"],"mappings":"AASA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,cAAc,EAAEC,SAAS,QAAQ,wBAAwB;AAElE,SAASC,MAAM,EAAEC,WAAW,EAAEC,aAAa,QAAQ,kBAAkB;AACrE,SAASC,SAAS,QAAQ,iBAAiB;AAE3C,SAASC,cAAc,QAAQ,SAAS;AAExC,MAAMC,iBAAiBD,eAAeE,UAAU;AAUhD;;;;;;C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AiC;IAEjC,IAAI,CAACA,YAAYpB,SAAS;QACxB,OAAO;IACT;IAEAlB,OAAOsC,WAAWpB,OAAO,CAACC,MAAM,KAAK;IACrCnB,OAAOsC,WAAWpB,OAAO,CAAC,EAAE,CAACE,IAAI,KAAKtB,eAAee,QAAQ;IAE7D,MAAMiB,SAASQ,WAAWpB,OAAO,CAAC,EAAE;IAEpC,OAAOY,OAAOC,KAAK,IAAI;AACzB;AAEA,OAAO,MAAMQ,iCAGT;IACF,CAACzC,eAAee,QAAQ,CAAC,EAAEc,OAAOC,MAAM,CAAC;QACvCR,MAAMtB,eAAee,QAAQ;QAC7BI,WAAW,CAACa,SAAgCD,eAAeC;IAC7D;AACF,EAAE"}
@@ -30,8 +30,8 @@ import { createSnapManifest, DEFAULT_REQUESTED_SNAP_VERSION, getTargetVersion, i
30
30
  import { assert, assertIsSemVerVersion, assertStruct, isObject } from '@metamask/utils';
31
31
  import concat from 'concat-stream';
32
32
  import createGunzipStream from 'gunzip-maybe';
33
- import pump from 'pump';
34
33
  import { ReadableWebToNodeStream } from 'readable-web-to-node-stream';
34
+ import { pipeline } from 'stream';
35
35
  import { extract as tarExtract } from 'tar-stream';
36
36
  export const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
37
37
  var _lazyInit = /*#__PURE__*/ new WeakSet();
@@ -125,7 +125,7 @@ async function lazyInit() {
125
125
  // We would need to replace tar-stream package because it requires immediate consumption of streams.
126
126
  await new Promise((resolve, reject)=>{
127
127
  this.files = new Map();
128
- pump(getNodeStream(tarballResponse), // The "gz" in "tgz" stands for "gzip". The tarball needs to be decompressed
128
+ pipeline(getNodeStream(tarballResponse), // The "gz" in "tgz" stands for "gzip". The tarball needs to be decompressed
129
129
  // before we can actually grab any files from it.
130
130
  // To prevent recursion-based zip bombs, we set a maximum recursion depth of 1.
131
131
  createGunzipStream(1), createTarballStream(`${canonicalBase}/${this.meta.packageName}/`, this.files), (error)=>{
@@ -242,7 +242,9 @@ const TARBALL_SIZE_SAFETY_LIMIT = 262144000;
242
242
  if (headerType === 'file') {
243
243
  // The name is a path if the header type is "file".
244
244
  const path = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');
245
- return entryStream.pipe(concat((data)=>{
245
+ return entryStream.pipe(concat({
246
+ encoding: 'uint8array'
247
+ }, (data)=>{
246
248
  try {
247
249
  totalSize += data.byteLength;
248
250
  // To prevent zip bombs, we set a safety limit for the total size of tarballs.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/snaps/location/npm.ts"],"sourcesContent":["import type { SnapManifest } from '@metamask/snaps-utils';\nimport {\n createSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n VirtualFile,\n normalizeRelative,\n parseJson,\n} from '@metamask/snaps-utils';\nimport type { SemVerRange, SemVerVersion } from '@metamask/utils';\nimport {\n assert,\n assertIsSemVerVersion,\n assertStruct,\n isObject,\n} from '@metamask/utils';\nimport concat from 'concat-stream';\nimport createGunzipStream from 'gunzip-maybe';\nimport pump from 'pump';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport type { Readable, Writable } from 'stream';\nimport { extract as tarExtract } from 'tar-stream';\n\nimport type { DetectSnapLocationOptions, SnapLocation } from './location';\n\nexport const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';\n\ninterface NpmMeta {\n registry: URL;\n packageName: string;\n requestedRange: SemVerRange;\n version?: string;\n fetch: typeof fetch;\n}\nexport interface NpmOptions {\n /**\n * @default DEFAULT_REQUESTED_SNAP_VERSION\n */\n versionRange?: SemVerRange;\n /**\n * Whether to allow custom NPM registries outside of {@link DEFAULT_NPM_REGISTRY}.\n *\n * @default false\n */\n allowCustomRegistries?: boolean;\n}\n\nexport class NpmLocation implements SnapLocation {\n private readonly meta: NpmMeta;\n\n private validatedManifest?: VirtualFile<SnapManifest>;\n\n private files?: Map<string, VirtualFile>;\n\n constructor(url: URL, opts: DetectSnapLocationOptions = {}) {\n const allowCustomRegistries = opts.allowCustomRegistries ?? false;\n const fetchFunction = opts.fetch ?? globalThis.fetch.bind(globalThis);\n const requestedRange = opts.versionRange ?? DEFAULT_REQUESTED_SNAP_VERSION;\n\n assertStruct(url.toString(), NpmSnapIdStruct, 'Invalid Snap Id: ');\n\n let registry: string | URL;\n if (\n url.host === '' &&\n url.port === '' &&\n url.username === '' &&\n url.password === ''\n ) {\n registry = new URL(DEFAULT_NPM_REGISTRY);\n } else {\n registry = 'https://';\n if (url.username) {\n registry += url.username;\n if (url.password) {\n registry += `:${url.password}`;\n }\n registry += '@';\n }\n registry += url.host;\n registry = new URL(registry);\n assert(\n allowCustomRegistries,\n new TypeError(\n `Custom NPM registries are disabled, tried to use \"${registry.toString()}\".`,\n ),\n );\n }\n\n assert(\n registry.pathname === '/' &&\n registry.search === '' &&\n registry.hash === '',\n );\n\n assert(\n url.pathname !== '' && url.pathname !== '/',\n new TypeError('The package name in NPM location is empty.'),\n );\n let packageName = url.pathname;\n if (packageName.startsWith('/')) {\n packageName = packageName.slice(1);\n }\n\n this.meta = {\n requestedRange,\n registry,\n packageName,\n fetch: fetchFunction,\n };\n }\n\n async manifest(): Promise<VirtualFile<SnapManifest>> {\n if (this.validatedManifest) {\n return this.validatedManifest.clone();\n }\n\n const vfile = await this.fetch('snap.manifest.json');\n const result = parseJson(vfile.toString());\n vfile.result = createSnapManifest(result);\n this.validatedManifest = vfile as VirtualFile<SnapManifest>;\n\n return this.manifest();\n }\n\n async fetch(path: string): Promise<VirtualFile> {\n const relativePath = normalizeRelative(path);\n if (!this.files) {\n await this.#lazyInit();\n assert(this.files !== undefined);\n }\n const vfile = this.files.get(relativePath);\n assert(\n vfile !== undefined,\n new TypeError(`File \"${path}\" not found in package.`),\n );\n return vfile.clone();\n }\n\n get packageName(): string {\n return this.meta.packageName;\n }\n\n get version(): string {\n assert(\n this.meta.version !== undefined,\n 'Tried to access version without first fetching NPM package.',\n );\n return this.meta.version;\n }\n\n get registry(): URL {\n return this.meta.registry;\n }\n\n get versionRange(): SemVerRange {\n return this.meta.requestedRange;\n }\n\n async #lazyInit() {\n assert(this.files === undefined);\n const [tarballResponse, actualVersion] = await fetchNpmTarball(\n this.meta.packageName,\n this.meta.requestedRange,\n this.meta.registry,\n this.meta.fetch,\n );\n this.meta.version = actualVersion;\n\n let canonicalBase = 'npm://';\n if (this.meta.registry.username !== '') {\n canonicalBase += this.meta.registry.username;\n if (this.meta.registry.password !== '') {\n canonicalBase += `:${this.meta.registry.password}`;\n }\n canonicalBase += '@';\n }\n canonicalBase += this.meta.registry.host;\n\n // TODO(ritave): Lazily extract files instead of up-front extracting all of them\n // We would need to replace tar-stream package because it requires immediate consumption of streams.\n await new Promise<void>((resolve, reject) => {\n this.files = new Map();\n pump(\n getNodeStream(tarballResponse),\n // The \"gz\" in \"tgz\" stands for \"gzip\". The tarball needs to be decompressed\n // before we can actually grab any files from it.\n // To prevent recursion-based zip bombs, we set a maximum recursion depth of 1.\n createGunzipStream(1),\n createTarballStream(\n `${canonicalBase}/${this.meta.packageName}/`,\n this.files,\n ),\n (error) => {\n error ? reject(error) : resolve();\n },\n );\n });\n }\n}\n\n// Safety limit for tarballs, 250 MB in bytes\nconst TARBALL_SIZE_SAFETY_LIMIT = 262144000;\n\n// Incomplete type\nexport type PartialNpmMetadata = {\n versions: Record<string, { dist: { tarball: string } }>;\n};\n\n/**\n * Fetches the NPM metadata of the specified package from\n * the public npm registry.\n *\n * @param packageName - The name of the package whose metadata to fetch.\n * @param registryUrl - The URL of the npm registry to fetch the metadata from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns The NPM metadata object.\n * @throws If fetching the metadata fails.\n */\nexport async function fetchNpmMetadata(\n packageName: string,\n registryUrl: URL | string,\n fetchFunction: typeof fetch,\n): Promise<PartialNpmMetadata> {\n const packageResponse = await fetchFunction(\n new URL(packageName, registryUrl).toString(),\n );\n if (!packageResponse.ok) {\n throw new Error(\n `Failed to fetch NPM registry entry. Status code: ${packageResponse.status}.`,\n );\n }\n const packageMetadata = await packageResponse.json();\n\n if (!isObject(packageMetadata)) {\n throw new Error(\n `Failed to fetch package \"${packageName}\" metadata from npm.`,\n );\n }\n\n return packageMetadata as PartialNpmMetadata;\n}\n\n/**\n * Fetches the tarball (`.tgz` file) of the specified package and version from\n * the public npm registry.\n *\n * @param packageName - The name of the package whose tarball to fetch.\n * @param versionRange - The SemVer range of the package to fetch. The highest\n * version satisfying the range will be fetched.\n * @param registryUrl - The URL of the npm registry to fetch the tarball from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns A tuple of the {@link Response} for the package tarball and the\n * actual version of the package.\n * @throws If fetching the tarball fails.\n */\nasync function fetchNpmTarball(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl: URL | string,\n fetchFunction: typeof fetch,\n): Promise<[ReadableStream, SemVerVersion]> {\n const packageMetadata = await fetchNpmMetadata(\n packageName,\n registryUrl,\n fetchFunction,\n );\n\n const versions = Object.keys(packageMetadata?.versions ?? {}).map(\n (version) => {\n assertIsSemVerVersion(version);\n return version;\n },\n );\n\n const targetVersion = getTargetVersion(versions, versionRange);\n\n if (targetVersion === null) {\n throw new Error(\n `Failed to find a matching version in npm metadata for package \"${packageName}\" and requested semver range \"${versionRange}\".`,\n );\n }\n\n const tarballUrlString =\n packageMetadata?.versions?.[targetVersion]?.dist?.tarball;\n\n if (\n !isValidUrl(tarballUrlString) ||\n !tarballUrlString.toString().endsWith('.tgz')\n ) {\n throw new Error(\n `Failed to find valid tarball URL in NPM metadata for package \"${packageName}\".`,\n );\n }\n\n // Override the tarball hostname/protocol with registryUrl hostname/protocol\n const newRegistryUrl = new URL(registryUrl);\n const newTarballUrl = new URL(tarballUrlString);\n newTarballUrl.hostname = newRegistryUrl.hostname;\n newTarballUrl.protocol = newRegistryUrl.protocol;\n\n // Perform a raw fetch because we want the Response object itself.\n const tarballResponse = await fetchFunction(newTarballUrl.toString());\n if (!tarballResponse.ok || !tarballResponse.body) {\n throw new Error(`Failed to fetch tarball for package \"${packageName}\".`);\n }\n // We assume that NPM is a good actor and provides us with a valid `content-length` header.\n const tarballSizeString = tarballResponse.headers.get('content-length');\n assert(tarballSizeString, 'Snap tarball has invalid content-length');\n const tarballSize = parseInt(tarballSizeString, 10);\n assert(\n tarballSize <= TARBALL_SIZE_SAFETY_LIMIT,\n 'Snap tarball exceeds size limit',\n );\n return [tarballResponse.body, targetVersion];\n}\n\n/**\n * The paths of files within npm tarballs appear to always be prefixed with\n * \"package/\".\n */\nconst NPM_TARBALL_PATH_PREFIX = /^package\\//u;\n\n/**\n * Converts a {@link ReadableStream} to a Node.js {@link Readable}\n * stream. Returns the stream directly if it is already a Node.js stream.\n * We can't use the native Web {@link ReadableStream} directly because the\n * other stream libraries we use expect Node.js streams.\n *\n * @param stream - The stream to convert.\n * @returns The given stream as a Node.js Readable stream.\n */\nfunction getNodeStream(stream: ReadableStream): Readable {\n if (typeof stream.getReader !== 'function') {\n return stream as unknown as Readable;\n }\n\n return new ReadableWebToNodeStream(stream);\n}\n\n/**\n * Creates a `tar-stream` that will get the necessary files from an npm Snap\n * package tarball (`.tgz` file).\n *\n * @param canonicalBase - A base URI as specified in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8}. Starting with 'npm:'. Will be used for canonicalPath vfile argument.\n * @param files - An object to write target file contents to.\n * @returns The {@link Writable} tarball extraction stream.\n */\nfunction createTarballStream(\n canonicalBase: string,\n files: Map<string, VirtualFile>,\n): Writable {\n assert(\n canonicalBase.endsWith('/'),\n \"Base needs to end with '/' for relative paths to be added as children instead of siblings.\",\n );\n\n assert(\n canonicalBase.startsWith('npm:'),\n 'Protocol mismatch, expected \"npm:\".',\n );\n // `tar-stream` is pretty old-school, so we create it first and then\n // instrument it by adding event listeners.\n const extractStream = tarExtract();\n\n let totalSize = 0;\n\n // \"entry\" is fired for every discreet entity in the tarball. This includes\n // files and folders.\n extractStream.on('entry', (header, entryStream, next) => {\n const { name: headerName, type: headerType } = header;\n if (headerType === 'file') {\n // The name is a path if the header type is \"file\".\n const path = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');\n return entryStream.pipe(\n concat((data) => {\n try {\n totalSize += data.byteLength;\n // To prevent zip bombs, we set a safety limit for the total size of tarballs.\n assert(\n totalSize < TARBALL_SIZE_SAFETY_LIMIT,\n `Snap tarball exceeds limit of ${TARBALL_SIZE_SAFETY_LIMIT} bytes.`,\n );\n const vfile = new VirtualFile({\n value: data,\n path,\n data: {\n canonicalPath: new URL(path, canonicalBase).toString(),\n },\n });\n // We disallow files having identical paths as it may confuse our checksum calculations.\n assert(\n !files.has(path),\n 'Malformed tarball, multiple files with the same path.',\n );\n files.set(path, vfile);\n return next();\n } catch (error) {\n return extractStream.destroy(error);\n }\n }),\n );\n }\n\n // If we get here, the entry is not a file, and we want to ignore. The entry\n // stream must be drained, or the extractStream will stop reading. This is\n // effectively a no-op for the current entry.\n entryStream.on('end', () => next());\n return entryStream.resume();\n });\n return extractStream;\n}\n"],"names":["createSnapManifest","DEFAULT_REQUESTED_SNAP_VERSION","getTargetVersion","isValidUrl","NpmSnapIdStruct","VirtualFile","normalizeRelative","parseJson","assert","assertIsSemVerVersion","assertStruct","isObject","concat","createGunzipStream","pump","ReadableWebToNodeStream","extract","tarExtract","DEFAULT_NPM_REGISTRY","NpmLocation","manifest","validatedManifest","clone","vfile","fetch","result","toString","path","relativePath","files","lazyInit","undefined","get","TypeError","packageName","meta","version","registry","versionRange","requestedRange","constructor","url","opts","allowCustomRegistries","fetchFunction","globalThis","bind","host","port","username","password","URL","pathname","search","hash","startsWith","slice","tarballResponse","actualVersion","fetchNpmTarball","canonicalBase","Promise","resolve","reject","Map","getNodeStream","createTarballStream","error","TARBALL_SIZE_SAFETY_LIMIT","fetchNpmMetadata","registryUrl","packageResponse","ok","Error","status","packageMetadata","json","versions","Object","keys","map","targetVersion","tarballUrlString","dist","tarball","endsWith","newRegistryUrl","newTarballUrl","hostname","protocol","body","tarballSizeString","headers","tarballSize","parseInt","NPM_TARBALL_PATH_PREFIX","stream","getReader","extractStream","totalSize","on","header","entryStream","next","name","headerName","type","headerType","replace","pipe","data","byteLength","value","canonicalPath","has","set","destroy","resume"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SACEA,kBAAkB,EAClBC,8BAA8B,EAC9BC,gBAAgB,EAChBC,UAAU,EACVC,eAAe,EACfC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,QACJ,wBAAwB;AAE/B,SACEC,MAAM,EACNC,qBAAqB,EACrBC,YAAY,EACZC,QAAQ,QACH,kBAAkB;AACzB,OAAOC,YAAY,gBAAgB;AACnC,OAAOC,wBAAwB,eAAe;AAC9C,OAAOC,UAAU,OAAO;AACxB,SAASC,uBAAuB,QAAQ,8BAA8B;AAEtE,SAASC,WAAWC,UAAU,QAAQ,aAAa;AAInD,OAAO,MAAMC,uBAAuB,6BAA6B;IAqIzD;AA/GR,OAAO,MAAMC;IAgEX,MAAMC,WAA+C;QACnD,IAAI,IAAI,CAACC,iBAAiB,EAAE;YAC1B,OAAO,IAAI,CAACA,iBAAiB,CAACC,KAAK;QACrC;QAEA,MAAMC,QAAQ,MAAM,IAAI,CAACC,KAAK,CAAC;QAC/B,MAAMC,SAASlB,UAAUgB,MAAMG,QAAQ;QACvCH,MAAME,MAAM,GAAGzB,mBAAmByB;QAClC,IAAI,CAACJ,iBAAiB,GAAGE;QAEzB,OAAO,IAAI,CAACH,QAAQ;IACtB;IAEA,MAAMI,MAAMG,IAAY,EAAwB;QAC9C,MAAMC,eAAetB,kBAAkBqB;QACvC,IAAI,CAAC,IAAI,CAACE,KAAK,EAAE;YACf,MAAM,0BAAA,IAAI,EAAEC,WAAAA,eAAN,IAAI;YACVtB,OAAO,IAAI,CAACqB,KAAK,KAAKE;QACxB;QACA,MAAMR,QAAQ,IAAI,CAACM,KAAK,CAACG,GAAG,CAACJ;QAC7BpB,OACEe,U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AoE;IACpE,2CAA2C;IAC3C,MAAM2C,gBAAgBjF;IAEtB,IAAIkF,YAAY;IAEhB,2EAA2E;IAC3E,qBAAqB;IACrBD,cAAcE,EAAE,CAAC,SAAS,CAACC,QAAQC,aAAaC;QAC9C,MAAM,EAAEC,MAAMC,UAAU,EAAEC,MAAMC,UAAU,EAAE,GAAGN;QAC/C,IAAIM,eAAe,QAAQ;YACzB,mDAAmD;YACnD,MAAMhF,OAAO8E,WAAWG,OAAO,CAACb,yBAAyB;YACzD,OAAOO,YAAYO,IAAI,CACrBjG,OAAO,CAACkG;gBACN,IAAI;oBACFX,aAAaW,KAAKC,UAAU;oBAC5B,8EAA8E;oBAC9EvG,OACE2F,YAAY/B,2BACZ,CAAC,8BAA8B,EAAEA,0BAA0B,OAAO,CAAC;oBAErE,MAAM7C,QAAQ,IAAIlB,YAAY;wBAC5B2G,OAAOF;wBACPnF;wBACAmF,MAAM;4BACJG,eAAe,IAAI9D,IAAIxB,MAAMiC,eAAelC,QAAQ;wBACtD;oBACF;oBACA,wFAAwF;oBACxFlB,OACE,CAACqB,MAAMqF,GAAG,CAACvF,OACX;oBAEFE,MAAMsF,GAAG,CAACxF,MAAMJ;oBAChB,OAAOgF;gBACT,EAAE,OAAOpC,OAAO;oBACd,OAAO+B,cAAckB,OAAO,CAACjD;gBAC/B;YACF;QAEJ;QAEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7CmC,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYe,MAAM;IAC3B;IACA,OAAOnB;AACT"}
1
+ {"version":3,"sources":["../../../../src/snaps/location/npm.ts"],"sourcesContent":["import type { SnapManifest } from '@metamask/snaps-utils';\nimport {\n createSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n VirtualFile,\n normalizeRelative,\n parseJson,\n} from '@metamask/snaps-utils';\nimport type { SemVerRange, SemVerVersion } from '@metamask/utils';\nimport {\n assert,\n assertIsSemVerVersion,\n assertStruct,\n isObject,\n} from '@metamask/utils';\nimport concat from 'concat-stream';\nimport createGunzipStream from 'gunzip-maybe';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { pipeline } from 'stream';\nimport type { Readable, Writable } from 'stream';\nimport { extract as tarExtract } from 'tar-stream';\n\nimport type { DetectSnapLocationOptions, SnapLocation } from './location';\n\nexport const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';\n\ninterface NpmMeta {\n registry: URL;\n packageName: string;\n requestedRange: SemVerRange;\n version?: string;\n fetch: typeof fetch;\n}\nexport interface NpmOptions {\n /**\n * @default DEFAULT_REQUESTED_SNAP_VERSION\n */\n versionRange?: SemVerRange;\n /**\n * Whether to allow custom NPM registries outside of {@link DEFAULT_NPM_REGISTRY}.\n *\n * @default false\n */\n allowCustomRegistries?: boolean;\n}\n\nexport class NpmLocation implements SnapLocation {\n private readonly meta: NpmMeta;\n\n private validatedManifest?: VirtualFile<SnapManifest>;\n\n private files?: Map<string, VirtualFile>;\n\n constructor(url: URL, opts: DetectSnapLocationOptions = {}) {\n const allowCustomRegistries = opts.allowCustomRegistries ?? false;\n const fetchFunction = opts.fetch ?? globalThis.fetch.bind(globalThis);\n const requestedRange = opts.versionRange ?? DEFAULT_REQUESTED_SNAP_VERSION;\n\n assertStruct(url.toString(), NpmSnapIdStruct, 'Invalid Snap Id: ');\n\n let registry: string | URL;\n if (\n url.host === '' &&\n url.port === '' &&\n url.username === '' &&\n url.password === ''\n ) {\n registry = new URL(DEFAULT_NPM_REGISTRY);\n } else {\n registry = 'https://';\n if (url.username) {\n registry += url.username;\n if (url.password) {\n registry += `:${url.password}`;\n }\n registry += '@';\n }\n registry += url.host;\n registry = new URL(registry);\n assert(\n allowCustomRegistries,\n new TypeError(\n `Custom NPM registries are disabled, tried to use \"${registry.toString()}\".`,\n ),\n );\n }\n\n assert(\n registry.pathname === '/' &&\n registry.search === '' &&\n registry.hash === '',\n );\n\n assert(\n url.pathname !== '' && url.pathname !== '/',\n new TypeError('The package name in NPM location is empty.'),\n );\n let packageName = url.pathname;\n if (packageName.startsWith('/')) {\n packageName = packageName.slice(1);\n }\n\n this.meta = {\n requestedRange,\n registry,\n packageName,\n fetch: fetchFunction,\n };\n }\n\n async manifest(): Promise<VirtualFile<SnapManifest>> {\n if (this.validatedManifest) {\n return this.validatedManifest.clone();\n }\n\n const vfile = await this.fetch('snap.manifest.json');\n const result = parseJson(vfile.toString());\n vfile.result = createSnapManifest(result);\n this.validatedManifest = vfile as VirtualFile<SnapManifest>;\n\n return this.manifest();\n }\n\n async fetch(path: string): Promise<VirtualFile> {\n const relativePath = normalizeRelative(path);\n if (!this.files) {\n await this.#lazyInit();\n assert(this.files !== undefined);\n }\n const vfile = this.files.get(relativePath);\n assert(\n vfile !== undefined,\n new TypeError(`File \"${path}\" not found in package.`),\n );\n return vfile.clone();\n }\n\n get packageName(): string {\n return this.meta.packageName;\n }\n\n get version(): string {\n assert(\n this.meta.version !== undefined,\n 'Tried to access version without first fetching NPM package.',\n );\n return this.meta.version;\n }\n\n get registry(): URL {\n return this.meta.registry;\n }\n\n get versionRange(): SemVerRange {\n return this.meta.requestedRange;\n }\n\n async #lazyInit() {\n assert(this.files === undefined);\n const [tarballResponse, actualVersion] = await fetchNpmTarball(\n this.meta.packageName,\n this.meta.requestedRange,\n this.meta.registry,\n this.meta.fetch,\n );\n this.meta.version = actualVersion;\n\n let canonicalBase = 'npm://';\n if (this.meta.registry.username !== '') {\n canonicalBase += this.meta.registry.username;\n if (this.meta.registry.password !== '') {\n canonicalBase += `:${this.meta.registry.password}`;\n }\n canonicalBase += '@';\n }\n canonicalBase += this.meta.registry.host;\n\n // TODO(ritave): Lazily extract files instead of up-front extracting all of them\n // We would need to replace tar-stream package because it requires immediate consumption of streams.\n await new Promise<void>((resolve, reject) => {\n this.files = new Map();\n pipeline(\n getNodeStream(tarballResponse),\n // The \"gz\" in \"tgz\" stands for \"gzip\". The tarball needs to be decompressed\n // before we can actually grab any files from it.\n // To prevent recursion-based zip bombs, we set a maximum recursion depth of 1.\n createGunzipStream(1),\n createTarballStream(\n `${canonicalBase}/${this.meta.packageName}/`,\n this.files,\n ),\n (error) => {\n error ? reject(error) : resolve();\n },\n );\n });\n }\n}\n\n// Safety limit for tarballs, 250 MB in bytes\nconst TARBALL_SIZE_SAFETY_LIMIT = 262144000;\n\n// Incomplete type\nexport type PartialNpmMetadata = {\n versions: Record<string, { dist: { tarball: string } }>;\n};\n\n/**\n * Fetches the NPM metadata of the specified package from\n * the public npm registry.\n *\n * @param packageName - The name of the package whose metadata to fetch.\n * @param registryUrl - The URL of the npm registry to fetch the metadata from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns The NPM metadata object.\n * @throws If fetching the metadata fails.\n */\nexport async function fetchNpmMetadata(\n packageName: string,\n registryUrl: URL | string,\n fetchFunction: typeof fetch,\n): Promise<PartialNpmMetadata> {\n const packageResponse = await fetchFunction(\n new URL(packageName, registryUrl).toString(),\n );\n if (!packageResponse.ok) {\n throw new Error(\n `Failed to fetch NPM registry entry. Status code: ${packageResponse.status}.`,\n );\n }\n const packageMetadata = await packageResponse.json();\n\n if (!isObject(packageMetadata)) {\n throw new Error(\n `Failed to fetch package \"${packageName}\" metadata from npm.`,\n );\n }\n\n return packageMetadata as PartialNpmMetadata;\n}\n\n/**\n * Fetches the tarball (`.tgz` file) of the specified package and version from\n * the public npm registry.\n *\n * @param packageName - The name of the package whose tarball to fetch.\n * @param versionRange - The SemVer range of the package to fetch. The highest\n * version satisfying the range will be fetched.\n * @param registryUrl - The URL of the npm registry to fetch the tarball from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns A tuple of the {@link Response} for the package tarball and the\n * actual version of the package.\n * @throws If fetching the tarball fails.\n */\nasync function fetchNpmTarball(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl: URL | string,\n fetchFunction: typeof fetch,\n): Promise<[ReadableStream, SemVerVersion]> {\n const packageMetadata = await fetchNpmMetadata(\n packageName,\n registryUrl,\n fetchFunction,\n );\n\n const versions = Object.keys(packageMetadata?.versions ?? {}).map(\n (version) => {\n assertIsSemVerVersion(version);\n return version;\n },\n );\n\n const targetVersion = getTargetVersion(versions, versionRange);\n\n if (targetVersion === null) {\n throw new Error(\n `Failed to find a matching version in npm metadata for package \"${packageName}\" and requested semver range \"${versionRange}\".`,\n );\n }\n\n const tarballUrlString =\n packageMetadata?.versions?.[targetVersion]?.dist?.tarball;\n\n if (\n !isValidUrl(tarballUrlString) ||\n !tarballUrlString.toString().endsWith('.tgz')\n ) {\n throw new Error(\n `Failed to find valid tarball URL in NPM metadata for package \"${packageName}\".`,\n );\n }\n\n // Override the tarball hostname/protocol with registryUrl hostname/protocol\n const newRegistryUrl = new URL(registryUrl);\n const newTarballUrl = new URL(tarballUrlString);\n newTarballUrl.hostname = newRegistryUrl.hostname;\n newTarballUrl.protocol = newRegistryUrl.protocol;\n\n // Perform a raw fetch because we want the Response object itself.\n const tarballResponse = await fetchFunction(newTarballUrl.toString());\n if (!tarballResponse.ok || !tarballResponse.body) {\n throw new Error(`Failed to fetch tarball for package \"${packageName}\".`);\n }\n // We assume that NPM is a good actor and provides us with a valid `content-length` header.\n const tarballSizeString = tarballResponse.headers.get('content-length');\n assert(tarballSizeString, 'Snap tarball has invalid content-length');\n const tarballSize = parseInt(tarballSizeString, 10);\n assert(\n tarballSize <= TARBALL_SIZE_SAFETY_LIMIT,\n 'Snap tarball exceeds size limit',\n );\n return [tarballResponse.body, targetVersion];\n}\n\n/**\n * The paths of files within npm tarballs appear to always be prefixed with\n * \"package/\".\n */\nconst NPM_TARBALL_PATH_PREFIX = /^package\\//u;\n\n/**\n * Converts a {@link ReadableStream} to a Node.js {@link Readable}\n * stream. Returns the stream directly if it is already a Node.js stream.\n * We can't use the native Web {@link ReadableStream} directly because the\n * other stream libraries we use expect Node.js streams.\n *\n * @param stream - The stream to convert.\n * @returns The given stream as a Node.js Readable stream.\n */\nfunction getNodeStream(stream: ReadableStream): Readable {\n if (typeof stream.getReader !== 'function') {\n return stream as unknown as Readable;\n }\n\n return new ReadableWebToNodeStream(stream);\n}\n\n/**\n * Creates a `tar-stream` that will get the necessary files from an npm Snap\n * package tarball (`.tgz` file).\n *\n * @param canonicalBase - A base URI as specified in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8}. Starting with 'npm:'. Will be used for canonicalPath vfile argument.\n * @param files - An object to write target file contents to.\n * @returns The {@link Writable} tarball extraction stream.\n */\nfunction createTarballStream(\n canonicalBase: string,\n files: Map<string, VirtualFile>,\n): Writable {\n assert(\n canonicalBase.endsWith('/'),\n \"Base needs to end with '/' for relative paths to be added as children instead of siblings.\",\n );\n\n assert(\n canonicalBase.startsWith('npm:'),\n 'Protocol mismatch, expected \"npm:\".',\n );\n // `tar-stream` is pretty old-school, so we create it first and then\n // instrument it by adding event listeners.\n const extractStream = tarExtract();\n\n let totalSize = 0;\n\n // \"entry\" is fired for every discreet entity in the tarball. This includes\n // files and folders.\n extractStream.on('entry', (header, entryStream, next) => {\n const { name: headerName, type: headerType } = header;\n if (headerType === 'file') {\n // The name is a path if the header type is \"file\".\n const path = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');\n return entryStream.pipe(\n concat({ encoding: 'uint8array' }, (data) => {\n try {\n totalSize += data.byteLength;\n // To prevent zip bombs, we set a safety limit for the total size of tarballs.\n assert(\n totalSize < TARBALL_SIZE_SAFETY_LIMIT,\n `Snap tarball exceeds limit of ${TARBALL_SIZE_SAFETY_LIMIT} bytes.`,\n );\n const vfile = new VirtualFile({\n value: data,\n path,\n data: {\n canonicalPath: new URL(path, canonicalBase).toString(),\n },\n });\n // We disallow files having identical paths as it may confuse our checksum calculations.\n assert(\n !files.has(path),\n 'Malformed tarball, multiple files with the same path.',\n );\n files.set(path, vfile);\n return next();\n } catch (error) {\n return extractStream.destroy(error);\n }\n }),\n );\n }\n\n // If we get here, the entry is not a file, and we want to ignore. The entry\n // stream must be drained, or the extractStream will stop reading. This is\n // effectively a no-op for the current entry.\n entryStream.on('end', () => next());\n return entryStream.resume();\n });\n return extractStream;\n}\n"],"names":["createSnapManifest","DEFAULT_REQUESTED_SNAP_VERSION","getTargetVersion","isValidUrl","NpmSnapIdStruct","VirtualFile","normalizeRelative","parseJson","assert","assertIsSemVerVersion","assertStruct","isObject","concat","createGunzipStream","ReadableWebToNodeStream","pipeline","extract","tarExtract","DEFAULT_NPM_REGISTRY","NpmLocation","manifest","validatedManifest","clone","vfile","fetch","result","toString","path","relativePath","files","lazyInit","undefined","get","TypeError","packageName","meta","version","registry","versionRange","requestedRange","constructor","url","opts","allowCustomRegistries","fetchFunction","globalThis","bind","host","port","username","password","URL","pathname","search","hash","startsWith","slice","tarballResponse","actualVersion","fetchNpmTarball","canonicalBase","Promise","resolve","reject","Map","getNodeStream","createTarballStream","error","TARBALL_SIZE_SAFETY_LIMIT","fetchNpmMetadata","registryUrl","packageResponse","ok","Error","status","packageMetadata","json","versions","Object","keys","map","targetVersion","tarballUrlString","dist","tarball","endsWith","newRegistryUrl","newTarballUrl","hostname","protocol","body","tarballSizeString","headers","tarballSize","parseInt","NPM_TARBALL_PATH_PREFIX","stream","getReader","extractStream","totalSize","on","header","entryStream","next","name","headerName","type","headerType","replace","pipe","encoding","data","byteLength","value","canonicalPath","has","set","destroy","resume"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SACEA,kBAAkB,EAClBC,8BAA8B,EAC9BC,gBAAgB,EAChBC,UAAU,EACVC,eAAe,EACfC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,QACJ,wBAAwB;AAE/B,SACEC,MAAM,EACNC,qBAAqB,EACrBC,YAAY,EACZC,QAAQ,QACH,kBAAkB;AACzB,OAAOC,YAAY,gBAAgB;AACnC,OAAOC,wBAAwB,eAAe;AAC9C,SAASC,uBAAuB,QAAQ,8B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AAEA,0BAA0B,OAAO,CAAC;oBAErE,MAAM7C,QAAQ,IAAIlB,YAAY;wBAC5B4G,OAAOF;wBACPpF;wBACAoF,MAAM;4BACJG,eAAe,IAAI/D,IAAIxB,MAAMiC,eAAelC,QAAQ;wBACtD;oBACF;oBACA,wFAAwF;oBACxFlB,OACE,CAACqB,MAAMsF,GAAG,CAACxF,OACX;oBAEFE,MAAMuF,GAAG,CAACzF,MAAMJ;oBAChB,OAAOgF;gBACT,EAAE,OAAOpC,OAAO;oBACd,OAAO+B,cAAcmB,OAAO,CAAClD;gBAC/B;YACF;QAEJ;QAEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7CmC,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYgB,MAAM;IAC3B;IACA,OAAOpB;AACT"}
@@ -2,10 +2,10 @@ import type { RestrictedControllerMessenger } from '@metamask/base-controller';
2
2
  import { BaseControllerV2 as BaseController } from '@metamask/base-controller';
3
3
  import type { GetPermissions } from '@metamask/permission-controller';
4
4
  import type { SnapId, ValidatedSnapId, CronjobSpecification } from '@metamask/snaps-utils';
5
- import type { GetAllSnaps, HandleSnapRequest, SnapInstalled, SnapRemoved, SnapUpdated } from '..';
5
+ import type { GetAllSnaps, HandleSnapRequest, SnapDisabled, SnapEnabled, SnapInstalled, SnapRemoved, SnapUpdated } from '..';
6
6
  import { Timer } from '../snaps/Timer';
7
7
  export declare type CronjobControllerActions = GetAllSnaps | HandleSnapRequest | GetPermissions;
8
- export declare type CronjobControllerEvents = SnapInstalled | SnapRemoved | SnapUpdated;
8
+ export declare type CronjobControllerEvents = SnapInstalled | SnapRemoved | SnapUpdated | SnapEnabled | SnapDisabled;
9
9
  export declare type CronjobControllerMessenger = RestrictedControllerMessenger<'CronjobController', CronjobControllerActions, CronjobControllerEvents, CronjobControllerActions['type'], CronjobControllerEvents['type']>;
10
10
  export declare const DAILY_TIMEOUT: number;
11
11
  export declare type CronjobControllerArgs = {
@@ -96,17 +96,17 @@ export declare class CronjobController extends BaseController<typeof controllerN
96
96
  */
97
97
  destroy(): void;
98
98
  /**
99
- * Handle cron jobs on 'snapInstalled' event.
99
+ * Handle events that should cause cronjobs to be registered.
100
100
  *
101
101
  * @param snap - Basic Snap information.
102
102
  */
103
- private _handleEventSnapInstalled;
103
+ private _handleSnapRegisterEvent;
104
104
  /**
105
- * Handle cron jobs on 'snapRemoved' event.
105
+ * Handle events that should cause cronjobs to be unregistered.
106
106
  *
107
107
  * @param snap - Basic Snap information.
108
108
  */
109
- private _handleEventSnapRemoved;
109
+ private _handleSnapUnregisterEvent;
110
110
  /**
111
111
  * Handle cron jobs on 'snapUpdated' event.
112
112
  *
@@ -240,7 +240,22 @@ export declare type SnapTerminated = {
240
240
  type: `${typeof controllerName}:snapTerminated`;
241
241
  payload: [snap: TruncatedSnap];
242
242
  };
243
- export declare type SnapControllerEvents = SnapAdded | SnapBlocked | SnapInstalled | SnapRemoved | SnapStateChange | SnapUnblocked | SnapUpdated | SnapRolledback | SnapTerminated;
243
+ /**
244
+ * Emitted when a Snap is enabled by a user.
245
+ * This is not emitted by default when installing a snap.
246
+ */
247
+ export declare type SnapEnabled = {
248
+ type: `${typeof controllerName}:snapEnabled`;
249
+ payload: [snap: TruncatedSnap];
250
+ };
251
+ /**
252
+ * Emitted when a Snap is disabled by a user.
253
+ */
254
+ export declare type SnapDisabled = {
255
+ type: `${typeof controllerName}:snapDisabled`;
256
+ payload: [snap: TruncatedSnap];
257
+ };
258
+ export declare type SnapControllerEvents = SnapAdded | SnapBlocked | SnapInstalled | SnapRemoved | SnapStateChange | SnapUnblocked | SnapUpdated | SnapRolledback | SnapTerminated | SnapEnabled | SnapDisabled;
244
259
  export declare type AllowedActions = GetEndowments | GetPermissions | GetSubjects | GetSubjectMetadata | HasPermission | HasPermissions | RevokePermissions | RevokeAllPermissions | RevokePermissionForAllSubjects | GrantPermissions | AddApprovalRequest | HandleRpcRequestAction | ExecuteSnapAction | TerminateAllSnapsAction | TerminateSnapAction | UpdateCaveat | UpdateRequestState | GetResult | GetMetadata | Update;
245
260
  export declare type AllowedEvents = ExecutionServiceEvents | SnapInstalled | SnapUpdated;
246
261
  declare type SnapControllerMessenger = RestrictedControllerMessenger<typeof controllerName, SnapControllerActions | AllowedActions, SnapControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
@@ -6,5 +6,6 @@ export declare enum SnapEndowments {
6
6
  EthereumProvider = "endowment:ethereum-provider",
7
7
  Rpc = "endowment:rpc",
8
8
  WebAssemblyAccess = "endowment:webassembly",
9
+ NameLookup = "endowment:name-lookup",
9
10
  LifecycleHooks = "endowment:lifecycle-hooks"
10
11
  }
@@ -68,6 +68,16 @@ export declare const endowmentPermissionBuilders: {
68
68
  allowedCaveats: null;
69
69
  }>;
70
70
  }>;
71
+ readonly "endowment:name-lookup": Readonly<{
72
+ readonly targetName: import("./enum").SnapEndowments.NameLookup;
73
+ readonly specificationBuilder: import("@metamask/permission-controller").PermissionSpecificationBuilder<import("@metamask/permission-controller").PermissionType.Endowment, any, {
74
+ permissionType: import("@metamask/permission-controller").PermissionType.Endowment;
75
+ targetName: import("./enum").SnapEndowments.NameLookup;
76
+ endowmentGetter: (_options?: import("@metamask/permission-controller").EndowmentGetterParams | undefined) => undefined;
77
+ allowedCaveats: readonly [string, ...string[]] | null;
78
+ validator: import("@metamask/permission-controller").PermissionValidatorConstraint;
79
+ }>;
80
+ }>;
71
81
  readonly "endowment:lifecycle-hooks": Readonly<{
72
82
  readonly targetName: import("./enum").SnapEndowments.LifecycleHooks;
73
83
  readonly specificationBuilder: import("@metamask/permission-controller").PermissionSpecificationBuilder<import("@metamask/permission-controller").PermissionType.Endowment, any, {
@@ -79,6 +89,7 @@ export declare const endowmentPermissionBuilders: {
79
89
  }>;
80
90
  };
81
91
  export declare const endowmentCaveatSpecifications: {
92
+ chainIds: import("@metamask/permission-controller").CaveatSpecificationConstraint;
82
93
  rpcOrigin: import("@metamask/permission-controller").CaveatSpecificationConstraint;
83
94
  transactionOrigin: import("@metamask/permission-controller").CaveatSpecificationConstraint;
84
95
  snapCronjob: import("@metamask/permission-controller").CaveatSpecificationConstraint;
@@ -88,3 +99,4 @@ export declare const handlerEndowments: Record<HandlerType, string>;
88
99
  export * from './enum';
89
100
  export { getRpcCaveatOrigins } from './rpc';
90
101
  export { getTransactionOriginCaveat } from './transaction-insight';
102
+ export { getChainIdsCaveat } from './name-lookup';
@@ -0,0 +1,38 @@
1
+ import type { EndowmentGetterParams, PermissionSpecificationBuilder, PermissionValidatorConstraint, CaveatSpecificationConstraint, PermissionConstraint } from '@metamask/permission-controller';
2
+ import { PermissionType } from '@metamask/permission-controller';
3
+ import { SnapCaveatType } from '@metamask/snaps-utils';
4
+ import type { Json, NonEmptyArray } from '@metamask/utils';
5
+ import { SnapEndowments } from './enum';
6
+ declare const permissionName = SnapEndowments.NameLookup;
7
+ export declare const nameLookupEndowmentBuilder: Readonly<{
8
+ readonly targetName: SnapEndowments.NameLookup;
9
+ readonly specificationBuilder: PermissionSpecificationBuilder<PermissionType.Endowment, any, {
10
+ permissionType: PermissionType.Endowment;
11
+ targetName: typeof permissionName;
12
+ endowmentGetter: (_options?: EndowmentGetterParams) => undefined;
13
+ allowedCaveats: Readonly<NonEmptyArray<string>> | null;
14
+ validator: PermissionValidatorConstraint;
15
+ }>;
16
+ }>;
17
+ /**
18
+ * Map a raw value from the `initialPermissions` to a caveat specification.
19
+ * Note that this function does not do any validation, that's handled by the
20
+ * PermissionsController when the permission is requested.
21
+ *
22
+ * @param value - The raw value from the `initialPermissions`.
23
+ * @returns The caveat specification.
24
+ */
25
+ export declare function getNameLookupCaveatMapper(value: Json): Pick<PermissionConstraint, 'caveats'>;
26
+ /**
27
+ * Getter function to get the chainIds caveat from a permission.
28
+ *
29
+ * This does basic validation of the caveat, but does not validate the type or
30
+ * value of the namespaces object itself, as this is handled by the
31
+ * `PermissionsController` when the permission is requested.
32
+ *
33
+ * @param permission - The permission to get the `chainIds` caveat from.
34
+ * @returns An array of `chainIds` that the snap supports.
35
+ */
36
+ export declare function getChainIdsCaveat(permission?: PermissionConstraint): string[] | null;
37
+ export declare const nameLookupCaveatSpecifications: Record<SnapCaveatType.ChainIds, CaveatSpecificationConstraint>;
38
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-controllers",
3
- "version": "0.38.2-flask.1",
3
+ "version": "0.39.0-flask.1",
4
4
  "description": "Controllers for MetaMask Snaps.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -47,12 +47,12 @@
47
47
  "@metamask/base-controller": "^3.2.0",
48
48
  "@metamask/object-multiplex": "^1.2.0",
49
49
  "@metamask/permission-controller": "^4.1.0",
50
- "@metamask/post-message-stream": "^6.1.2",
51
- "@metamask/rpc-methods": "^0.38.1-flask.1",
52
- "@metamask/snaps-execution-environments": "^0.38.2-flask.1",
53
- "@metamask/snaps-registry": "^1.2.1",
54
- "@metamask/snaps-utils": "^0.38.2-flask.1",
55
- "@metamask/utils": "^6.0.1",
50
+ "@metamask/post-message-stream": "^7.0.0",
51
+ "@metamask/rpc-methods": "^0.38.3-flask.1",
52
+ "@metamask/snaps-execution-environments": "^0.39.0-flask.1",
53
+ "@metamask/snaps-registry": "^2.0.0",
54
+ "@metamask/snaps-utils": "^0.38.4-flask.1",
55
+ "@metamask/utils": "^8.1.0",
56
56
  "@xstate/fsm": "^2.0.0",
57
57
  "concat-stream": "^2.0.0",
58
58
  "eth-rpc-errors": "^4.0.3",
@@ -61,7 +61,6 @@
61
61
  "json-rpc-engine": "^6.1.0",
62
62
  "json-rpc-middleware-stream": "^4.2.0",
63
63
  "nanoid": "^3.1.31",
64
- "pump": "^3.0.0",
65
64
  "readable-web-to-node-stream": "^3.0.2",
66
65
  "tar-stream": "^2.2.0"
67
66
  },
@@ -83,21 +82,20 @@
83
82
  "@types/gunzip-maybe": "^1.4.0",
84
83
  "@types/jest": "^27.5.1",
85
84
  "@types/mocha": "^10.0.1",
86
- "@types/node": "^20.3.1",
87
- "@types/pump": "^1.1.1",
85
+ "@types/node": "18.14.2",
88
86
  "@types/readable-stream": "^2.3.15",
89
87
  "@types/tar-stream": "^2.2.2",
90
88
  "@typescript-eslint/eslint-plugin": "^5.42.1",
91
89
  "@typescript-eslint/parser": "^5.42.1",
92
- "@wdio/browser-runner": "^8.5.2",
93
- "@wdio/cli": "^8.5.2",
94
- "@wdio/globals": "^8.5.2",
95
- "@wdio/mocha-framework": "^8.5.2",
96
- "@wdio/spec-reporter": "^8.5.2",
97
- "@wdio/static-server-service": "^8.5.2",
90
+ "@wdio/browser-runner": "^8.15.9",
91
+ "@wdio/cli": "^8.15.9",
92
+ "@wdio/globals": "^8.15.9",
93
+ "@wdio/mocha-framework": "^8.15.9",
94
+ "@wdio/spec-reporter": "^8.15.7",
95
+ "@wdio/static-server-service": "^8.15.7",
98
96
  "deepmerge": "^4.2.2",
99
97
  "depcheck": "^1.4.5",
100
- "esbuild": "^0.17.15",
98
+ "esbuild": "^0.18.10",
101
99
  "eslint": "^8.27.0",
102
100
  "eslint-config-prettier": "^8.5.0",
103
101
  "eslint-plugin-import": "^2.26.0",
@@ -121,8 +119,8 @@
121
119
  "vite": "^4.3.9",
122
120
  "vite-tsconfig-paths": "^4.0.5",
123
121
  "wdio-chromedriver-service": "^8.1.1",
124
- "wdio-geckodriver-service": "^4.1.0",
125
- "webdriverio": "^8.5.2"
122
+ "wdio-geckodriver-service": "^5.0.2",
123
+ "webdriverio": "^8.15.9"
126
124
  },
127
125
  "engines": {
128
126
  "node": ">=16.0.0"