@metamask/snaps-controllers 0.33.1-flask.1 → 0.34.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 (47) hide show
  1. package/CHANGELOG.md +73 -65
  2. package/dist/cronjob/CronjobController.d.ts +3 -3
  3. package/dist/cronjob/CronjobController.js.map +1 -1
  4. package/dist/multichain/MultiChainController.js +1 -1
  5. package/dist/multichain/MultiChainController.js.map +1 -1
  6. package/dist/snaps/SnapController.d.ts +22 -22
  7. package/dist/snaps/SnapController.js +8 -22
  8. package/dist/snaps/SnapController.js.map +1 -1
  9. package/dist/snaps/endowments/cronjob.d.ts +2 -2
  10. package/dist/snaps/endowments/cronjob.js +2 -2
  11. package/dist/snaps/endowments/cronjob.js.map +1 -1
  12. package/dist/snaps/endowments/ethereum-provider.d.ts +2 -2
  13. package/dist/snaps/endowments/ethereum-provider.js +2 -2
  14. package/dist/snaps/endowments/ethereum-provider.js.map +1 -1
  15. package/dist/snaps/endowments/index.d.ts +16 -16
  16. package/dist/snaps/endowments/index.js +16 -16
  17. package/dist/snaps/endowments/index.js.map +1 -1
  18. package/dist/snaps/endowments/keyring.d.ts +3 -3
  19. package/dist/snaps/endowments/keyring.js +5 -4
  20. package/dist/snaps/endowments/keyring.js.map +1 -1
  21. package/dist/snaps/endowments/long-running.d.ts +2 -2
  22. package/dist/snaps/endowments/long-running.js +2 -2
  23. package/dist/snaps/endowments/long-running.js.map +1 -1
  24. package/dist/snaps/endowments/network-access.d.ts +2 -2
  25. package/dist/snaps/endowments/network-access.js +2 -2
  26. package/dist/snaps/endowments/network-access.js.map +1 -1
  27. package/dist/snaps/endowments/rpc.d.ts +3 -3
  28. package/dist/snaps/endowments/rpc.js +5 -4
  29. package/dist/snaps/endowments/rpc.js.map +1 -1
  30. package/dist/snaps/endowments/transaction-insight.d.ts +2 -2
  31. package/dist/snaps/endowments/transaction-insight.js +2 -2
  32. package/dist/snaps/endowments/transaction-insight.js.map +1 -1
  33. package/dist/snaps/endowments/web-assembly.d.ts +2 -2
  34. package/dist/snaps/endowments/web-assembly.js +2 -2
  35. package/dist/snaps/endowments/web-assembly.js.map +1 -1
  36. package/dist/snaps/index.d.ts +1 -0
  37. package/dist/snaps/index.js +1 -0
  38. package/dist/snaps/index.js.map +1 -1
  39. package/dist/snaps/location/npm.d.ts +20 -0
  40. package/dist/snaps/location/npm.js +30 -14
  41. package/dist/snaps/location/npm.js.map +1 -1
  42. package/dist/snaps/permissions.d.ts +16 -0
  43. package/dist/snaps/permissions.js +54 -0
  44. package/dist/snaps/permissions.js.map +1 -0
  45. package/dist/snaps/registry/registry.d.ts +3 -3
  46. package/dist/snaps/registry/registry.js.map +1 -1
  47. package/package.json +10 -10
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-insight.js","sourceRoot":"","sources":["../../../src/snaps/endowments/transaction-insight.ts"],"names":[],"mappings":";;;AAAA,2EAUyC;AACzC,uDAAuD;AACvD,2CAOyB;AACzB,mDAA2C;AAE3C,iCAAwC;AAExC,MAAM,cAAc,GAAG,qBAAc,CAAC,kBAAkB,CAAC;AAUzD;;;;;;GAMG;AACH,MAAM,oBAAoB,GAItB,CAAC,eAAyB,EAAE,EAAE;IAChC,OAAO;QACL,cAAc,EAAE,sCAAc,CAAC,SAAS;QACxC,SAAS,EAAE,cAAc;QACzB,cAAc,EAAE,CAAC,4BAAc,CAAC,iBAAiB,CAAC;QAClD,eAAe,EAAE,CAAC,cAAsC,EAAE,EAAE,CAAC,SAAS;QACtE,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE;YACzB,IACE,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC;gBACzC,CAAC,OAAO,EAAE,MAAM,KAAK,CAAC;oBACpB,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,4BAAc,CAAC,iBAAiB,CAAC,EACvD;gBACA,MAAM,0BAAS,CAAC,GAAG,CA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B,0BAA0B,CACxC,UAAiC;IAEjC,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE;QACxB,OAAO,IAAI,CAAC;KACb;IAED,IAAA,cAAM,EAAC,UAAU,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;IACxC,IAAA,cAAM,EAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,4BAAc,CAAC,iBAAiB,CAAC,CAAC;IAExE,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,CAA4B,CAAC;IAEhE,OAAO,MAAM,CAAC,KAAK,IAAI,IAAI,CAAC;AAC9B,CAAC;AAbD,gEAaC;AAEY,QAAA,sCAAsC,GAG/C;IACF,CAAC,4BAAc,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC;QAChD,IAAI,EAAE,4BAAc,CAAC,iBAAiB;QACtC,SAAS,EAAE,CAAC,MAA2B,EAAE,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC;KACnE,CAAC;CACH,CAAC","sourcesContent":["import {\n PermissionSpecificationBuilder,\n PermissionType,\n EndowmentGetterParams,\n ValidPermissionSpecification,\n PermissionValidatorConstraint,\n PermissionConstraint,\n CaveatSpecificationConstraint,\n Caveat,\n SubjectType,\n} from '@metamask/permission-controller';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\nimport {\n assert,\n hasProperty,\n isObject,\n isPlainObject,\n Json,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.TransactionInsight;\n\ntype TransactionInsightEndowmentSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.Endowment;\n targetKey: typeof permissionName;\n endowmentGetter: (_options?: EndowmentGetterParams) => undefined;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\n/**\n * `endowment:transaction-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 transaction confirmation screen.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the transaction-insight endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n TransactionInsightEndowmentSpecification\n> = (_builderOptions?: unknown) => {\n return {\n permissionType: PermissionType.Endowment,\n targetKey: permissionName,\n allowedCaveats: [SnapCaveatType.TransactionOrigin],\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.TransactionOrigin)\n ) {\n throw ethErrors.rpc.invalidParams({\n message: `Expected a single \"${SnapCaveatType.TransactionOrigin}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nexport const transactionInsightEndowmentBuilder = Object.freeze({\n targetKey: 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 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 * PermissionsController when the permission is requested.\n *\n * @param value - The raw value from the `initialPermissions`.\n * @returns The caveat specification.\n */\nexport function getTransactionInsightCaveatMapper(\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.TransactionOrigin,\n value:\n hasProperty(value, 'allowTransactionOrigin') &&\n (value.allowTransactionOrigin as boolean),\n },\n ],\n };\n}\n\n/**\n * Getter function to get the transaction 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 transaction origin caveat from.\n * @returns The transaction origin, or `null` if the permission does not have a\n * transaction origin caveat.\n */\nexport function getTransactionOriginCaveat(\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.TransactionOrigin);\n\n const caveat = permission.caveats[0] as Caveat<string, boolean>;\n\n return caveat.value ?? null;\n}\n\nexport const transactionInsightCaveatSpecifications: Record<\n SnapCaveatType.TransactionOrigin,\n CaveatSpecificationConstraint\n> = {\n [SnapCaveatType.TransactionOrigin]: Object.freeze({\n type: SnapCaveatType.TransactionOrigin,\n validator: (caveat: Caveat<string, any>) => validateCaveat(caveat),\n }),\n};\n"]}
1
+ {"version":3,"file":"transaction-insight.js","sourceRoot":"","sources":["../../../src/snaps/endowments/transaction-insight.ts"],"names":[],"mappings":";;;AAAA,2EAUyC;AACzC,uDAAuD;AACvD,2CAOyB;AACzB,mDAA2C;AAE3C,iCAAwC;AAExC,MAAM,cAAc,GAAG,qBAAc,CAAC,kBAAkB,CAAC;AAUzD;;;;;;GAMG;AACH,MAAM,oBAAoB,GAItB,CAAC,eAAyB,EAAE,EAAE;IAChC,OAAO;QACL,cAAc,EAAE,sCAAc,CAAC,SAAS;QACxC,UAAU,EAAE,cAAc;QAC1B,cAAc,EAAE,CAAC,4BAAc,CAAC,iBAAiB,CAAC;QAClD,eAAe,EAAE,CAAC,cAAsC,EAAE,EAAE,CAAC,SAAS;QACtE,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE;YACzB,IACE,CAAC,OAAO,KAAK,IAAI,IAAI,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC;gB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ACH,IAAA,mBAAW,EAAC,KAAK,EAAE,wBAAwB,CAAC;oBAC3C,KAAK,CAAC,sBAAkC;aAC5C;SACF;KACF,CAAC;AACJ,CAAC;AApBD,8EAoBC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,0BAA0B,CACxC,UAAiC;IAEjC,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE;QACxB,OAAO,IAAI,CAAC;KACb;IAED,IAAA,cAAM,EAAC,UAAU,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;IACxC,IAAA,cAAM,EAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,4BAAc,CAAC,iBAAiB,CAAC,CAAC;IAExE,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,CAA4B,CAAC;IAEhE,OAAO,MAAM,CAAC,KAAK,IAAI,IAAI,CAAC;AAC9B,CAAC;AAbD,gEAaC;AAEY,QAAA,sCAAsC,GAG/C;IACF,CAAC,4BAAc,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC;QAChD,IAAI,EAAE,4BAAc,CAAC,iBAAiB;QACtC,SAAS,EAAE,CAAC,MAA2B,EAAE,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC;KACnE,CAAC;CACH,CAAC","sourcesContent":["import {\n PermissionSpecificationBuilder,\n PermissionType,\n EndowmentGetterParams,\n ValidPermissionSpecification,\n PermissionValidatorConstraint,\n PermissionConstraint,\n CaveatSpecificationConstraint,\n Caveat,\n SubjectType,\n} from '@metamask/permission-controller';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\nimport {\n assert,\n hasProperty,\n isObject,\n isPlainObject,\n Json,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.TransactionInsight;\n\ntype TransactionInsightEndowmentSpecification = 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:transaction-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 transaction confirmation screen.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the transaction-insight endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n TransactionInsightEndowmentSpecification\n> = (_builderOptions?: unknown) => {\n return {\n permissionType: PermissionType.Endowment,\n targetName: permissionName,\n allowedCaveats: [SnapCaveatType.TransactionOrigin],\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.TransactionOrigin)\n ) {\n throw ethErrors.rpc.invalidParams({\n message: `Expected a single \"${SnapCaveatType.TransactionOrigin}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nexport const transactionInsightEndowmentBuilder = 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 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 * PermissionsController when the permission is requested.\n *\n * @param value - The raw value from the `initialPermissions`.\n * @returns The caveat specification.\n */\nexport function getTransactionInsightCaveatMapper(\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.TransactionOrigin,\n value:\n hasProperty(value, 'allowTransactionOrigin') &&\n (value.allowTransactionOrigin as boolean),\n },\n ],\n };\n}\n\n/**\n * Getter function to get the transaction 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 transaction origin caveat from.\n * @returns The transaction origin, or `null` if the permission does not have a\n * transaction origin caveat.\n */\nexport function getTransactionOriginCaveat(\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.TransactionOrigin);\n\n const caveat = permission.caveats[0] as Caveat<string, boolean>;\n\n return caveat.value ?? null;\n}\n\nexport const transactionInsightCaveatSpecifications: Record<\n SnapCaveatType.TransactionOrigin,\n CaveatSpecificationConstraint\n> = {\n [SnapCaveatType.TransactionOrigin]: Object.freeze({\n type: SnapCaveatType.TransactionOrigin,\n validator: (caveat: Caveat<string, any>) => validateCaveat(caveat),\n }),\n};\n"]}
@@ -2,10 +2,10 @@ import { PermissionSpecificationBuilder, PermissionType } from '@metamask/permis
2
2
  import { SnapEndowments } from './enum';
