@metamask/snaps-controllers 4.0.0 → 4.1.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/dist/cjs/services/ProxyPostMessageStream.js +3 -10
  3. package/dist/cjs/services/ProxyPostMessageStream.js.map +1 -1
  4. package/dist/cjs/services/node/NodeProcessExecutionService.js +13 -1
  5. package/dist/cjs/services/node/NodeProcessExecutionService.js.map +1 -1
  6. package/dist/cjs/services/node/NodeThreadExecutionService.js +14 -1
  7. package/dist/cjs/services/node/NodeThreadExecutionService.js.map +1 -1
  8. package/dist/cjs/services/offscreen/OffscreenExecutionService.js +36 -99
  9. package/dist/cjs/services/offscreen/OffscreenExecutionService.js.map +1 -1
  10. package/dist/cjs/services/proxy/ProxyExecutionService.js +110 -0
  11. package/dist/cjs/services/proxy/ProxyExecutionService.js.map +1 -0
  12. package/dist/cjs/snaps/SnapController.js +198 -93
  13. package/dist/cjs/snaps/SnapController.js.map +1 -1
  14. package/dist/cjs/snaps/endowments/enum.js +1 -0
  15. package/dist/cjs/snaps/endowments/enum.js.map +1 -1
  16. package/dist/cjs/snaps/endowments/index.js +12 -4
  17. package/dist/cjs/snaps/endowments/index.js.map +1 -1
  18. package/dist/cjs/snaps/endowments/signature-insight.js +106 -0
  19. package/dist/cjs/snaps/endowments/signature-insight.js.map +1 -0
  20. package/dist/cjs/utils.js +32 -0
  21. package/dist/cjs/utils.js.map +1 -1
  22. package/dist/esm/services/ProxyPostMessageStream.js +3 -10
  23. package/dist/esm/services/ProxyPostMessageStream.js.map +1 -1
  24. package/dist/esm/services/node/NodeProcessExecutionService.js +13 -1
  25. package/dist/esm/services/node/NodeProcessExecutionService.js.map +1 -1
  26. package/dist/esm/services/node/NodeThreadExecutionService.js +14 -1
  27. package/dist/esm/services/node/NodeThreadExecutionService.js.map +1 -1
  28. package/dist/esm/services/offscreen/OffscreenExecutionService.js +36 -99
  29. package/dist/esm/services/offscreen/OffscreenExecutionService.js.map +1 -1
  30. package/dist/esm/services/proxy/ProxyExecutionService.js +100 -0
  31. package/dist/esm/services/proxy/ProxyExecutionService.js.map +1 -0
  32. package/dist/esm/snaps/SnapController.js +200 -95
  33. package/dist/esm/snaps/SnapController.js.map +1 -1
  34. package/dist/esm/snaps/endowments/enum.js +1 -0
  35. package/dist/esm/snaps/endowments/enum.js.map +1 -1
  36. package/dist/esm/snaps/endowments/index.js +10 -4
  37. package/dist/esm/snaps/endowments/index.js.map +1 -1
  38. package/dist/esm/snaps/endowments/signature-insight.js +99 -0
  39. package/dist/esm/snaps/endowments/signature-insight.js.map +1 -0
  40. package/dist/esm/utils.js +37 -0
  41. package/dist/esm/utils.js.map +1 -1
  42. package/dist/types/services/ProxyPostMessageStream.d.ts +1 -2
  43. package/dist/types/services/offscreen/OffscreenExecutionService.d.ts +5 -22
  44. package/dist/types/services/proxy/ProxyExecutionService.d.ts +39 -0
  45. package/dist/types/snaps/SnapController.d.ts +31 -3
  46. package/dist/types/snaps/endowments/enum.d.ts +1 -0
  47. package/dist/types/snaps/endowments/index.d.ts +12 -0
  48. package/dist/types/snaps/endowments/signature-insight.d.ts +39 -0
  49. package/dist/types/utils.d.ts +99 -0
  50. package/package.json +8 -8
@@ -1,6 +1,7 @@
1
1
  export var SnapEndowments;
2
2
  (function(SnapEndowments) {
3
3
  SnapEndowments["NetworkAccess"] = 'endowment:network-access';
4
+ SnapEndowments["SignatureInsight"] = 'endowment:signature-insight';
4
5
  SnapEndowments["TransactionInsight"] = 'endowment:transaction-insight';
5
6
  SnapEndowments["Cronjob"] = 'endowment:cronjob';
6
7
  SnapEndowments["EthereumProvider"] = 'endowment:ethereum-provider';
@@ -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 Keyring = 'endowment:keyring',\n HomePage = 'endowment:page-home',\n}\n"],"names":["SnapEndowments","NetworkAccess","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","NameLookup","LifecycleHooks","Keyring","HomePage"],"mappings":"WAAO;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;IATAT,eAUVU,cAAW;GAVDV,mBAAAA"}
1
+ {"version":3,"sources":["../../../../src/snaps/endowments/enum.ts"],"sourcesContent":["export enum SnapEndowments {\n NetworkAccess = 'endowment:network-access',\n SignatureInsight = 'endowment:signature-insight',\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 HomePage = 'endowment:page-home',\n}\n"],"names":["SnapEndowments","NetworkAccess","SignatureInsight","TransactionInsight","Cronjob","EthereumProvider","Rpc","WebAssemblyAccess","NameLookup","LifecycleHooks","Keyring","HomePage"],"mappings":"WAAO;UAAKA,cAAc;IAAdA,eACVC,mBAAgB;IADND,eAEVE,sBAAmB;IAFTF,eAGVG,wBAAqB;IAHXH,eAIVI,aAAU;IAJAJ,eAKVK,sBAAmB;IALTL,eAMVM,SAAM;IANIN,eAOVO,uBAAoB;IAPVP,eAQVQ,gBAAa;IARHR,eASVS,oBAAiB;IATPT,eAUVU,aAAU;IAVAV,eAWVW,cAAW;GAXDX,mBAAAA"}
@@ -7,6 +7,7 @@ import { lifecycleHooksEndowmentBuilder } from './lifecycle-hooks';
7
7
  import { getNameLookupCaveatMapper, nameLookupCaveatSpecifications, nameLookupEndowmentBuilder } from './name-lookup';
8
8
  import { networkAccessEndowmentBuilder } from './network-access';
9
9
  import { getRpcCaveatMapper, rpcCaveatSpecifications, rpcEndowmentBuilder } from './rpc';
10
+ import { getSignatureInsightCaveatMapper, signatureInsightCaveatSpecifications, signatureInsightEndowmentBuilder } from './signature-insight';
10
11
  import { getTransactionInsightCaveatMapper, transactionInsightCaveatSpecifications, transactionInsightEndowmentBuilder } from './transaction-insight';
11
12
  import { webAssemblyEndowmentBuilder } from './web-assembly';
12
13
  export const endowmentPermissionBuilders = {
@@ -19,21 +20,24 @@ export const endowmentPermissionBuilders = {
19
20
  [nameLookupEndowmentBuilder.targetName]: nameLookupEndowmentBuilder,
20
21
  [lifecycleHooksEndowmentBuilder.targetName]: lifecycleHooksEndowmentBuilder,
21
22
  [keyringEndowmentBuilder.targetName]: keyringEndowmentBuilder,
22
- [homePageEndowmentBuilder.targetName]: homePageEndowmentBuilder
23
+ [homePageEndowmentBuilder.targetName]: homePageEndowmentBuilder,
24
+ [signatureInsightEndowmentBuilder.targetName]: signatureInsightEndowmentBuilder
23
25
  };
24
26
  export const endowmentCaveatSpecifications = {
25
27
  ...cronjobCaveatSpecifications,
26
28
  ...transactionInsightCaveatSpecifications,
27
29
  ...rpcCaveatSpecifications,
28
30
  ...nameLookupCaveatSpecifications,
29
- ...keyringCaveatSpecifications
31
+ ...keyringCaveatSpecifications,
32
+ ...signatureInsightCaveatSpecifications
30
33
  };
31
34
  export const endowmentCaveatMappers = {
32
35
  [cronjobEndowmentBuilder.targetName]: getCronjobCaveatMapper,
33
36
  [transactionInsightEndowmentBuilder.targetName]: getTransactionInsightCaveatMapper,
34
37
  [rpcEndowmentBuilder.targetName]: getRpcCaveatMapper,
35
38
  [nameLookupEndowmentBuilder.targetName]: getNameLookupCaveatMapper,
36
- [keyringEndowmentBuilder.targetName]: getKeyringCaveatMapper
39
+ [keyringEndowmentBuilder.targetName]: getKeyringCaveatMapper,
40
+ [signatureInsightEndowmentBuilder.targetName]: getSignatureInsightCaveatMapper
37
41
  };
38
42
  export const handlerEndowments = {
39
43
  [HandlerType.OnRpcRequest]: rpcEndowmentBuilder.targetName,
@@ -43,10 +47,12 @@ export const handlerEndowments = {
43
47
  [HandlerType.OnInstall]: lifecycleHooksEndowmentBuilder.targetName,
44
48
  [HandlerType.OnUpdate]: lifecycleHooksEndowmentBuilder.targetName,
45
49
  [HandlerType.OnKeyringRequest]: keyringEndowmentBuilder.targetName,
46
- [HandlerType.OnHomePage]: homePageEndowmentBuilder.targetName
50
+ [HandlerType.OnHomePage]: homePageEndowmentBuilder.targetName,
51
+ [HandlerType.OnSignature]: signatureInsightEndowmentBuilder.targetName
47
52
  };
48
53
  export * from './enum';
49
54
  export { getRpcCaveatOrigins } from './rpc';
55
+ export { getSignatureOriginCaveat } from './signature-insight';
50
56
  export { getTransactionOriginCaveat } from './transaction-insight';
51
57
  export { getChainIdsCaveat } from './name-lookup';
52
58
  export { getKeyringCaveatOrigins } from './keyring';
@@ -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 { homePageEndowmentBuilder } from './home-page';\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 [homePageEndowmentBuilder.targetName]: homePageEndowmentBuilder,\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 [HandlerType.OnHomePage]: homePageEndowmentBuilder.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":["HandlerType","cronjobCaveatSpecifications","cronjobEndowmentBuilder","getCronjobCaveatMapper","ethereumProviderEndowmentBuilder","homePageEndowmentBuilder","getKeyringCaveatMapper","keyringCaveatSpecifications","keyringEndowmentBuilder","lifecycleHooksEndowmentBuilder","getNameLookupCaveatMapper","nameLookupCaveatSpecifications","nameLookupEndowmentBuilder","networkAccessEndowmentBuilder","getRpcCaveatMapper","rpcCaveatSpecifications","rpcEndowmentBuilder","getTransactionInsightCaveatMapper","transactionInsightCaveatSpecifications","transactionInsightEndowmentBuilder","webAssemblyEndowmentBuilder","endowmentPermissionBuilders","targetName","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","OnRpcRequest","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","getRpcCaveatOrigins","getTransactionOriginCaveat","getChainIdsCaveat","getKeyringCaveatOrigins"],"mappings":"AACA,SAASA,WAAW,QAAQ,wBAAwB;AAGpD,SACEC,2BAA2B,EAC3BC,uBAAuB,EACvBC,sBAAsB,QACjB,YAAY;AACnB,SAASC,gCAAgC,QAAQ,sBAAsB;AACvE,SAASC,wBAAwB,QAAQ,cAAc;AACvD,SACEC,sBAAsB,EACtBC,2BAA2B,EAC3BC,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CAACzB,YAAY0B,YAAY,CAAC,EAAEV,oBAAoBM,UAAU;IAC1D,CAACtB,YAAY2B,aAAa,CAAC,EAAER,mCAAmCG,UAAU;IAC1E,CAACtB,YAAY4B,SAAS,CAAC,EAAE1B,wBAAwBoB,UAAU;IAC3D,CAACtB,YAAY6B,YAAY,CAAC,EAAEjB,2BAA2BU,UAAU;IACjE,CAACtB,YAAY8B,SAAS,CAAC,EAAErB,+BAA+Ba,UAAU;IAClE,CAACtB,YAAY+B,QAAQ,CAAC,EAAEtB,+BAA+Ba,UAAU;IACjE,CAACtB,YAAYgC,gBAAgB,CAAC,EAAExB,wBAAwBc,UAAU;IAClE,CAACtB,YAAYiC,UAAU,CAAC,EAAE5B,yBAAyBiB,UAAU;AAC/D,EAAE;AAEF,cAAc,SAAS;AACvB,SAASY,mBAAmB,QAAQ,QAAQ;AAC5C,SAASC,0BAA0B,QAAQ,wBAAwB;AACnE,SAASC,iBAAiB,QAAQ,gBAAgB;AAClD,SAASC,uBAAuB,QAAQ,YAAY"}
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 { homePageEndowmentBuilder } from './home-page';\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 getSignatureInsightCaveatMapper,\n signatureInsightCaveatSpecifications,\n signatureInsightEndowmentBuilder,\n} from './signature-insight';\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 [homePageEndowmentBuilder.targetName]: homePageEndowmentBuilder,\n [signatureInsightEndowmentBuilder.targetName]:\n signatureInsightEndowmentBuilder,\n} as const;\n\nexport const endowmentCaveatSpecifications = {\n ...cronjobCaveatSpecifications,\n ...transactionInsightCaveatSpecifications,\n ...rpcCaveatSpecifications,\n ...nameLookupCaveatSpecifications,\n ...keyringCaveatSpecifications,\n ...signatureInsightCaveatSpecifications,\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 [signatureInsightEndowmentBuilder.targetName]:\n getSignatureInsightCaveatMapper,\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 [HandlerType.OnHomePage]: homePageEndowmentBuilder.targetName,\n [HandlerType.OnSignature]: signatureInsightEndowmentBuilder.targetName,\n};\n\nexport * from './enum';\nexport { getRpcCaveatOrigins } from './rpc';\nexport { getSignatureOriginCaveat } from './signature-insight';\nexport { getTransactionOriginCaveat } from './transaction-insight';\nexport { getChainIdsCaveat } from './name-lookup';\nexport { getKeyringCaveatOrigins } from './keyring';\n"],"names":["HandlerType","cronjobCaveatSpecifications","cronjobEndowmentBuilder","getCronjobCaveatMapper","ethereumProviderEndowmentBuilder","homePageEndowmentBuilder","getKeyringCaveatMapper","keyringCaveatSpecifications","keyringEndowmentBuilder","lifecycleHooksEndowmentBuilder","getNameLookupCaveatMapper","nameLookupCaveatSpecifications","nameLookupEndowmentBuilder","networkAccessEndowmentBuilder","getRpcCaveatMapper","rpcCaveatSpecifications","rpcEndowmentBuilder","getSignatureInsightCaveatMapper","signatureInsightCaveatSpecifications","signatureInsightEndowmentBuilder","getTransactionInsightCaveatMapper","transactionInsightCaveatSpecifications","transactionInsightEndowmentBuilder","webAssemblyEndowmentBuilder","endowmentPermissionBuilders","targetName","endowmentCaveatSpecifications","endowmentCaveatMappers","handlerEndowments","OnRpcRequest","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","OnSignature","getRpcCaveatOrigins","getSignatureOriginCaveat","getTransactionOriginCaveat","getChainIdsCaveat","getKe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amask/rpc-errors';
3
+ import { SnapCaveatType } from '@metamask/snaps-utils';
4
+ import { assert, hasProperty, isObject, isPlainObject } from '@metamask/utils';
5
+ import { SnapEndowments } from './enum';
6
+ const permissionName = SnapEndowments.SignatureInsight;
7
+ /**
8
+ * `endowment:signature-insight` returns nothing; it is intended to be used as a flag
9
+ * by the extension to detect whether the snap has the capability to show information on the signature confirmation screen.
10
+ *
11
+ * @param _builderOptions - Optional specification builder options.
12
+ * @returns The specification for the signature-insight endowment.
13
+ */ const specificationBuilder = (_builderOptions)=>{
14
+ return {
15
+ permissionType: PermissionType.Endowment,
16
+ targetName: permissionName,
17
+ allowedCaveats: [
18
+ SnapCaveatType.SignatureOrigin
19
+ ],
20
+ endowmentGetter: (_getterOptions)=>undefined,
21
+ validator: ({ caveats })=>{
22
+ if (caveats !== null && caveats?.length > 1 || caveats?.length === 1 && caveats[0].type !== SnapCaveatType.SignatureOrigin) {
23
+ throw rpcErrors.invalidParams({
24
+ message: `Expected a single "${SnapCaveatType.SignatureOrigin}" caveat.`
25
+ });
26
+ }
27
+ },
28
+ subjectTypes: [
29
+ SubjectType.Snap
30
+ ]
31
+ };
32
+ };
33
+ export const signatureInsightEndowmentBuilder = 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 rpcErrors.invalidParams({
45
+ message: 'Expected a plain object.'
46
+ });
47
+ }
48
+ const { value } = caveat;
49
+ assert(typeof value === 'boolean', 'Expected caveat value to have type "boolean"');
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
+ * PermissionController when the permission is requested.
55
+ *
56
+ * @param value - The raw value from the `initialPermissions`.
57
+ * @returns The caveat specification.
58
+ */ export function getSignatureInsightCaveatMapper(value) {
59
+ if (!value || !isObject(value) || isObject(value) && Object.keys(value).length === 0) {
60
+ return {
61
+ caveats: null
62
+ };
63
+ }
64
+ return {
65
+ caveats: [
66
+ {
67
+ type: SnapCaveatType.SignatureOrigin,
68
+ value: hasProperty(value, 'allowSignatureOrigin') && value.allowSignatureOrigin
69
+ }
70
+ ]
71
+ };
72
+ }
73
+ /**
74
+ * Getter function to get the signature origin 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 signature origin caveat from.
81
+ * @returns The signature origin, or `null` if the permission does not have a
82
+ * signature origin caveat.
83
+ */ export function getSignatureOriginCaveat(permission) {
84
+ if (!permission?.caveats) {
85
+ return null;
86
+ }
87
+ assert(permission.caveats.length === 1);
88
+ assert(permission.caveats[0].type === SnapCaveatType.SignatureOrigin);
89
+ const caveat = permission.caveats[0];
90
+ return caveat.value ?? null;
91
+ }
92
+ export const signatureInsightCaveatSpecifications = {
93
+ [SnapCaveatType.SignatureOrigin]: Object.freeze({
94
+ type: SnapCaveatType.SignatureOrigin,
95
+ validator: (caveat)=>validateCaveat(caveat)
96
+ })
97
+ };
98
+
99
+ //# sourceMappingURL=signature-insight.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/snaps/endowments/signature-insight.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n EndowmentGetterParams,\n ValidPermissionSpecification,\n PermissionValidatorConstraint,\n PermissionConstraint,\n CaveatSpecificationConstraint,\n Caveat,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { assert, hasProperty, isObject, isPlainObject } from '@metamask/utils';\n\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.SignatureInsight;\n\ntype SignatureInsightEndowmentSpecification = 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:signature-insight` returns nothing; it is intended to be used as a flag\n * by the extension to detect whether the snap has the capability to show information on the signature confirmation screen.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the signature-insight endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n SignatureInsightEndowmentSpecification\n> = (_builderOptions?: unknown) => {\n return {\n permissionType: PermissionType.Endowment,\n targetName: permissionName,\n allowedCaveats: [SnapCaveatType.SignatureOrigin],\n endowmentGetter: (_getterOptions?: EndowmentGetterParams) => undefined,\n validator: ({ caveats }) => {\n if (\n (caveats !== null && caveats?.length > 1) ||\n (caveats?.length === 1 &&\n caveats[0].type !== SnapCaveatType.SignatureOrigin)\n ) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.SignatureOrigin}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nexport const signatureInsightEndowmentBuilder = 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 rpcErrors.invalidParams({\n message: 'Expected a plain object.',\n });\n }\n\n const { value } = caveat;\n\n assert(\n typeof value === 'boolean',\n 'Expected caveat value to have type \"boolean\"',\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 * PermissionController when the permission is requested.\n *\n * @param value - The raw value from the `initialPermissions`.\n * @returns The caveat specification.\n */\nexport function getSignatureInsightCaveatMapper(\n value: Json,\n): Pick<PermissionConstraint, 'caveats'> {\n if (\n !value ||\n !isObject(value) ||\n (isObject(value) && Object.keys(value).length === 0)\n ) {\n return { caveats: null };\n }\n return {\n caveats: [\n {\n type: SnapCaveatType.SignatureOrigin,\n value:\n hasProperty(value, 'allowSignatureOrigin') &&\n (value.allowSignatureOrigin as boolean),\n },\n ],\n };\n}\n\n/**\n * Getter function to get the signature origin 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 signature origin caveat from.\n * @returns The signature origin, or `null` if the permission does not have a\n * signature origin caveat.\n */\nexport function getSignatureOriginCaveat(\n permission?: PermissionConstraint,\n): boolean | null {\n if (!permission?.caveats) {\n return null;\n }\n\n assert(permission.caveats.length === 1);\n assert(permission.caveats[0].type === SnapCaveatType.SignatureOrigin);\n\n const caveat = permission.caveats[0] as Caveat<string, boolean>;\n\n return caveat.value ?? null;\n}\n\nexport const signatureInsightCaveatSpecifications: Record<\n SnapCaveatType.SignatureOrigin,\n CaveatSpecificationConstraint\n> = {\n [SnapCaveatType.SignatureOrigin]: Object.freeze({\n type: SnapCaveatType.SignatureOrigin,\n validator: (caveat: Caveat<string, any>) => validateCaveat(caveat),\n }),\n};\n"],"names":["PermissionType","SubjectType","rpcErrors","SnapCaveatType","assert","hasProperty","isObject","isPlainObject","SnapEndowments","permissionName","SignatureInsight","specificationBuilder","_builderOptions","permissionType","Endowment","targetName","allowedCaveats","SignatureOrigin","endowmentGetter","_getterOptions","undefined","validator","caveats","length","type","invalidParams","message","subjectTypes","Snap","signatureInsightEndowmentBuilder","Object","freeze","validateCaveat","caveat","value","getSignatureInsightCaveatMapper","keys","allowSignatureOrigin","getSignatureOriginCaveat","permission","signatureInsightCaveatSpecifications"],"mappings":"AASA,SAASA,cAAc,EAAEC,WAAW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AO;YAAED,SAAS;QAAK;IACzB;IACA,OAAO;QACLA,SAAS;YACP;gBACEE,MAAMrB,eAAec,eAAe;gBACpCiB,OACE7B,YAAY6B,OAAO,2BAClBA,MAAMG,oBAAoB;YAC/B;SACD;IACH;AACF;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASC,yBACdC,UAAiC;IAEjC,IAAI,CAACA,YAAYjB,SAAS;QACxB,OAAO;IACT;IAEAlB,OAAOmC,WAAWjB,OAAO,CAACC,MAAM,KAAK;IACrCnB,OAAOmC,WAAWjB,OAAO,CAAC,EAAE,CAACE,IAAI,KAAKrB,eAAec,eAAe;IAEpE,MAAMgB,SAASM,WAAWjB,OAAO,CAAC,EAAE;IAEpC,OAAOW,OAAOC,KAAK,IAAI;AACzB;AAEA,OAAO,MAAMM,uCAGT;IACF,CAACrC,eAAec,eAAe,CAAC,EAAEa,OAAOC,MAAM,CAAC;QAC9CP,MAAMrB,eAAec,eAAe;QACpCI,WAAW,CAACY,SAAgCD,eAAeC;IAC7D;AACF,EAAE"}
package/dist/esm/utils.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { getErrorMessage } from '@metamask/snaps-sdk';
2
+ import { encodeBase64, getValidatedLocalizationFiles, validateFetchedSnap } from '@metamask/snaps-utils';
1
3
  import { Timer } from './snaps/Timer';