3
3
  declare const permissionName = SnapEndowments.WebAssemblyAccess;
4
4
  export declare const webAssemblyEndowmentBuilder: Readonly<{
5
- readonly targetKey: SnapEndowments.WebAssemblyAccess;
5
+ readonly targetName: SnapEndowments.WebAssemblyAccess;
6
6
  readonly specificationBuilder: PermissionSpecificationBuilder<PermissionType.Endowment, any, {
7
7
  permissionType: PermissionType.Endowment;
8
- targetKey: typeof permissionName;
8
+ targetName: typeof permissionName;
9
9
  endowmentGetter: (_options?: any) => ['WebAssembly'];
10
10
  allowedCaveats: null;
11
11
  }>;
@@ -16,7 +16,7 @@ const permissionName = enum_1.SnapEndowments.WebAssemblyAccess;
16
16
  const specificationBuilder = (_builderOptions) => {
17
17
  return {
18
18
  permissionType: permission_controller_1.PermissionType.Endowment,
19
- targetKey: permissionName,
19
+ targetName: permissionName,
20
20
  allowedCaveats: null,
21
21
  endowmentGetter: (_getterOptions) => {
22
22
  return ['WebAssembly'];
@@ -25,7 +25,7 @@ const specificationBuilder = (_builderOptions) => {
25
25
  };
26
26
  };
27
27
  exports.webAssemblyEndowmentBuilder = Object.freeze({
28
- targetKey: permissionName,
28
+ targetName: permissionName,
29
29
  specificationBuilder,
30
30
  });
31
31
  //# sourceMappingURL=web-assembly.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"web-assembly.js","sourceRoot":"","sources":["../../../src/snaps/endowments/web-assembly.ts"],"names":[],"mappings":";;;AAAA,2EAMyC;AAEzC,iCAAwC;AAExC,MAAM,cAAc,GAAG,qBAAc,CAAC,iBAAiB,CAAC;AASxD;;;;;;;;GAQG;AACH,MAAM,oBAAoB,GAItB,CAAC,eAAqB,EAAE,EAAE;IAC5B,OAAO;QACL,cAAc,EAAE,sCAAc,CAAC,SAAS;QACxC,SAAS,EAAE,cAAc;QACzB,cAAc,EAAE,IAAI;QACpB,eAAe,EAAE,CAAC,cAAsC,EAAE,EAAE;YAC1D,OAAO,CAAC,aAAa,CAAC,CAAC;QACzB,CAAC;QACD,YAAY,EAAE,CAAC,mCAAW,CAAC,IAAI,CAAC;KACjC,CAAC;AACJ,CAAC,CAAC;AAEW,QAAA,2BAA2B,GAAG,MAAM,CAAC,MAAM,CAAC;IACvD,SAAS,EAAE,cAAc;IACzB,oBAAoB;CACZ,CAAC,CAAC","sourcesContent":["import {\n EndowmentGetterParams,\n PermissionSpecificationBuilder,\n PermissionType,\n ValidPermissionSpecification,\n SubjectType,\n} from '@metamask/permission-controller';\n\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.WebAssemblyAccess;\n\ntype WebAssemblyEndowmentSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.Endowment;\n targetKey: typeof permissionName;\n endowmentGetter: (_options?: any) => ['WebAssembly'];\n allowedCaveats: null;\n}>;\n\n/**\n * `endowment:webassembly` returns the name of global browser API(s) that\n * enable access to the WebAssembly API.\n * This is intended to populate the endowments of the SES Compartment\n * in which a Snap executes.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the WebAssembly endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n WebAssemblyEndowmentSpecification\n> = (_builderOptions?: any) => {\n return {\n permissionType: PermissionType.Endowment,\n targetKey: permissionName,\n allowedCaveats: null,\n endowmentGetter: (_getterOptions?: EndowmentGetterParams) => {\n return ['WebAssembly'];\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nexport const webAssemblyEndowmentBuilder = Object.freeze({\n targetKey: permissionName,\n specificationBuilder,\n} as const);\n"]}
1
+ {"version":3,"file":"web-assembly.js","sourceRoot":"","sources":["../../../src/snaps/endowments/web-assembly.ts"],"names":[],"mappings":";;;AAAA,2EAMyC;AAEzC,iCAAwC;AAExC,MAAM,cAAc,GAAG,qBAAc,CAAC,iBAAiB,CAAC;AASxD;;;;;;;;GAQG;AACH,MAAM,oBAAoB,GAItB,CAAC,eAAqB,EAAE,EAAE;IAC5B,OAAO;QACL,cAAc,EAAE,sCAAc,CAAC,SAAS;QACxC,UAAU,EAAE,cAAc;QAC1B,cAAc,EAAE,IAAI;QACpB,eAAe,EAAE,CAAC,cAAsC,EAAE,EAAE;YAC1D,OAAO,CAAC,aAAa,CAAC,CAAC;QACzB,CAAC;QACD,YAAY,EAAE,CAAC,mCAAW,CAAC,IAAI,CAAC;KACjC,CAAC;AACJ,CAAC,CAAC;AAEW,QAAA,2BAA2B,GAAG,MAAM,CAAC,MAAM,CAAC;IACvD,UAAU,EAAE,cAAc;IAC1B,oBAAoB;CACZ,CAAC,CAAC","sourcesContent":["import {\n EndowmentGetterParams,\n PermissionSpecificationBuilder,\n PermissionType,\n ValidPermissionSpecification,\n SubjectType,\n} from '@metamask/permission-controller';\n\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.WebAssemblyAccess;\n\ntype WebAssemblyEndowmentSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.Endowment;\n targetName: typeof permissionName;\n endowmentGetter: (_options?: any) => ['WebAssembly'];\n allowedCaveats: null;\n}>;\n\n/**\n * `endowment:webassembly` returns the name of global browser API(s) that\n * enable access to the WebAssembly API.\n * This is intended to populate the endowments of the SES Compartment\n * in which a Snap executes.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the WebAssembly endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n WebAssemblyEndowmentSpecification\n> = (_builderOptions?: any) => {\n return {\n permissionType: PermissionType.Endowment,\n targetName: permissionName,\n allowedCaveats: null,\n endowmentGetter: (_getterOptions?: EndowmentGetterParams) => {\n return ['WebAssembly'];\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nexport const webAssemblyEndowmentBuilder = Object.freeze({\n targetName: permissionName,\n specificationBuilder,\n} as const);\n"]}
@@ -2,3 +2,4 @@ export * from './SnapController';
2
2
  export * from './endowments';
3
3
  export * from './selectors';
4
4
  export * from './registry';
5
+ export * from './permissions';
@@ -18,4 +18,5 @@ __exportStar(require("./SnapController"), exports);
18
18
  __exportStar(require("./endowments"), exports);
19
19
  __exportStar(require("./selectors"), exports);
20
20
  __exportStar(require("./registry"), exports);
21
+ __exportStar(require("./permissions"), exports);
21
22
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/snaps/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,mDAAiC;AACjC,+CAA6B;AAC7B,8CAA4B;AAC5B,6CAA2B","sourcesContent":["export * from './SnapController';\nexport * from './endowments';\nexport * from './selectors';\nexport * from './registry';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/snaps/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,mDAAiC;AACjC,+CAA6B;AAC7B,8CAA4B;AAC5B,6CAA2B;AAC3B,gDAA8B","sourcesContent":["export * from './SnapController';\nexport * from './endowments';\nexport * from './selectors';\nexport * from './registry';\nexport * from './permissions';\n"]}
@@ -1,6 +1,7 @@
1
1
  import { SnapManifest, VirtualFile } from '@metamask/snaps-utils';
2
2
  import { SemVerRange } from '@metamask/utils';
3
3
  import { DetectSnapLocationOptions, SnapLocation } from './location';
4
+ export declare const DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
4
5
  export interface NpmOptions {
5
6
  /**
6
7
  * @default DEFAULT_REQUESTED_SNAP_VERSION
@@ -26,3 +27,22 @@ export declare class NpmLocation implements SnapLocation {
26
27
  get registry(): URL;
27
28
  get versionRange(): SemVerRange;
28
29
  }
30
+ export declare type PartialNpmMetadata = {
31
+ versions: Record<string, {
32
+ dist: {
33
+ tarball: string;
34
+ };
35
+ }>;
36
+ };
37
+ /**
38
+ * Fetches the NPM metadata of the specified package from
39
+ * the public npm registry.
40
+ *
41
+ * @param packageName - The name of the package whose metadata to fetch.
42
+ * @param registryUrl - The URL of the npm registry to fetch the metadata from.
43
+ * @param fetchFunction - The fetch function to use. Defaults to the global
44
+ * {@link fetch}. Useful for Node.js compatibility.
45
+ * @returns The NPM metadata object.
46
+ * @throws If fetching the metadata fails.
47
+ */
48
+ export declare function fetchNpmMetadata(packageName: string, registryUrl: URL | string, fetchFunction: typeof fetch): Promise<PartialNpmMetadata>;
@@ -9,7 +9,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  };
10
10
  var _NpmLocation_instances, _NpmLocation_lazyInit;
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.NpmLocation = void 0;
12
+ exports.fetchNpmMetadata = exports.NpmLocation = exports.DEFAULT_NPM_REGISTRY = void 0;
13
13
  const snaps_utils_1 = require("@metamask/snaps-utils");
14
14
  const utils_1 = require("@metamask/utils");
15
15
  const concat_stream_1 = __importDefault(require("concat-stream"));
@@ -17,7 +17,7 @@ const gunzip_maybe_1 = __importDefault(require("gunzip-maybe"));
17
17
  const pump_1 = __importDefault(require("pump"));
18
18
  const readable_web_to_node_stream_1 = require("readable-web-to-node-stream");
19
19
  const tar_stream_1 = require("tar-stream");
20
- const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
20
+ exports.DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
21
21
  class NpmLocation {
22
22
  constructor(url, opts = {}) {
23
23
  _NpmLocation_instances.add(this);
@@ -30,7 +30,7 @@ class NpmLocation {
30
30
  url.port === '' &&
31
31
  url.username === '' &&
32
32
  url.password === '') {
33
- registry = new URL(DEFAULT_NPM_REGISTRY);
33
+ registry = new URL(exports.DEFAULT_NPM_REGISTRY);
34
34
  }
35
35
  else {
36
36
  registry = 'https://';
@@ -124,19 +124,17 @@ _NpmLocation_instances = new WeakSet(), _NpmLocation_lazyInit = async function _
124
124
  // Safety limit for tarballs, 250 MB in bytes
125
125
  const TARBALL_SIZE_SAFETY_LIMIT = 262144000;
126
126
  /**
127
- * Fetches the tarball (`.tgz` file) of the specified package and version from
128
- * the public npm registry. Throws an error if fetching fails.
127
+ * Fetches the NPM metadata of the specified package from
128
+ * the public npm registry.
129
129
  *
130
- * @param packageName - The name of the package whose tarball to fetch.
131
- * @param versionRange - The SemVer range of the package to fetch. The highest
132
- * version satisfying the range will be fetched.
133
- * @param registryUrl - The URL of the npm registry to fetch the tarball from.
130
+ * @param packageName - The name of the package whose metadata to fetch.
131
+ * @param registryUrl - The URL of the npm registry to fetch the metadata from.
134
132
  * @param fetchFunction - The fetch function to use. Defaults to the global
135
133
  * {@link fetch}. Useful for Node.js compatibility.
136
- * @returns A tuple of the {@link Response} for the package tarball and the
137
- * actual version of the package.
134
+ * @returns The NPM metadata object.
135
+ * @throws If fetching the metadata fails.
138
136
  */
139
- async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunction) {
137
+ async function fetchNpmMetadata(packageName, registryUrl, fetchFunction) {
140
138
  const packageResponse = await fetchFunction(new URL(packageName, registryUrl).toString());
141
139
  if (!packageResponse.ok) {
142
140
  throw new Error(`Failed to fetch NPM registry entry. Status code: ${packageResponse.status}.`);
@@ -145,6 +143,25 @@ async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunc
145
143
  if (!(0, utils_1.isObject)(packageMetadata)) {
146
144
  throw new Error(`Failed to fetch package "${packageName}" metadata from npm.`);
147
145
  }
146
+ return packageMetadata;
147
+ }
148
+ exports.fetchNpmMetadata = fetchNpmMetadata;
149
+ /**
150
+ * Fetches the tarball (`.tgz` file) of the specified package and version from
151
+ * the public npm registry.
152
+ *
153
+ * @param packageName - The name of the package whose tarball to fetch.
154
+ * @param versionRange - The SemVer range of the package to fetch. The highest
155
+ * version satisfying the range will be fetched.
156
+ * @param registryUrl - The URL of the npm registry to fetch the tarball from.
157
+ * @param fetchFunction - The fetch function to use. Defaults to the global
158
+ * {@link fetch}. Useful for Node.js compatibility.
159
+ * @returns A tuple of the {@link Response} for the package tarball and the
160
+ * actual version of the package.
161
+ * @throws If fetching the tarball fails.
162
+ */
163
+ async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunction) {
164
+ const packageMetadata = await fetchNpmMetadata(packageName, registryUrl, fetchFunction);
148
165
  const versions = Object.keys(packageMetadata?.versions ?? {}).map((version) => {
149
166
  (0, utils_1.assertIsSemVerVersion)(version);
150
167
  return version;
@@ -153,8 +170,7 @@ async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunc
153
170
  if (targetVersion === null) {
154
171
  throw new Error(`Failed to find a matching version in npm metadata for package "${packageName}" and requested semver range "${versionRange}".`);
155
172
  }
156
- const tarballUrlString = packageMetadata?.versions?.[targetVersion]
157
- ?.dist?.tarball;
173
+ const tarballUrlString = packageMetadata?.versions?.[targetVersion]?.dist?.tarball;
158
174
  if (!(0, snaps_utils_1.isValidUrl)(tarballUrlString) ||
159
175
  !tarballUrlString.toString().endsWith('.tgz')) {
160
176
  throw new Error(`Failed to find valid tarball URL in NPM metadata for package "${packageName}".`);
@@ -1 +1 @@
1
- {"version":3,"file":"npm.js","sourceRoot":"","sources":["../../../src/snaps/location/npm.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uDAS+B;AAC/B,2CAOyB;AACzB,kEAAmC;AACnC,gEAA8C;AAC9C,gDAAwB;AACxB,6EAAsE;AAEtE,2CAAmD;AAInD,MAAM,oBAAoB,GAAG,4BAA4B,CAAC;AAsB1D,MAAa,WAAW;IAOtB,YAAY,GAAQ,EAAE,OAAkC,EAAE;;QACxD,MAAM,qBAAqB,GAAG,IAAI,CAAC,qBAAqB,IAAI,KAAK,CAAC;QAClE,MAAM,aAAa,GAAG,IAAI,CAAC,KAAK,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACtE,MAAM,cAAc,GAAG,IAAI,CAAC,YAAY,IAAI,4CAA8B,CAAC;QAE3E,IAAA,oBAAY,EAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,6BAAe,EAAE,mBAAmB,CAAC,CAAC;QAEnE,IAAI,QAAsB,CAAC;QAC3B,IACE,GAAG,CAAC,IAAI,KAAK,EAAE;YACf,GAAG,CAAC,IAAI,KAAK,EAAE;YACf,GAAG,CAAC,QAAQ,KAAK,EAAE;YACnB,GAAG,CAAC,QAAQ,KAAK,EAAE,EACnB;YACA,QAAQ,GAAG,IAAI,GAAG,CAAC,oBAAoB,CAAC,CAAC;SAC1C;aAAM;YACL,QAAQ,GAAG,UAAU,CAAC;YACtB,IAAI,GAAG,CAAC,QAAQ,EAAE;gBAChB,QAAQ,IAAI,GAAG,CAAC,QAAQ,CAAC;gBACzB,IAAI,GAAG,CAAC,QAAQ,EAAE;oBAChB,QAAQ,IAAI,IAAI,GAAG,CAAC,QAAQ,EAAE,CAAC;iBAChC;gBACD,QAAQ,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AAC;iBACrC;YACH,CAAC,CAAC,CACH,CAAC;SACH;QAED,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7C,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;QACpC,OAAO,WAAW,CAAC,MAAM,EAAE,CAAC;IAC9B,CAAC,CAAC,CAAC;IACH,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import {\n createSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n SnapManifest,\n VirtualFile,\n normalizeRelative,\n} from '@metamask/snaps-utils';\nimport {\n assert,\n assertIsSemVerVersion,\n assertStruct,\n isObject,\n SemVerRange,\n SemVerVersion,\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 { Readable, Writable } from 'stream';\nimport { extract as tarExtract } from 'tar-stream';\n\nimport { DetectSnapLocationOptions, SnapLocation } from './location';\n\nconst 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 = JSON.parse(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/**\n * Fetches the tarball (`.tgz` file) of the specified package and version from\n * the public npm registry. Throws an error if fetching fails.\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 */\nasync function fetchNpmTarball(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl: URL | string,\n fetchFunction: typeof fetch,\n): Promise<[ReadableStream, SemVerVersion]> {\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 const versions = Object.keys((packageMetadata as any)?.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 = (packageMetadata as any)?.versions?.[targetVersion]\n ?.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"]}
1
+ {"version":3,"file":"npm.js","sourceRoot":"","sources":["../../../src/snaps/location/npm.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uDAS+B;AAC/B,2CAOyB;AACzB,kEAAmC;AACnC,gEAA8C;AAC9C,gDAAwB;AACxB,6EAAsE;AAEtE,2CAAmD;AAItC,QAAA,oBAAoB,GAAG,4BAA4B,CAAC;AAsBjE,MAAa,WAAW;IAOtB,YAAY,GAAQ,EAAE,OAAkC,EAAE;;QACxD,MAAM,qBAAqB,GAAG,IAAI,CAAC,qBAAqB,IAAI,KAAK,CAAC;QAClE,MAAM,aAAa,GAAG,IAAI,CAAC,KAAK,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACtE,MAAM,cAAc,GAAG,IAAI,CAAC,YAAY,IAAI,4CAA8B,CAAC;QAE3E,IAAA,oBAAY,EAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,6BAAe,EAAE,mBAAmB,CAAC,CAAC;QAEnE,IAAI,QAAsB,CAAC;QAC3B,IACE,GAAG,CAAC,IAAI,KAAK,EAAE;YACf,GAAG,CAAC,IAAI,KAAK,EAAE;YACf,GAAG,CAAC,QAAQ,KAAK,EAAE;YACnB,GAAG,CAAC,QAAQ,KAAK,EAAE,EACnB;YACA,QAAQ,GAAG,IAAI,GAAG,CAAC,4BAAoB,CAAC,CAAC;SAC1C;aAAM;YACL,QAAQ,GAAG,UAAU,CAAC;YACtB,IAAI,GAAG,CAAC,QAAQ,EAAE;gBAChB,QAAQ,IAAI,GAAG,CAAC,QAAQ,CAAC;gBACzB,IAAI,GAAG,CAAC,QAAQ,EAAE;oBAChB,QAAQ,IAAI,IAAI,GAAG,CAAC,QAAQ,EAAE,CAAC;iBAChC;gBACD,QAAQ,IAAI,GAAG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AAI,CAAC,EAChB,uDAAuD,CACxD,CAAC;oBACF,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;oBACvB,OAAO,IAAI,EAAE,CAAC;iBACf;gBAAC,OAAO,KAAK,EAAE;oBACd,OAAO,aAAa,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;iBACrC;YACH,CAAC,CAAC,CACH,CAAC;SACH;QAED,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7C,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;QACpC,OAAO,WAAW,CAAC,MAAM,EAAE,CAAC;IAC9B,CAAC,CAAC,CAAC;IACH,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import {\n createSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n SnapManifest,\n VirtualFile,\n normalizeRelative,\n} from '@metamask/snaps-utils';\nimport {\n assert,\n assertIsSemVerVersion,\n assertStruct,\n isObject,\n SemVerRange,\n SemVerVersion,\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 { Readable, Writable } from 'stream';\nimport { extract as tarExtract } from 'tar-stream';\n\nimport { 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 = JSON.parse(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"]}
@@ -0,0 +1,16 @@
1
+ import { PermissionConstraint, PermissionSpecificationConstraint } from '@metamask/permission-controller';
2
+ import { SnapPermissions } from '@metamask/snaps-utils';
3
+ /**
4
+ * Map initial permissions as defined in a Snap manifest to something that can
5
+ * be processed by the PermissionsController. Each caveat mapping function
6
+ * should return a valid permission caveat value.
7
+ *
8
+ * This function does not validate the caveat values, since that is done by
9
+ * the PermissionsController itself, upon requesting the permissions.
10
+ *
11
+ * @param initialPermissions - The initial permissions to process.
12
+ * @returns The processed permissions.
13
+ */
14
+ export declare function processSnapPermissions(initialPermissions: SnapPermissions): Record<string, Pick<PermissionConstraint, 'caveats'>>;
15
+ export declare const buildSnapEndowmentSpecifications: (excludedEndowments: string[]) => Record<string, PermissionSpecificationConstraint>;
16
+ export declare const buildSnapRestrictedMethodSpecifications: (excludedPermissions: string[], hooks: Record<string, unknown>) => Record<string, PermissionSpecificationConstraint>;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSnapRestrictedMethodSpecifications = exports.buildSnapEndowmentSpecifications = exports.processSnapPermissions = void 0;
4
+ const rpc_methods_1 = require("@metamask/rpc-methods");
5
+ const utils_1 = require("@metamask/utils");
6
+ const endowments_1 = require("./endowments");
7
+ /**
8
+ * Map initial permissions as defined in a Snap manifest to something that can
9
+ * be processed by the PermissionsController. Each caveat mapping function
10
+ * should return a valid permission caveat value.
11
+ *
12
+ * This function does not validate the caveat values, since that is done by
13
+ * the PermissionsController itself, upon requesting the permissions.
14
+ *
15
+ * @param initialPermissions - The initial permissions to process.
16
+ * @returns The processed permissions.
17
+ */
18
+ function processSnapPermissions(initialPermissions) {
19
+ return Object.fromEntries(Object.entries(initialPermissions).map(([initialPermission, value]) => {
20
+ if ((0, utils_1.hasProperty)(rpc_methods_1.caveatMappers, initialPermission)) {
21
+ return [initialPermission, rpc_methods_1.caveatMappers[initialPermission](value)];
22
+ }
23
+ else if ((0, utils_1.hasProperty)(endowments_1.endowmentCaveatMappers, initialPermission)) {
24
+ return [
25
+ initialPermission,
26
+ endowments_1.endowmentCaveatMappers[initialPermission](value),
27
+ ];
28
+ }
29
+ // If we have no mapping, this may be a non-snap permission, return as-is
30
+ return [
31
+ initialPermission,
32
+ value,
33
+ ];
34
+ }));
35
+ }
36
+ exports.processSnapPermissions = processSnapPermissions;
37
+ const buildSnapEndowmentSpecifications = (excludedEndowments) => Object.values(endowments_1.endowmentPermissionBuilders).reduce((allSpecifications, { targetName, specificationBuilder }) => {
38
+ if (!excludedEndowments.includes(targetName)) {
39
+ allSpecifications[targetName] = specificationBuilder({});
40
+ }
41
+ return allSpecifications;
42
+ }, {});
43
+ exports.buildSnapEndowmentSpecifications = buildSnapEndowmentSpecifications;
44
+ const buildSnapRestrictedMethodSpecifications = (excludedPermissions, hooks) => Object.values(rpc_methods_1.restrictedMethodPermissionBuilders).reduce((specifications, { targetName, specificationBuilder, methodHooks }) => {
45
+ if (!excludedPermissions.includes(targetName)) {
46
+ specifications[targetName] = specificationBuilder({
47
+ // @ts-expect-error The selectHooks type is wonky
48
+ methodHooks: (0, rpc_methods_1.selectHooks)(hooks, methodHooks),
49
+ });
50
+ }
51
+ return specifications;
52
+ }, {});
53
+ exports.buildSnapRestrictedMethodSpecifications = buildSnapRestrictedMethodSpecifications;
54
+ //# sourceMappingURL=permissions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permissions.js","sourceRoot":"","sources":["../../src/snaps/permissions.ts"],"names":[],"mappings":";;;AAIA,uDAI+B;AAE/B,2CAA8C;AAE9C,6CAGsB;AAEtB;;;;;;;;;;GAUG;AACH,SAAgB,sBAAsB,CACpC,kBAAmC;IAEnC,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,iBAAiB,EAAE,KAAK,CAAC,EAAE,EAAE;QACpE,IAAI,IAAA,mBAAW,EAAC,2BAAa,EAAE,iBAAiB,CAAC,EAAE;YACjD,OAAO,CAAC,iBAAiB,EAAE,2BAAa,CAAC,iBAAiB,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;SACrE;aAAM,IAAI,IAAA,mBAAW,EAAC,mCAAsB,EAAE,iBAAiB,CAAC,EAAE;YACjE,OAAO;gBACL,iBAAiB;gBACjB,mCAAsB,CAAC,iBAAiB,CAAC,CAAC,KAAK,CAAC;aACjD,CAAC;SACH;QAED,yEAAyE;QACzE,OAAO;YACL,iBAAiB;YACjB,KAA8C;SAC/C,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;AACJ,CAAC;AArBD,wDAqBC;AAEM,MAAM,gCAAgC,GAAG,CAC9C,kBAA4B,EAC5B,EAAE,CACF,MAAM,CAAC,MAAM,CAAC,wCAA2B,CAAC,CAAC,MAAM,CAE/C,CAAC,iBAAiB,EAAE,EAAE,UAAU,EAAE,oBAAoB,EAAE,EAAE,EAAE;IAC5D,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;QAC5C,iBAAiB,CAAC,UAAU,CAAC,GAAG,oBAAoB,CAAC,EAAE,CAAC,CAAC;KAC1D;IACD,OAAO,iBAAiB,CAAC;AAC3B,CAAC,EAAE,EAAE,CAAC,CAAC;AAVI,QAAA,gCAAgC,oCAUpC;AAEF,MAAM,uCAAuC,GAAG,CACrD,mBAA6B,EAC7B,KAA8B,EAC9B,EAAE,CACF,MAAM,CAAC,MAAM,CAAC,gDAAkC,CAAC,CAAC,MAAM,CAEtD,CAAC,cAAc,EAAE,EAAE,UAAU,EAAE,oBAAoB,EAAE,WAAW,EAAE,EAAE,EAAE;IACtE,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;QAC7C,cAAc,CAAC,UAAU,CAAC,GAAG,oBAAoB,CAAC;YAChD,iDAAiD;YACjD,WAAW,EAAE,IAAA,yBAAW,EACtB,KAAK,EACL,WAAW,CACoC;SAClD,CAAC,CAAC;KACJ;IACD,OAAO,cAAc,CAAC;AACxB,CAAC,EAAE,EAAE,CAAC,CAAC;AAjBI,QAAA,uCAAuC,2CAiB3C","sourcesContent":["import {\n PermissionConstraint,\n PermissionSpecificationConstraint,\n} from '@metamask/permission-controller';\nimport {\n caveatMappers,\n restrictedMethodPermissionBuilders,\n selectHooks,\n} from '@metamask/rpc-methods';\nimport { SnapPermissions } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport {\n endowmentCaveatMappers,\n endowmentPermissionBuilders,\n} from './endowments';\n\n/**\n * Map initial permissions as defined in a Snap manifest to something that can\n * be processed by the PermissionsController. Each caveat mapping function\n * should return a valid permission caveat value.\n *\n * This function does not validate the caveat values, since that is done by\n * the PermissionsController itself, upon requesting the permissions.\n *\n * @param initialPermissions - The initial permissions to process.\n * @returns The processed permissions.\n */\nexport function processSnapPermissions(\n initialPermissions: SnapPermissions,\n): Record<string, Pick<PermissionConstraint, 'caveats'>> {\n return Object.fromEntries(\n Object.entries(initialPermissions).map(([initialPermission, value]) => {\n if (hasProperty(caveatMappers, initialPermission)) {\n return [initialPermission, caveatMappers[initialPermission](value)];\n } else if (hasProperty(endowmentCaveatMappers, initialPermission)) {\n return [\n initialPermission,\n endowmentCaveatMappers[initialPermission](value),\n ];\n }\n\n // If we have no mapping, this may be a non-snap permission, return as-is\n return [\n initialPermission,\n value as Pick<PermissionConstraint, 'caveats'>,\n ];\n }),\n );\n}\n\nexport const buildSnapEndowmentSpecifications = (\n excludedEndowments: string[],\n) =>\n Object.values(endowmentPermissionBuilders).reduce<\n Record<string, PermissionSpecificationConstraint>\n >((allSpecifications, { targetName, specificationBuilder }) => {\n if (!excludedEndowments.includes(targetName)) {\n allSpecifications[targetName] = specificationBuilder({});\n }\n return allSpecifications;\n }, {});\n\nexport const buildSnapRestrictedMethodSpecifications = (\n excludedPermissions: string[],\n hooks: Record<string, unknown>,\n) =>\n Object.values(restrictedMethodPermissionBuilders).reduce<\n Record<string, PermissionSpecificationConstraint>\n >((specifications, { targetName, specificationBuilder, methodHooks }) => {\n if (!excludedPermissions.includes(targetName)) {\n specifications[targetName] = specificationBuilder({\n // @ts-expect-error The selectHooks type is wonky\n methodHooks: selectHooks<typeof hooks, keyof typeof methodHooks>(\n hooks,\n methodHooks,\n ) as Pick<typeof hooks, keyof typeof methodHooks>,\n });\n }\n return specifications;\n }, {});\n"]}
@@ -1,12 +1,12 @@
1
1
  import { BlockReason, SnapsRegistryDatabase } from '@metamask/snaps-registry';
2
- import { SnapId } from '@metamask/snaps-utils';
2
+ import { SnapId, ValidatedSnapId } from '@metamask/snaps-utils';
3
3
  import { SemVerVersion } from '@metamask/utils';
4
4
  export declare type SnapsRegistryInfo = {
5
5
  version: SemVerVersion;
6
6
  checksum: string;
7
7
  };
8
8
  export declare type SnapsRegistryRequest = Record<SnapId, SnapsRegistryInfo>;
9
- export declare type SnapsRegistryMetadata = SnapsRegistryDatabase['verifiedSnaps'][SnapId]['metadata'];
9
+ export declare type SnapsRegistryMetadata = SnapsRegistryDatabase['verifiedSnaps'][ValidatedSnapId]['metadata'];
10
10
  export declare enum SnapsRegistryStatus {
11
11
  Unverified = 0,
12
12
  Blocked = 1,
@@ -17,7 +17,7 @@ export declare type SnapsRegistryResult = {
17
17
  reason?: BlockReason;
18
18
  };
19
19
  export declare type SnapsRegistry = {
20
- get(snaps: SnapsRegistryRequest): Promise<Record<SnapId, SnapsRegistryResult>>;
20
+ get(snaps: SnapsRegistryRequest): Promise<Record<ValidatedSnapId, SnapsRegistryResult>>;
21
21
  /**
22
22
  * Get metadata for the given snap ID.
23
23
  *
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../src/snaps/registry/registry.ts"],"names":[],"mappings":";;;AASA,kCAAkC;AAClC,IAAY,mBAIX;AAJD,WAAY,mBAAmB;IAC7B,yEAAU,CAAA;IACV,mEAAO,CAAA;IACP,qEAAQ,CAAA;AACV,CAAC,EAJW,mBAAmB,GAAnB,2BAAmB,KAAnB,2BAAmB,QAI9B","sourcesContent":["import { BlockReason, SnapsRegistryDatabase } from '@metamask/snaps-registry';\nimport { SnapId } from '@metamask/snaps-utils';\nimport { SemVerVersion } from '@metamask/utils';\n\nexport type SnapsRegistryInfo = { version: SemVerVersion; checksum: string };\nexport type SnapsRegistryRequest = Record<SnapId, SnapsRegistryInfo>;\nexport type SnapsRegistryMetadata =\n SnapsRegistryDatabase['verifiedSnaps'][SnapId]['metadata'];\n\n// TODO: Decide on names for these\nexport enum SnapsRegistryStatus {\n Unverified,\n Blocked,\n Verified,\n}\n\nexport type SnapsRegistryResult = {\n status: SnapsRegistryStatus;\n reason?: BlockReason;\n};\n\nexport type SnapsRegistry = {\n get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<SnapId, SnapsRegistryResult>>;\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n getMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null>;\n};\n"]}
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../src/snaps/registry/registry.ts"],"names":[],"mappings":";;;AASA,kCAAkC;AAClC,IAAY,mBAIX;AAJD,WAAY,mBAAmB;IAC7B,yEAAU,CAAA;IACV,mEAAO,CAAA;IACP,qEAAQ,CAAA;AACV,CAAC,EAJW,mBAAmB,GAAnB,2BAAmB,KAAnB,2BAAmB,QAI9B","sourcesContent":["import { BlockReason, SnapsRegistryDatabase } from '@metamask/snaps-registry';\nimport { SnapId, ValidatedSnapId } from '@metamask/snaps-utils';\nimport { SemVerVersion } from '@metamask/utils';\n\nexport type SnapsRegistryInfo = { version: SemVerVersion; checksum: string };\nexport type SnapsRegistryRequest = Record<SnapId, SnapsRegistryInfo>;\nexport type SnapsRegistryMetadata =\n SnapsRegistryDatabase['verifiedSnaps'][ValidatedSnapId]['metadata'];\n\n// TODO: Decide on names for these\nexport enum SnapsRegistryStatus {\n Unverified,\n Blocked,\n Verified,\n}\n\nexport type SnapsRegistryResult = {\n status: SnapsRegistryStatus;\n reason?: BlockReason;\n};\n\nexport type SnapsRegistry = {\n get(\n snaps: SnapsRegistryRequest,\n ): Promise<Record<ValidatedSnapId, SnapsRegistryResult>>;\n\n /**\n * Get metadata for the given snap ID.\n *\n * @param snapId - The ID of the snap to get metadata for.\n * @returns The metadata for the given snap ID, or `null` if the snap is not\n * verified.\n */\n getMetadata(snapId: SnapId): Promise<SnapsRegistryMetadata | null>;\n};\n"]}
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@metamask/snaps-controllers",
3
- "version": "0.33.1-flask.1",
3
+ "version": "0.34.0-flask.1",
4
4
  "description": "Controllers for MetaMask Snaps.",
5
5
  "repository": {
6
6
  "type": "git",
7
- "url": "https://github.com/MetaMask/snaps-monorepo.git"
7
+ "url": "https://github.com/MetaMask/snaps.git"
8
8
  },
9
9
  "main": "dist/index.js",
10
10
  "browser": {
@@ -33,16 +33,16 @@
33
33
  "publish:preview": "yarn npm publish --tag preview"
34
34
  },
35
35
  "dependencies": {
36
- "@metamask/approval-controller": "^2.0.0",
37
- "@metamask/base-controller": "^2.0.0",
36
+ "@metamask/approval-controller": "^3.0.0",
37
+ "@metamask/base-controller": "^3.0.0",
38
38
  "@metamask/object-multiplex": "^1.2.0",
39
- "@metamask/permission-controller": "^3.2.0",
39
+ "@metamask/permission-controller": "^4.0.0",
40
40
  "@metamask/post-message-stream": "^6.1.2",
41
- "@metamask/rpc-methods": "^0.33.1-flask.1",
42
- "@metamask/snaps-execution-environments": "^0.33.1-flask.1",
43
- "@metamask/snaps-registry": "^1.2.0",
44
- "@metamask/snaps-utils": "^0.33.1-flask.1",
45
- "@metamask/utils": "^5.0.0",
41
+ "@metamask/rpc-methods": "^0.34.0-flask.1",
42
+ "@metamask/snaps-execution-environments": "^0.34.0-flask.1",
43
+ "@metamask/snaps-registry": "^1.2.1",
44
+ "@metamask/snaps-utils": "^0.34.0-flask.1",
45
+ "@metamask/utils": "^6.0.0",
46
46
  "@xstate/fsm": "^2.0.0",
47
47
  "concat-stream": "^2.0.0",
48
48
  "cron-parser": "^4.5.0",