2
4
  /**
3
5
  * Takes two objects and does a Set Difference of them.
@@ -91,5 +93,40 @@ import { Timer } from './snaps/Timer';
91
93
  }
92
94
  return await Promise.all(files.map(async (filePath)=>location.fetch(filePath)));
93
95
  }
96
+ /**
97
+ * Fetch the Snap manifest, source code, and any other files from the given
98
+ * location.
99
+ *
100
+ * @param snapId - The ID of the Snap to fetch.
101
+ * @param location - The location of the Snap.
102
+ * @returns The Snap files and location.
103
+ * @throws If the Snap files are invalid, or if the Snap could not be fetched.
104
+ */ export async function fetchSnap(snapId, location) {
105
+ try {
106
+ const manifest = await location.manifest();
107
+ const sourceCode = await location.fetch(manifest.result.source.location.npm.filePath);
108
+ const { iconPath } = manifest.result.source.location.npm;
109
+ const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;
110
+ const auxiliaryFiles = await getSnapFiles(location, manifest.result.source.files);
111
+ await Promise.all(auxiliaryFiles.map(async (file)=>{
112
+ // This should still be safe
113
+ // eslint-disable-next-line require-atomic-updates
114
+ file.data.base64 = await encodeBase64(file);
115
+ }));
116
+ const localizationFiles = await getSnapFiles(location, manifest.result.source.locales);
117
+ const validatedLocalizationFiles = getValidatedLocalizationFiles(localizationFiles);
118
+ const files = {
119
+ manifest,
120
+ sourceCode,
121
+ svgIcon,
122
+ auxiliaryFiles,
123
+ localizationFiles: validatedLocalizationFiles
124
+ };
125
+ await validateFetchedSnap(files);
126
+ return files;
127
+ } catch (error) {
128
+ throw new Error(`Failed to fetch snap "${snapId}": ${getErrorMessage(error)}.`);
129
+ }
130
+ }
94
131
 
95
132
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type { SnapLocation } from './snaps';\nimport { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * A Promise that delays its return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n\n/**\n * Get all files in a Snap from an array of file paths.\n *\n * @param location - The location of the Snap.\n * @param files - The array of file paths.\n * @returns The array of files as {@link VirtualFile}s.\n */\nexport async function getSnapFiles(\n location: SnapLocation,\n files?: string[] | undefined,\n) {\n if (!files || files.length === 0) {\n return [];\n }\n\n return await Promise.all(\n files.map(async (filePath) => location.fetch(filePath)),\n );\n}\n"],"names":["Timer","setDiff","objectA","objectB","Object","entries","reduce","acc","key","value","delay","ms","result","delayWithTimer","timer","rejectFunc","promise","Promise","resolve","reject","start","undefined","cancel","status","Error","hasTimedOut","Symbol","withTimeout","timerOrMs","delayPromise","race","getSnapFiles","location","files","length","all","map","filePath","fetch"],"mappings":"AACA,SAASA,KAAK,QAAQ,gBAAgB;AAEtC;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,QAGdC,OAAgB,EAAEC,OAAgB;IAClC,OAAOC,OAAOC,OAAO,CAACH,SAASI,MAAM,CACnC,CAACC,KAAK,CAACC,KAAKC,MAAM;QAChB,IAAI,CAAED,CAAAA,OAAOL,OAAM,GAAI;YACrBI,GAAG,CAACC,IAAI,GAAGC;QACb;QACA,OAAOF;IACT,GACA,CAAC;AAEL;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,MACdC,EAAU,EACVC,MAAe;IAEf,OAAOC,eAAe,IAAIb,MAAMW,KAAKC;AACvC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,eACdC,KAAY,EACZF,MAAe;IAEf,IAAIG;IACJ,MAAMC,UAAe,IAAIC,QAAgB,CAACC,SAAcC;QACtDL,MAAMM,KAAK,CAAC;YACVR,WAAWS,YAAYH,YAAYA,QAAQN;QAC7C;QACAG,aAAaI;IACf;IAEAH,QAAQM,MAAM,GAAG;QACf,IAAIR,MAAMS,MAAM,KAAK,YAAY;YAC/BT,MAAMQ,MAAM;YACZP,WAAW,IAAIS,MAAM;QACvB;IACF;IACA,OAAOR;AACT;AAEA;;;CAGC,GACD,OAAO,MAAMS,cAAcC,OACzB,wEACA;AAEF;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,YACpBX,OAA8B,EAC9BY,SAAyB;IAEzB,MAAMd,QACJ,OAAOc,cAAc,WAAW,IAAI5B,MAAM4B,aAAaA;IACzD,MAAMC,eAAehB,eAAeC,OAAOW;IAC3C,IAAI;QACF,OAAO,MAAMR,QAAQa,IAAI,CAAC;YAACd;YAASa;SAAa;IACnD,SAAU;QACRA,aAAaP,MAAM;IACrB;AACF;AA+FA;;;;;;CAMC,GACD,OAAO,eAAeS,aACpBC,QAAsB,EACtBC,KAA4B;IAE5B,IAAI,CAACA,SAASA,MAAMC,MAAM,KAAK,GAAG;QAChC,OAAO,EAAE;IACX;IAEA,OAAO,MAAMjB,QAAQkB,GAAG,CACtBF,MAAMG,GAAG,CAAC,OAAOC,WAAaL,SAASM,KAAK,CAACD;AAEjD"}
1
+ {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-sdk';\nimport { getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n encodeBase64,\n getValidatedLocalizationFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\n\nimport type { SnapLocation } from './snaps';\nimport { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * A Promise that delays its return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n\n/**\n * Get all files in a Snap from an array of file paths.\n *\n * @param location - The location of the Snap.\n * @param files - The array of file paths.\n * @returns The array of files as {@link VirtualFile}s.\n */\nexport async function getSnapFiles(\n location: SnapLocation,\n files?: string[] | undefined,\n) {\n if (!files || files.length === 0) {\n return [];\n }\n\n return await Promise.all(\n files.map(async (filePath) => location.fetch(filePath)),\n );\n}\n\n/**\n * Fetch the Snap manifest, source code, and any other files from the given\n * location.\n *\n * @param snapId - The ID of the Snap to fetch.\n * @param location - The location of the Snap.\n * @returns The Snap files and location.\n * @throws If the Snap files are invalid, or if the Snap could not be fetched.\n */\nexport async function fetchSnap(snapId: SnapId, location: SnapLocation) {\n try {\n const manifest = await location.manifest();\n const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\n );\n const { iconPath } = manifest.result.source.location.npm;\n const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;\n\n const auxiliaryFiles = await getSnapFiles(\n location,\n manifest.result.source.files,\n );\n\n await Promise.all(\n auxiliaryFiles.map(async (file) => {\n // This should still be safe\n // eslint-disable-next-line require-atomic-updates\n file.data.base64 = await encodeBase64(file);\n }),\n );\n\n const localizationFiles = await getSnapFiles(\n location,\n manifest.result.source.locales,\n );\n\n const validatedLocalizationFiles =\n getValidatedLocalizationFiles(localizationFiles);\n\n const files = {\n manifest,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles: validatedLocalizationFiles,\n };\n\n await validateFetchedSnap(files);\n\n return files;\n } catch (error) {\n throw new Error(\n `Failed to fetch snap \"${snapId}\": ${getErrorMessage(error)}.`,\n );\n }\n}\n"],"names":["getErrorMessage","encodeBase64","getValidatedLocalizationFiles","validateFetchedSnap","Timer","setDiff","objectA","objectB","Object","entries","reduce","acc","key","value","delay","ms","result","delayWithTimer","timer","rejectFunc","promise","Promise","resolve","reject","start","undefined","cancel","status","Error","hasTimedOut","Symbol","withTimeout","timerOrMs","delayPromise","race","getSnapFiles","location","files","length","all","map","filePath","fetch","fetchSnap","snapId","manifest","sourceCode","source","npm","iconPath","svgIcon","auxiliaryFiles","file","data","base64","localizationFiles","locales","validatedLocalizationFiles","error"],"mappings":"AACA,SAASA,eAAe,QAAQ,sBAAsB;AACtD,SACEC,YAAY,EACZC,6BAA6B,EAC7BC,mBAAmB,QACd,wBAAwB;AAG/B,SAASC,KAAK,QAAQ,gBAAgB;AAEtC;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,QAGdC,OAAgB,EAAEC,OAAgB;IAClC,OAAOC,OAAOC,OAAO,CAACH,SAASI,MAAM,CACnC,CAACC,KAAK,CAACC,KAAKC,MAAM;QAChB,IAAI,CAAED,CAAAA,OAAOL,OAAM,GAAI;YACrBI,GAAG,CAACC,IAAI,GAAGC;QACb;QACA,OAAOF;IACT,GACA,CAAC;AAEL;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,MACdC,EAAU,EACVC,MAA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GAAGJ,SAAS7B,MAAM,CAAC+B,MAAM,CAACX,QAAQ,CAACY,GAAG;QACxD,MAAME,UAAUD,WAAW,MAAMb,SAASM,KAAK,CAACO,YAAYxB;QAE5D,MAAM0B,iBAAiB,MAAMhB,aAC3BC,UACAS,SAAS7B,MAAM,CAAC+B,MAAM,CAACV,KAAK;QAG9B,MAAMhB,QAAQkB,GAAG,CACfY,eAAeX,GAAG,CAAC,OAAOY;YACxB,4BAA4B;YAC5B,kDAAkD;YAClDA,KAAKC,IAAI,CAACC,MAAM,GAAG,MAAMrD,aAAamD;QACxC;QAGF,MAAMG,oBAAoB,MAAMpB,aAC9BC,UACAS,SAAS7B,MAAM,CAAC+B,MAAM,CAACS,OAAO;QAGhC,MAAMC,6BACJvD,8BAA8BqD;QAEhC,MAAMlB,QAAQ;YACZQ;YACAC;YACAI;YACAC;YACAI,mBAAmBE;QACrB;QAEA,MAAMtD,oBAAoBkC;QAE1B,OAAOA;IACT,EAAE,OAAOqB,OAAO;QACd,MAAM,IAAI9B,MACR,CAAC,sBAAsB,EAAEgB,OAAO,GAAG,EAAE5C,gBAAgB0D,OAAO,CAAC,CAAC;IAElE;AACF"}
@@ -22,9 +22,8 @@ export declare class ProxyPostMessageStream extends BasePostMessageStream {
22
22
  * @param args - The constructor arguments.
23
23
  * @param args.stream - The underlying stream to use for communication.
24
24
  * @param args.jobId - The ID of the job this stream is associated with.
25
- * @param args.extra - Extra data to include in the post message.
26
25
  */
27
- constructor({ stream, jobId, extra }: ProxyPostMessageStreamArgs);
26
+ constructor({ stream, jobId }: ProxyPostMessageStreamArgs);
28
27
  /**
29
28
  * Write data to the underlying stream. This wraps the data in an object with
30
29
  * the job ID.
@@ -1,14 +1,11 @@
1
- import type { ExecutionServiceArgs, Job } from '../AbstractExecutionService';
2
- import { AbstractExecutionService } from '../AbstractExecutionService';
3
- import { ProxyPostMessageStream } from '../ProxyPostMessageStream';
1
+ import type { ExecutionServiceArgs } from '../AbstractExecutionService';
2
+ import { ProxyExecutionService } from '../proxy/ProxyExecutionService';
4
3
  declare type OffscreenExecutionEnvironmentServiceArgs = {
5
4
  documentUrl: URL;
6
- frameUrl: URL;
7
5
  } & ExecutionServiceArgs;
8
- export declare class OffscreenExecutionService extends AbstractExecutionService<string> {
6
+ export declare class OffscreenExecutionService extends ProxyExecutionService {
9
7
  #private;
10
8
  readonly documentUrl: URL;
11
- readonly frameUrl: URL;
12
9
  /**
13
10
  * Create a new offscreen execution service.
14
11
  *
@@ -16,20 +13,12 @@ export declare class OffscreenExecutionService extends AbstractExecutionService<
16
13
  * @param args.documentUrl - The URL of the offscreen document to use as the
17
14
  * execution environment. This must be a URL relative to the location where
18
15
  * this is called. This cannot be a public (http(s)) URL.
19
- * @param args.frameUrl - The URL of the iframe to load inside the offscreen
20
- * document.
21
16
  * @param args.messenger - The messenger to use for communication with the
22
17
  * `SnapController`.
23
18
  * @param args.setupSnapProvider - The function to use to set up the snap
24
19
  * provider.
25
20
  */
26
- constructor({ documentUrl, frameUrl, messenger, setupSnapProvider, }: OffscreenExecutionEnvironmentServiceArgs);
27
- /**
28
- * Send a termination command to the offscreen document.
29
- *
30
- * @param job - The job to terminate.
31
- */
32
- protected terminateJob(job: Job<string>): Promise<void>;
21
+ constructor({ documentUrl, messenger, setupSnapProvider, }: OffscreenExecutionEnvironmentServiceArgs);
33
22
  /**
34
23
  * Create a new stream for the specified job. This wraps the runtime stream
35
24
  * in a stream specific to the job.
@@ -38,13 +27,7 @@ export declare class OffscreenExecutionService extends AbstractExecutionService<
38
27
  */
39
28
  protected initEnvStream(jobId: string): Promise<{
40
29
  worker: string;
41
- stream: ProxyPostMessageStream;
30
+ stream: import("..").ProxyPostMessageStream;
42
31
  }>;
43
- /**
44
- * Creates the offscreen document to be used as the execution environment.
45
- *
46
- * If the document already exists, this does nothing.
47
- */
48
- private createDocument;
49
32
  }
50
33
  export {};
@@ -0,0 +1,39 @@
1
+ import type { BasePostMessageStream } from '@metamask/post-message-stream';
2
+ import type { ExecutionServiceArgs, Job } from '../AbstractExecutionService';
3
+ import { AbstractExecutionService } from '../AbstractExecutionService';
4
+ import { ProxyPostMessageStream } from '../ProxyPostMessageStream';
5
+ declare type ProxyExecutionEnvironmentServiceArgs = {
6
+ stream: BasePostMessageStream;
7
+ } & ExecutionServiceArgs;
8
+ export declare class ProxyExecutionService extends AbstractExecutionService<string> {
9
+ #private;
10
+ /**
11
+ * Create a new proxy execution service.
12
+ *
13
+ * @param args - The constructor arguments.
14
+ * @param args.messenger - The messenger to use for communication with the
15
+ * `SnapController`.
16
+ * @param args.setupSnapProvider - The function to use to set up the snap
17
+ * provider.
18
+ * @param args.stream - The stream to use for communicating with the proxy
19
+ * executor.
20
+ */
21
+ constructor({ stream, messenger, setupSnapProvider, }: ProxyExecutionEnvironmentServiceArgs);
22
+ /**
23
+ * Send a termination command to the proxy stream.
24
+ *
25
+ * @param job - The job to terminate.
26
+ */
27
+ protected terminateJob(job: Job<string>): Promise<void>;
28
+ /**
29
+ * Create a new stream for the specified job. This wraps the root stream
30
+ * in a stream specific to the job.
31
+ *
32
+ * @param jobId - The job ID.
33
+ */
34
+ protected initEnvStream(jobId: string): Promise<{
35
+ worker: string;
36
+ stream: ProxyPostMessageStream;
37
+ }>;
38
+ }
39
+ export {};
@@ -6,7 +6,7 @@ import type { MaybeUpdateState, TestOrigin } from '@metamask/phishing-controller
6
6
  import type { BlockReason } from '@metamask/snaps-registry';
7
7
  import type { RequestSnapsParams, RequestSnapsResult, SnapId } from '@metamask/snaps-sdk';
8
8
  import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';
9
- import type { PersistedSnap, Snap, SnapRpcHook, SnapRpcHookArgs, StatusContext, StatusEvents, StatusStates, TruncatedSnap } from '@metamask/snaps-utils';
9
+ import type { PersistedSnap, Snap, SnapManifest, SnapRpcHook, SnapRpcHookArgs, StatusContext, StatusEvents, StatusStates, TruncatedSnap } from '@metamask/snaps-utils';
10
10
  import { SnapStatusEvents } from '@metamask/snaps-utils';
11
11
  import type { Json, NonEmptyArray } from '@metamask/utils';
12
12
  import type { StateMachine } from '@xstate/fsm';
@@ -24,6 +24,16 @@ export declare type PendingRequest = {
24
24
  requestId: unknown;
25
25
  timer: Timer;
26
26
  };
27
+ export interface PreinstalledSnapFile {
28
+ path: string;
29
+ value: string | Uint8Array;
30
+ }
31
+ export interface PreinstalledSnap {
32
+ snapId: SnapId;
33
+ manifest: SnapManifest;
34
+ files: PreinstalledSnapFile[];
35
+ removable?: boolean;
36
+ }
27
37
  /**
28
38
  * A wrapper type for any data stored during runtime of Snaps.
29
39
  * It is not persisted in state as it contains non-serializable data and is only relevant for the
@@ -188,6 +198,20 @@ export declare type SnapBlocked = {
188
198
  type: `${typeof controllerName}:snapBlocked`;
189
199
  payload: [snapId: string, blockedSnapInfo?: BlockReason];
190
200
  };
201
+ /**
202
+ * Emitted when a snap installation or update is started.
203
+ */
204
+ export declare type SnapInstallStarted = {
205
+ type: `${typeof controllerName}:snapInstallStarted`;
206
+ payload: [snapId: SnapId, origin: string, isUpdate: boolean];
207
+ };
208
+ /**
209
+ * Emitted when a snap installation or update failed.
210
+ */
211
+ export declare type SnapInstallFailed = {
212
+ type: `${typeof controllerName}:snapInstallFailed`;
213
+ payload: [snapId: SnapId, origin: string, isUpdate: boolean, error: string];
214
+ };
191
215
  /**
192
216
  * Emitted when a snap has been started after being added and authorized during
193
217
  * installation.
@@ -247,7 +271,7 @@ export declare type SnapDisabled = {
247
271
  type: `${typeof controllerName}:snapDisabled`;
248
272
  payload: [snap: TruncatedSnap];
249
273
  };
250
- export declare type SnapControllerEvents = SnapBlocked | SnapInstalled | SnapUninstalled | SnapStateChange | SnapUnblocked | SnapUpdated | SnapRolledback | SnapTerminated | SnapEnabled | SnapDisabled;
274
+ export declare type SnapControllerEvents = SnapBlocked | SnapInstalled | SnapUninstalled | SnapInstallStarted | SnapInstallFailed | SnapStateChange | SnapUnblocked | SnapUpdated | SnapRolledback | SnapTerminated | SnapEnabled | SnapDisabled;
251
275
  export declare type AllowedActions = GetEndowments | GetPermissions | GetSubjects | GetSubjectMetadata | AddSubjectMetadata | HasPermission | HasPermissions | RevokePermissions | RevokeAllPermissions | RevokePermissionForAllSubjects | GrantPermissions | AddApprovalRequest | HandleRpcRequestAction | ExecuteSnapAction | TerminateAllSnapsAction | TerminateSnapAction | UpdateCaveat | UpdateRequestState | GetResult | GetMetadata | Update | ResolveVersion | TestOrigin | MaybeUpdateState;
252
276
  export declare type AllowedEvents = ExecutionServiceEvents | SnapInstalled | SnapUpdated;
253
277
  declare type SnapControllerMessenger = RestrictedControllerMessenger<typeof controllerName, SnapControllerActions | AllowedActions, SnapControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
@@ -315,11 +339,15 @@ declare type SnapControllerArgs = {
315
339
  * Used for test overrides.
316
340
  */
317
341
  detectSnapLocation?: typeof detectSnapLocation;
342
+ /**
343
+ * A list of snaps to be preinstalled into the SnapController state on initialization.
344
+ */
345
+ preinstalledSnaps?: PreinstalledSnap[];
318
346
  };
319
347
  export declare class SnapController extends BaseController<string, SnapControllerState, SnapControllerMessenger> {
320
348
  #private;
321
349
  private readonly maxRequestTime;
322
- constructor({ closeAllConnections, messenger, state, dynamicPermissions, environmentEndowmentPermissions, excludedPermissions, idleTimeCheckInterval, maxIdleTime, maxRequestTime, fetchFunction, featureFlags, detectSnapLocation: detectSnapLocationFunction, }: SnapControllerArgs);
350
+ constructor({ closeAllConnections, messenger, state, dynamicPermissions, environmentEndowmentPermissions, excludedPermissions, idleTimeCheckInterval, maxIdleTime, maxRequestTime, fetchFunction, featureFlags, detectSnapLocation: detectSnapLocationFunction, preinstalledSnaps, }: SnapControllerArgs);
323
351
  /**
324
352
  * Checks all installed snaps against the block list and
325
353
  * blocks/unblocks snaps as appropriate. See {@link SnapController.blockSnap}
@@ -1,5 +1,6 @@
1
1
  export declare enum SnapEndowments {
2
2
  NetworkAccess = "endowment:network-access",
3
+ SignatureInsight = "endowment:signature-insight",
3
4
  TransactionInsight = "endowment:transaction-insight",
4
5
  Cronjob = "endowment:cronjob",
5
6
  EthereumProvider = "endowment:ethereum-provider",
@@ -98,8 +98,19 @@ export declare const endowmentPermissionBuilders: {
98
98
  allowedCaveats: readonly [string, ...string[]] | null;
99
99
  }>;
100
100
  }>;
101
+ readonly "endowment:signature-insight": Readonly<{
102
+ readonly targetName: import("./enum").SnapEndowments.SignatureInsight;
103
+ readonly specificationBuilder: import("@metamask/permission-controller").PermissionSpecificationBuilder<import("@metamask/permission-controller").PermissionType.Endowment, any, {
104
+ permissionType: import("@metamask/permission-controller").PermissionType.Endowment;
105
+ targetName: import("./enum").SnapEndowments.SignatureInsight;
106
+ endowmentGetter: (_options?: import("@metamask/permission-controller").EndowmentGetterParams | undefined) => undefined;
107
+ allowedCaveats: readonly [string, ...string[]] | null;
108
+ validator: import("@metamask/permission-controller").PermissionValidatorConstraint;
109
+ }>;
110
+ }>;
101
111
  };
102
112
  export declare const endowmentCaveatSpecifications: {
113
+ signatureOrigin: import("@metamask/permission-controller").CaveatSpecificationConstraint;
103
114
  keyringOrigin: import("@metamask/permission-controller").CaveatSpecificationConstraint;
104
115
  chainIds: import("@metamask/permission-controller").CaveatSpecificationConstraint;
105
116
  rpcOrigin: import("@metamask/permission-controller").CaveatSpecificationConstraint;
@@ -110,6 +121,7 @@ export declare const endowmentCaveatMappers: Record<string, (value: Json) => Pic
110
121
  export declare const handlerEndowments: Record<HandlerType, string>;
111
122
  export * from './enum';
112
123
  export { getRpcCaveatOrigins } from './rpc';
124
+ export { getSignatureOriginCaveat } from './signature-insight';
113
125
  export { getTransactionOriginCaveat } from './transaction-insight';
114
126
  export { getChainIdsCaveat } from './name-lookup';
115
127
  export { getKeyringCaveatOrigins } from './keyring';
@@ -0,0 +1,39 @@
1
+ import type { PermissionSpecificationBuilder, EndowmentGetterParams, PermissionValidatorConstraint, PermissionConstraint, CaveatSpecificationConstraint } 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.SignatureInsight;
7
+ export declare const signatureInsightEndowmentBuilder: Readonly<{
8
+ readonly targetName: SnapEndowments.SignatureInsight;
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
+ * PermissionController 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 getSignatureInsightCaveatMapper(value: Json): Pick<PermissionConstraint, 'caveats'>;
26
+ /**
27
+ * Getter function to get the signature origin 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 signature origin caveat from.
34
+ * @returns The signature origin, or `null` if the permission does not have a
35
+ * signature origin caveat.
36
+ */
37
+ export declare function getSignatureOriginCaveat(permission?: PermissionConstraint): boolean | null;
38
+ export declare const signatureInsightCaveatSpecifications: Record<SnapCaveatType.SignatureOrigin, CaveatSpecificationConstraint>;
39
+ export {};