@metamask/snaps-rpc-methods 3.2.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +18 -1
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/cjs/permitted/common/snapInstallation.js.map +1 -1
  4. package/dist/cjs/permitted/getFile.js +5 -4
  5. package/dist/cjs/permitted/getFile.js.map +1 -1
  6. package/dist/cjs/permitted/getSnaps.js.map +1 -1
  7. package/dist/cjs/permitted/invokeKeyring.js.map +1 -1
  8. package/dist/cjs/permitted/invokeSnapSugar.js.map +1 -1
  9. package/dist/cjs/permitted/requestSnaps.js.map +1 -1
  10. package/dist/cjs/restricted/caveats/permittedCoinTypes.js.map +1 -1
  11. package/dist/cjs/restricted/dialog.js +16 -25
  12. package/dist/cjs/restricted/dialog.js.map +1 -1
  13. package/dist/cjs/restricted/getBip32Entropy.js.map +1 -1
  14. package/dist/cjs/restricted/getBip32PublicKey.js.map +1 -1
  15. package/dist/cjs/restricted/getBip44Entropy.js +0 -1
  16. package/dist/cjs/restricted/getBip44Entropy.js.map +1 -1
  17. package/dist/cjs/restricted/getEntropy.js.map +1 -1
  18. package/dist/cjs/restricted/getLocale.js.map +1 -1
  19. package/dist/cjs/restricted/index.js +0 -9
  20. package/dist/cjs/restricted/index.js.map +1 -1
  21. package/dist/cjs/restricted/invokeSnap.js.map +1 -1
  22. package/dist/cjs/restricted/manageAccounts.js.map +1 -1
  23. package/dist/cjs/restricted/manageState.js +32 -31
  24. package/dist/cjs/restricted/manageState.js.map +1 -1
  25. package/dist/cjs/restricted/notify.js +6 -13
  26. package/dist/cjs/restricted/notify.js.map +1 -1
  27. package/dist/esm/index.js.map +1 -1
  28. package/dist/esm/permitted/common/snapInstallation.js.map +1 -1
  29. package/dist/esm/permitted/getFile.js +2 -1
  30. package/dist/esm/permitted/getFile.js.map +1 -1
  31. package/dist/esm/permitted/getSnaps.js.map +1 -1
  32. package/dist/esm/permitted/invokeKeyring.js.map +1 -1
  33. package/dist/esm/permitted/invokeSnapSugar.js.map +1 -1
  34. package/dist/esm/permitted/requestSnaps.js.map +1 -1
  35. package/dist/esm/restricted/caveats/permittedCoinTypes.js.map +1 -1
  36. package/dist/esm/restricted/dialog.js +3 -9
  37. package/dist/esm/restricted/dialog.js.map +1 -1
  38. package/dist/esm/restricted/getBip32Entropy.js.map +1 -1
  39. package/dist/esm/restricted/getBip32PublicKey.js.map +1 -1
  40. package/dist/esm/restricted/getBip44Entropy.js +0 -1
  41. package/dist/esm/restricted/getBip44Entropy.js.map +1 -1
  42. package/dist/esm/restricted/getEntropy.js.map +1 -1
  43. package/dist/esm/restricted/getLocale.js.map +1 -1
  44. package/dist/esm/restricted/index.js +0 -3
  45. package/dist/esm/restricted/index.js.map +1 -1
  46. package/dist/esm/restricted/invokeSnap.js.map +1 -1
  47. package/dist/esm/restricted/manageAccounts.js.map +1 -1
  48. package/dist/esm/restricted/manageState.js +28 -24
  49. package/dist/esm/restricted/manageState.js.map +1 -1
  50. package/dist/esm/restricted/notify.js +3 -7
  51. package/dist/esm/restricted/notify.js.map +1 -1
  52. package/dist/types/index.d.ts +0 -1
  53. package/dist/types/permitted/common/snapInstallation.d.ts +3 -5
  54. package/dist/types/permitted/getFile.d.ts +5 -4
  55. package/dist/types/permitted/getSnaps.d.ts +3 -3
  56. package/dist/types/permitted/handlers.d.ts +6 -12
  57. package/dist/types/permitted/invokeKeyring.d.ts +5 -7
  58. package/dist/types/permitted/invokeSnapSugar.d.ts +5 -8
  59. package/dist/types/permitted/requestSnaps.d.ts +3 -2
  60. package/dist/types/restricted/caveats/permittedCoinTypes.d.ts +1 -1
  61. package/dist/types/restricted/dialog.d.ts +34 -35
  62. package/dist/types/restricted/getBip32Entropy.d.ts +2 -3
  63. package/dist/types/restricted/getBip32PublicKey.d.ts +2 -6
  64. package/dist/types/restricted/getBip44Entropy.d.ts +2 -5
  65. package/dist/types/restricted/getEntropy.d.ts +3 -2
  66. package/dist/types/restricted/getLocale.d.ts +2 -1
  67. package/dist/types/restricted/index.d.ts +9 -90
  68. package/dist/types/restricted/invokeSnap.d.ts +8 -7
  69. package/dist/types/restricted/manageAccounts.d.ts +4 -3
  70. package/dist/types/restricted/manageState.d.ts +6 -15
  71. package/dist/types/restricted/notify.d.ts +4 -7
  72. package/package.json +4 -5
  73. package/dist/cjs/request.js +0 -6
  74. package/dist/cjs/request.js.map +0 -1
  75. package/dist/esm/request.js +0 -3
  76. package/dist/esm/request.js.map +0 -1
  77. package/dist/types/request.d.ts +0 -99
@@ -9,18 +9,9 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
- DialogType: function() {
13
- return _dialog.DialogType;
14
- },
15
- ManageStateOperation: function() {
16
- return _manageState.ManageStateOperation;
17
- },
18
12
  WALLET_SNAP_PERMISSION_KEY: function() {
19
13
  return _invokeSnap.WALLET_SNAP_PERMISSION_KEY;
20
14
  },
21
- NotificationType: function() {
22
- return _notify.NotificationType;
23
- },
24
15
  restrictedMethodPermissionBuilders: function() {
25
16
  return restrictedMethodPermissionBuilders;
26
17
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/restricted/index.ts"],"sourcesContent":["import type { DialogMethodHooks } from './dialog';\nimport { dialogBuilder } from './dialog';\nimport type { GetBip32EntropyMethodHooks } from './getBip32Entropy';\nimport { getBip32EntropyBuilder } from './getBip32Entropy';\nimport type { GetBip32PublicKeyMethodHooks } from './getBip32PublicKey';\nimport { getBip32PublicKeyBuilder } from './getBip32PublicKey';\nimport type { GetBip44EntropyMethodHooks } from './getBip44Entropy';\nimport { getBip44EntropyBuilder } from './getBip44Entropy';\nimport type { GetEntropyHooks } from './getEntropy';\nimport { getEntropyBuilder } from './getEntropy';\nimport type { GetLocaleMethodHooks } from './getLocale';\nimport { getLocaleBuilder } from './getLocale';\nimport type { InvokeSnapMethodHooks } from './invokeSnap';\nimport { invokeSnapBuilder } from './invokeSnap';\nimport type { ManageAccountsMethodHooks } from './manageAccounts';\nimport { manageAccountsBuilder } from './manageAccounts';\nimport type { ManageStateMethodHooks } from './manageState';\nimport { manageStateBuilder } from './manageState';\nimport type { NotifyMethodHooks } from './notify';\nimport { notifyBuilder } from './notify';\n\nexport type { DialogParameters } from './dialog';\nexport { DialogType } from './dialog';\nexport { ManageStateOperation } from './manageState';\nexport { WALLET_SNAP_PERMISSION_KEY } from './invokeSnap';\nexport type { NotificationArgs } from './notify';\nexport { NotificationType } from './notify';\n\nexport type RestrictedMethodHooks = DialogMethodHooks &\n GetBip32EntropyMethodHooks &\n GetBip32PublicKeyMethodHooks &\n GetBip44EntropyMethodHooks &\n GetEntropyHooks &\n InvokeSnapMethodHooks &\n ManageStateMethodHooks &\n NotifyMethodHooks &\n ManageAccountsMethodHooks &\n GetLocaleMethodHooks;\n\nexport const restrictedMethodPermissionBuilders = {\n [dialogBuilder.targetName]: dialogBuilder,\n [getBip32EntropyBuilder.targetName]: getBip32EntropyBuilder,\n [getBip32PublicKeyBuilder.targetName]: getBip32PublicKeyBuilder,\n [getBip44EntropyBuilder.targetName]: getBip44EntropyBuilder,\n [getEntropyBuilder.targetName]: getEntropyBuilder,\n [invokeSnapBuilder.targetName]: invokeSnapBuilder,\n [manageStateBuilder.targetName]: manageStateBuilder,\n [notifyBuilder.targetName]: notifyBuilder,\n [manageAccountsBuilder.targetName]: manageAccountsBuilder,\n [getLocaleBuilder.targetName]: getLocaleBuilder,\n} as const;\n\nexport * from './caveats';\n"],"names":["DialogType","ManageStateOperation","WALLET_SNAP_PERMISSION_KEY","NotificationType","restrictedMethodPermissionBuilders","dialogBuilder","targetName","getBip32EntropyBuilder","getBip32PublicKeyBuilder","getBip44EntropyBuilder","getEntropyBuilder","invokeSnapBuilder","manageStateBuilder","notifyBuilder","manageAccountsBuilder","getLocaleBuilder"],"mappings":";;;;;;;;;;;IAsBSA,UAAU;eAAVA,kBAAU;;IACVC,oBAAoB;eAApBA,iCAAoB;;IACpBC,0BAA0B;eAA1BA,sCAA0B;;IAE1BC,gBAAgB;eAAhBA,wBAAgB;;IAaZC,kCAAkC;eAAlCA;;;wBAtCiB;iCAES;mCAEE;iCAEF;4BAEL;2BAED;4BAEC;gCAEI;6BAEH;wBAEL;qBAiChB;;;;;;;;;;;;;;AAbP,MAAMA,qCAAqC;IAChD,CAACC,qBAAa,CAACC,UAAU,CAAC,EAAED,qBAAa;IACzC,CAACE,uCAAsB,CAACD,UAAU,CAAC,EAAEC,uCAAsB;IAC3D,CAACC,2CAAwB,CAACF,UAAU,CAAC,EAAEE,2CAAwB;IAC/D,CAACC,uCAAsB,CAACH,UAAU,CAAC,EAAEG,uCAAsB;IAC3D,CAACC,6BAAiB,CAACJ,UAAU,CAAC,EAAEI,6BAAiB;IACjD,CAACC,6BAAiB,CAACL,UAAU,CAAC,EAAEK,6BAAiB;IACjD,CAACC,+BAAkB,CAACN,UAAU,CAAC,EAAEM,+BAAkB;IACnD,CAACC,qBAAa,CAACP,UAAU,CAAC,EAAEO,qBAAa;IACzC,CAACC,qCAAqB,CAACR,UAAU,CAAC,EAAEQ,qCAAqB;IACzD,CAACC,2BAAgB,CAACT,UAAU,CAAC,EAAES,2BAAgB;AACjD"}
1
+ {"version":3,"sources":["../../../src/restricted/index.ts"],"sourcesContent":["import type { DialogMethodHooks } from './dialog';\nimport { dialogBuilder } from './dialog';\nimport type { GetBip32EntropyMethodHooks } from './getBip32Entropy';\nimport { getBip32EntropyBuilder } from './getBip32Entropy';\nimport type { GetBip32PublicKeyMethodHooks } from './getBip32PublicKey';\nimport { getBip32PublicKeyBuilder } from './getBip32PublicKey';\nimport type { GetBip44EntropyMethodHooks } from './getBip44Entropy';\nimport { getBip44EntropyBuilder } from './getBip44Entropy';\nimport type { GetEntropyHooks } from './getEntropy';\nimport { getEntropyBuilder } from './getEntropy';\nimport type { GetLocaleMethodHooks } from './getLocale';\nimport { getLocaleBuilder } from './getLocale';\nimport type { InvokeSnapMethodHooks } from './invokeSnap';\nimport { invokeSnapBuilder } from './invokeSnap';\nimport type { ManageAccountsMethodHooks } from './manageAccounts';\nimport { manageAccountsBuilder } from './manageAccounts';\nimport type { ManageStateMethodHooks } from './manageState';\nimport { manageStateBuilder } from './manageState';\nimport type { NotifyMethodHooks } from './notify';\nimport { notifyBuilder } from './notify';\n\nexport { WALLET_SNAP_PERMISSION_KEY } from './invokeSnap';\n\nexport type RestrictedMethodHooks = DialogMethodHooks &\n GetBip32EntropyMethodHooks &\n GetBip32PublicKeyMethodHooks &\n GetBip44EntropyMethodHooks &\n GetEntropyHooks &\n InvokeSnapMethodHooks &\n ManageStateMethodHooks &\n NotifyMethodHooks &\n ManageAccountsMethodHooks &\n GetLocaleMethodHooks;\n\nexport const restrictedMethodPermissionBuilders = {\n [dialogBuilder.targetName]: dialogBuilder,\n [getBip32EntropyBuilder.targetName]: getBip32EntropyBuilder,\n [getBip32PublicKeyBuilder.targetName]: getBip32PublicKeyBuilder,\n [getBip44EntropyBuilder.targetName]: getBip44EntropyBuilder,\n [getEntropyBuilder.targetName]: getEntropyBuilder,\n [invokeSnapBuilder.targetName]: invokeSnapBuilder,\n [manageStateBuilder.targetName]: manageStateBuilder,\n [notifyBuilder.targetName]: notifyBuilder,\n [manageAccountsBuilder.targetName]: manageAccountsBuilder,\n [getLocaleBuilder.targetName]: getLocaleBuilder,\n} as const;\n\nexport * from './caveats';\n"],"names":["WALLET_SNAP_PERMISSION_KEY","restrictedMethodPermissionBuilders","dialogBuilder","targetName","getBip32EntropyBuilder","getBip32PublicKeyBuilder","getBip44EntropyBuilder","getEntropyBuilder","invokeSnapBuilder","manageStateBuilder","notifyBuilder","manageAccountsBuilder","getLocaleBuilder"],"mappings":";;;;;;;;;;;IAqBSA,0BAA0B;eAA1BA,sCAA0B;;IAatBC,kCAAkC;eAAlCA;;;wBAjCiB;iCAES;mCAEE;iCAEF;4BAEL;2BAED;4BAEC;gCAEI;6BAEH;wBAEL;qBA4BhB;;;;;;;;;;;;;;AAbP,MAAMA,qCAAqC;IAChD,CAACC,qBAAa,CAACC,UAAU,CAAC,EAAED,qBAAa;IACzC,CAACE,uCAAsB,CAACD,UAAU,CAAC,EAAEC,uCAAsB;IAC3D,CAACC,2CAAwB,CAACF,UAAU,CAAC,EAAEE,2CAAwB;IAC/D,CAACC,uCAAsB,CAACH,UAAU,CAAC,EAAEG,uCAAsB;IAC3D,CAACC,6BAAiB,CAACJ,UAAU,CAAC,EAAEI,6BAAiB;IACjD,CAACC,6BAAiB,CAACL,UAAU,CAAC,EAAEK,6BAAiB;IACjD,CAACC,+BAAkB,CAACN,UAAU,CAAC,EAAEM,+BAAkB;IACnD,CAACC,qBAAa,CAACP,UAAU,CAAC,EAAEO,qBAAa;IACzC,CAACC,qCAAqB,CAACR,UAAU,CAAC,EAAEQ,qCAAqB;IACzD,CAACC,2BAAgB,CAACT,UAAU,CAAC,EAAES,2BAAgB;AACjD"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/restricted/invokeSnap.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n PermissionValidatorConstraint,\n PermissionSideEffect,\n} from '@metamask/permission-controller';\nimport { PermissionType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n Snap,\n SnapId,\n SnapRpcHookArgs,\n RequestedSnapPermissions,\n InstallSnapsResult,\n} from '@metamask/snaps-utils';\nimport { HandlerType, SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\n// Redeclare installSnaps action type to avoid circular dependencies\nexport type InstallSnaps = {\n type: `SnapController:install`;\n handler: (\n origin: string,\n requestedSnaps: RequestedSnapPermissions,\n ) => Promise<InstallSnapsResult>;\n};\n\nexport type GetPermittedSnaps = {\n type: `SnapController:getPermitted`;\n handler: (origin: string) => InstallSnapsResult;\n};\n\ntype AllowedActions = InstallSnaps | GetPermittedSnaps;\n\nexport type InvokeSnapMethodHooks = {\n getSnap: (snapId: SnapId) => Snap | undefined;\n handleSnapRpcRequest: ({\n snapId,\n origin,\n handler,\n request,\n }: SnapRpcHookArgs & { snapId: SnapId }) => Promise<unknown>;\n};\n\ntype InvokeSnapSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: InvokeSnapMethodHooks;\n};\n\ntype InvokeSnapSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof WALLET_SNAP_PERMISSION_KEY;\n methodImplementation: ReturnType<typeof getInvokeSnapImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n sideEffect: {\n onPermitted: PermissionSideEffect<AllowedActions, never>['onPermitted'];\n };\n}>;\n\nexport type InvokeSnapParams = {\n snapId: string;\n request: Record<string, unknown>;\n};\n\n/**\n * The side-effect method to handle the snap install.\n *\n * @param params - The side-effect params.\n * @param params.requestData - The request data associated to the requested permission.\n * @param params.messagingSystem - The messenger to call an action.\n */\nexport const handleSnapInstall: PermissionSideEffect<\n AllowedActions,\n never\n>['onPermitted'] = async ({ requestData, messagingSystem }) => {\n const snaps = requestData.permissions[WALLET_SNAP_PERMISSION_KEY].caveats?.[0]\n .value as RequestedSnapPermissions;\n\n const permittedSnaps = messagingSystem.call(\n `SnapController:getPermitted`,\n requestData.metadata.origin,\n );\n\n const dedupedSnaps = Object.keys(snaps).reduce<RequestedSnapPermissions>(\n (filteredSnaps, snap) => {\n if (!permittedSnaps[snap]) {\n filteredSnaps[snap] = snaps[snap];\n }\n return filteredSnaps;\n },\n {},\n );\n\n return messagingSystem.call(\n `SnapController:install`,\n requestData.metadata.origin,\n dedupedSnaps,\n );\n};\n/**\n * The specification builder for the `wallet_snap_*` permission.\n *\n * `wallet_snap_*` attempts to invoke an RPC method of the specified Snap.\n *\n * Requesting its corresponding permission will attempt to connect to the Snap,\n * and install it if it's not available yet.\n *\n * @param options - The specification builder options.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `wallet_snap_*` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n InvokeSnapSpecificationBuilderOptions,\n InvokeSnapSpecification\n> = ({ methodHooks }: InvokeSnapSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: WALLET_SNAP_PERMISSION_KEY,\n allowedCaveats: [SnapCaveatType.SnapIds],\n methodImplementation: getInvokeSnapImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (caveats?.length !== 1 || caveats[0].type !== SnapCaveatType.SnapIds) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.SnapIds}\" caveat.`,\n });\n }\n },\n sideEffect: {\n onPermitted: handleSnapInstall,\n },\n };\n};\n\nconst methodHooks: MethodHooksObject<InvokeSnapMethodHooks> = {\n getSnap: true,\n handleSnapRpcRequest: true,\n};\n\nexport const invokeSnapBuilder = Object.freeze({\n targetName: WALLET_SNAP_PERMISSION_KEY,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `wallet_snap_*`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnap - A function that retrieves all information stored about a snap.\n * @param hooks.handleSnapRpcRequest - A function that sends an RPC request to a snap's RPC handler or throws if that fails.\n * @returns The method implementation which returns the result of `handleSnapRpcRequest`.\n * @throws If the params are invalid.\n */\nexport function getInvokeSnapImplementation({\n getSnap,\n handleSnapRpcRequest,\n}: InvokeSnapMethodHooks) {\n return async function invokeSnap(\n options: RestrictedMethodOptions<Record<string, Json>>,\n ): Promise<Json> {\n const { params = {}, context } = options;\n\n const { snapId, request } = params as InvokeSnapParams;\n\n if (!getSnap(snapId)) {\n throw rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not installed. Please install it first, before invoking the snap.`,\n });\n }\n\n const { origin } = context;\n\n return (await handleSnapRpcRequest({\n snapId,\n origin,\n request,\n handler: HandlerType.OnRpcRequest,\n })) as Json;\n };\n}\n"],"names":["WALLET_SNAP_PERMISSION_KEY","handleSnapInstall","invokeSnapBuilder","getInvokeSnapImplementation","requestData","messagingSystem","snaps","permissions","caveats","value","permittedSnaps","call","metadata","origin","dedupedSnaps","Object","keys","reduce","filteredSnaps","snap","specificationBuilder","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","allowedCaveats","SnapCaveatType","SnapIds","methodImplementation","validator","length","type","rpcErrors","invalidParams","message","sideEffect","onPermitted","getSnap","handleSnapRpcRequest","freeze","invokeSnap","options","params","context","snapId","request","invalidRequest","handler","HandlerType","OnRpcRequest"],"mappings":";;;;;;;;;;;IAqBaA,0BAA0B;eAA1BA;;IAwDAC,iBAAiB;eAAjBA;;IAoEAC,iBAAiB;eAAjBA;;IAeGC,2BAA2B;eAA3BA;;;sCAzJe;2BACL;4BAQkB;AAKrC,MAAMH,6BAA6B;AAwDnC,MAAMC,oBAGM,OAAO,EAAEG,WAAW,EAAEC,eAAe,EAAE;IACxD,MAAMC,QAAQF,YAAYG,WAAW,CAACP,2BAA2B,CAACQ,OAAO,EAAE,CAAC,EAAE,CAC3EC;IAEH,MAAMC,iBAAiBL,gBAAgBM,IAAI,CACzC,CAAC,2BAA2B,CAAC,EAC7BP,YAAYQ,QAAQ,CAACC,MAAM;IAG7B,MAAMC,eAAeC,OAAOC,IAAI,CAACV,OAAOW,MAAM,CAC5C,CAACC,eAAeC;QACd,IAAI,CAACT,cAAc,CAACS,KAAK,EAAE;YACzBD,aAAa,CAACC,KAAK,GAAGb,KAAK,CAACa,KAAK;QACnC;QACA,OAAOD;IACT,GACA,CAAC;IAGH,OAAOb,gBAAgBM,IAAI,CACzB,CAAC,sBAAsB,CAAC,EACxBP,YAAYQ,QAAQ,CAACC,MAAM,EAC3BC;AAEJ;AACA;;;;;;;;;;;CAWC,GACD,MAAMM,uBAIF,CAAC,EAAEC,WAAW,EAAyC;IACzD,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,gBAAgB;QAC/CC,YAAYzB;QACZ0B,gBAAgB;YAACC,0BAAc,CAACC,OAAO;SAAC;QACxCC,sBAAsB1B,4BAA4BkB;QAClDS,WAAW,CAAC,EAAEtB,OAAO,EAAE;YACrB,IAAIA,SAASuB,WAAW,KAAKvB,OAAO,CAAC,EAAE,CAACwB,IAAI,KAAKL,0BAAc,CAACC,OAAO,EAAE;gBACvE,MAAMK,oBAAS,CAACC,aAAa,CAAC;oBAC5BC,SAAS,CAAC,mBAAmB,EAAER,0BAAc,CAACC,OAAO,CAAC,SAAS,CAAC;gBAClE;YACF;QACF;QACAQ,YAAY;YACVC,aAAapC;QACf;IACF;AACF;AAEA,MAAMoB,cAAwD;IAC5DiB,SAAS;IACTC,sBAAsB;AACxB;AAEO,MAAMrC,oBAAoBa,OAAOyB,MAAM,CAAC;IAC7Cf,YAAYzB;IACZoB;IACAC;AACF;AAWO,SAASlB,4BAA4B,EAC1CmC,OAAO,EACPC,oBAAoB,EACE;IACtB,OAAO,eAAeE,WACpBC,OAAsD;QAEtD,MAAM,EAAEC,SAAS,CAAC,CAAC,EAAEC,OAAO,EAAE,GAAGF;QAEjC,MAAM,EAAEG,MAAM,EAAEC,OAAO,EAAE,GAAGH;QAE5B,IAAI,CAACL,QAAQO,SAAS;YACpB,MAAMZ,oBAAS,CAACc,cAAc,CAAC;gBAC7BZ,SAAS,CAAC,UAAU,EAAEU,OAAO,sEAAsE,CAAC;YACtG;QACF;QAEA,MAAM,EAAEhC,MAAM,EAAE,GAAG+B;QAEnB,OAAQ,MAAML,qBAAqB;YACjCM;YACAhC;YACAiC;YACAE,SAASC,uBAAW,CAACC,YAAY;QACnC;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/restricted/invokeSnap.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n PermissionValidatorConstraint,\n PermissionSideEffect,\n} from '@metamask/permission-controller';\nimport { PermissionType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n InvokeSnapResult,\n RequestSnapsParams,\n RequestSnapsResult,\n} from '@metamask/snaps-sdk';\nimport type { Snap, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { HandlerType, SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\n// Redeclare installSnaps action type to avoid circular dependencies\nexport type InstallSnaps = {\n type: `SnapController:install`;\n handler: (\n origin: string,\n requestedSnaps: RequestSnapsParams,\n ) => Promise<RequestSnapsResult>;\n};\n\nexport type GetPermittedSnaps = {\n type: `SnapController:getPermitted`;\n handler: (origin: string) => RequestSnapsResult;\n};\n\ntype AllowedActions = InstallSnaps | GetPermittedSnaps;\n\nexport type InvokeSnapMethodHooks = {\n getSnap: (snapId: string) => Snap | undefined;\n handleSnapRpcRequest: ({\n snapId,\n origin,\n handler,\n request,\n }: SnapRpcHookArgs & { snapId: string }) => Promise<unknown>;\n};\n\ntype InvokeSnapSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: InvokeSnapMethodHooks;\n};\n\ntype InvokeSnapSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof WALLET_SNAP_PERMISSION_KEY;\n methodImplementation: ReturnType<typeof getInvokeSnapImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n sideEffect: {\n onPermitted: PermissionSideEffect<AllowedActions, never>['onPermitted'];\n };\n}>;\n\nexport type InvokeSnapParams = {\n snapId: string;\n request: Record<string, Json>;\n};\n\n/**\n * The side-effect method to handle the snap install.\n *\n * @param params - The side-effect params.\n * @param params.requestData - The request data associated to the requested permission.\n * @param params.messagingSystem - The messenger to call an action.\n */\nexport const handleSnapInstall: PermissionSideEffect<\n AllowedActions,\n never\n>['onPermitted'] = async ({ requestData, messagingSystem }) => {\n const snaps = requestData.permissions[WALLET_SNAP_PERMISSION_KEY].caveats?.[0]\n .value as RequestSnapsParams;\n\n const permittedSnaps = messagingSystem.call(\n `SnapController:getPermitted`,\n requestData.metadata.origin,\n );\n\n const dedupedSnaps = Object.keys(snaps).reduce<RequestSnapsParams>(\n (filteredSnaps, snap) => {\n if (!permittedSnaps[snap]) {\n filteredSnaps[snap] = snaps[snap];\n }\n return filteredSnaps;\n },\n {},\n );\n\n return messagingSystem.call(\n `SnapController:install`,\n requestData.metadata.origin,\n dedupedSnaps,\n );\n};\n/**\n * The specification builder for the `wallet_snap_*` permission.\n *\n * `wallet_snap_*` attempts to invoke an RPC method of the specified Snap.\n *\n * Requesting its corresponding permission will attempt to connect to the Snap,\n * and install it if it's not available yet.\n *\n * @param options - The specification builder options.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `wallet_snap_*` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n InvokeSnapSpecificationBuilderOptions,\n InvokeSnapSpecification\n> = ({ methodHooks }: InvokeSnapSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: WALLET_SNAP_PERMISSION_KEY,\n allowedCaveats: [SnapCaveatType.SnapIds],\n methodImplementation: getInvokeSnapImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (caveats?.length !== 1 || caveats[0].type !== SnapCaveatType.SnapIds) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.SnapIds}\" caveat.`,\n });\n }\n },\n sideEffect: {\n onPermitted: handleSnapInstall,\n },\n };\n};\n\nconst methodHooks: MethodHooksObject<InvokeSnapMethodHooks> = {\n getSnap: true,\n handleSnapRpcRequest: true,\n};\n\nexport const invokeSnapBuilder = Object.freeze({\n targetName: WALLET_SNAP_PERMISSION_KEY,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `wallet_snap_*`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnap - A function that retrieves all information stored about a snap.\n * @param hooks.handleSnapRpcRequest - A function that sends an RPC request to a snap's RPC handler or throws if that fails.\n * @returns The method implementation which returns the result of `handleSnapRpcRequest`.\n * @throws If the params are invalid.\n */\nexport function getInvokeSnapImplementation({\n getSnap,\n handleSnapRpcRequest,\n}: InvokeSnapMethodHooks) {\n return async function invokeSnap(\n options: RestrictedMethodOptions<InvokeSnapParams>,\n ): Promise<InvokeSnapResult> {\n const { params = {}, context } = options;\n\n const { snapId, request } = params as InvokeSnapParams;\n\n if (!getSnap(snapId)) {\n throw rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not installed. Please install it first, before invoking the snap.`,\n });\n }\n\n const { origin } = context;\n\n return (await handleSnapRpcRequest({\n snapId,\n origin,\n request,\n handler: HandlerType.OnRpcRequest,\n })) as Json;\n };\n}\n"],"names":["WALLET_SNAP_PERMISSION_KEY","handleSnapInstall","invokeSnapBuilder","getInvokeSnapImplementation","requestData","messagingSystem","snaps","permissions","caveats","value","permittedSnaps","call","metadata","origin","dedupedSnaps","Object","keys","reduce","filteredSnaps","snap","specificationBuilder","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","allowedCaveats","SnapCaveatType","SnapIds","methodImplementation","validator","length","type","rpcErrors","invalidParams","message","sideEffect","onPermitted","getSnap","handleSnapRpcRequest","freeze","invokeSnap","options","params","context","snapId","request","invalidRequest","handler","HandlerType","OnRpcRequest"],"mappings":";;;;;;;;;;;IAoBaA,0BAA0B;eAA1BA;;IAwDAC,iBAAiB;eAAjBA;;IAoEAC,iBAAiB;eAAjBA;;IAeGC,2BAA2B;eAA3BA;;;sCAxJe;2BACL;4BAOkB;AAKrC,MAAMH,6BAA6B;AAwDnC,MAAMC,oBAGM,OAAO,EAAEG,WAAW,EAAEC,eAAe,EAAE;IACxD,MAAMC,QAAQF,YAAYG,WAAW,CAACP,2BAA2B,CAACQ,OAAO,EAAE,CAAC,EAAE,CAC3EC;IAEH,MAAMC,iBAAiBL,gBAAgBM,IAAI,CACzC,CAAC,2BAA2B,CAAC,EAC7BP,YAAYQ,QAAQ,CAACC,MAAM;IAG7B,MAAMC,eAAeC,OAAOC,IAAI,CAACV,OAAOW,MAAM,CAC5C,CAACC,eAAeC;QACd,IAAI,CAACT,cAAc,CAACS,KAAK,EAAE;YACzBD,aAAa,CAACC,KAAK,GAAGb,KAAK,CAACa,KAAK;QACnC;QACA,OAAOD;IACT,GACA,CAAC;IAGH,OAAOb,gBAAgBM,IAAI,CACzB,CAAC,sBAAsB,CAAC,EACxBP,YAAYQ,QAAQ,CAACC,MAAM,EAC3BC;AAEJ;AACA;;;;;;;;;;;CAWC,GACD,MAAMM,uBAIF,CAAC,EAAEC,WAAW,EAAyC;IACzD,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,gBAAgB;QAC/CC,YAAYzB;QACZ0B,gBAAgB;YAACC,0BAAc,CAACC,OAAO;SAAC;QACxCC,sBAAsB1B,4BAA4BkB;QAClDS,WAAW,CAAC,EAAEtB,OAAO,EAAE;YACrB,IAAIA,SAASuB,WAAW,KAAKvB,OAAO,CAAC,EAAE,CAACwB,IAAI,KAAKL,0BAAc,CAACC,OAAO,EAAE;gBACvE,MAAMK,oBAAS,CAACC,aAAa,CAAC;oBAC5BC,SAAS,CAAC,mBAAmB,EAAER,0BAAc,CAACC,OAAO,CAAC,SAAS,CAAC;gBAClE;YACF;QACF;QACAQ,YAAY;YACVC,aAAapC;QACf;IACF;AACF;AAEA,MAAMoB,cAAwD;IAC5DiB,SAAS;IACTC,sBAAsB;AACxB;AAEO,MAAMrC,oBAAoBa,OAAOyB,MAAM,CAAC;IAC7Cf,YAAYzB;IACZoB;IACAC;AACF;AAWO,SAASlB,4BAA4B,EAC1CmC,OAAO,EACPC,oBAAoB,EACE;IACtB,OAAO,eAAeE,WACpBC,OAAkD;QAElD,MAAM,EAAEC,SAAS,CAAC,CAAC,EAAEC,OAAO,EAAE,GAAGF;QAEjC,MAAM,EAAEG,MAAM,EAAEC,OAAO,EAAE,GAAGH;QAE5B,IAAI,CAACL,QAAQO,SAAS;YACpB,MAAMZ,oBAAS,CAACc,cAAc,CAAC;gBAC7BZ,SAAS,CAAC,UAAU,EAAEU,OAAO,sEAAsE,CAAC;YACtG;QACF;QAEA,MAAM,EAAEhC,MAAM,EAAE,GAAG+B;QAEnB,OAAQ,MAAML,qBAAqB;YACjCM;YACAhC;YACAiC;YACAE,SAASC,uBAAW,CAACC,YAAY;QACnC;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/restricted/manageAccounts.ts"],"sourcesContent":["import type {\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n PermissionSpecificationBuilder,\n} from '@metamask/permission-controller';\nimport { SubjectType, PermissionType } from '@metamask/permission-controller';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { JsonStruct } from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { assert, string, object, union, array, record } from 'superstruct';\n\nconst SnapMessageStruct = union([\n object({\n method: string(),\n }),\n object({\n method: string(),\n params: union([array(JsonStruct), record(string(), JsonStruct)]),\n }),\n]);\n\ntype Message = Infer<typeof SnapMessageStruct>;\n\nexport const methodName = 'snap_manageAccounts';\n\nexport type ManageAccountsMethodHooks = {\n /**\n * Gets the snap keyring implementation.\n */\n getSnapKeyring: (snapOrigin: string) => Promise<{\n handleKeyringSnapMessage: (\n snapId: string,\n message: Message,\n ) => Promise<Json>;\n }>;\n};\n\ntype ManageAccountsSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageAccountsMethodHooks;\n};\n\ntype ManageAccountsSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof manageAccountsImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageAccounts` permission.\n * `snap_manageAccounts` lets the Snap manage a set of accounts via a custom keyring.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageAccounts` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageAccountsSpecificationBuilderOptions,\n ManageAccountsSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageAccountsSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: manageAccountsImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\n/**\n * Builds the method implementation for `snap_manageAccounts`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnapKeyring - A function to get the snap keyring.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function manageAccountsImplementation({\n getSnapKeyring,\n}: ManageAccountsMethodHooks) {\n return async function manageAccounts(\n options: RestrictedMethodOptions<Message>,\n ): Promise<Json> {\n const {\n context: { origin },\n params,\n } = options;\n\n assert(params, SnapMessageStruct);\n const keyring = await getSnapKeyring(origin);\n return await keyring.handleKeyringSnapMessage(origin, params);\n };\n}\n\nexport const manageAccountsBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks: {\n getSnapKeyring: true,\n },\n} as const);\n"],"names":["methodName","specificationBuilder","manageAccountsImplementation","manageAccountsBuilder","SnapMessageStruct","union","object","method","string","params","array","JsonStruct","record","allowedCaveats","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","methodImplementation","subjectTypes","SubjectType","Snap","getSnapKeyring","manageAccounts","options","context","origin","assert","keyring","handleKeyringSnapMessage","Object","freeze"],"mappings":";;;;;;;;;;;IAuBaA,UAAU;eAAVA;;IAmCAC,oBAAoB;eAApBA;;IA0BGC,4BAA4B;eAA5BA;;IAiBHC,qBAAqB;eAArBA;;;sCAhG+B;uBAEjB;6BAEkC;AAE7D,MAAMC,oBAAoBC,IAAAA,kBAAK,EAAC;IAC9BC,IAAAA,mBAAM,EAAC;QACLC,QAAQC,IAAAA,mBAAM;IAChB;IACAF,IAAAA,mBAAM,EAAC;QACLC,QAAQC,IAAAA,mBAAM;QACdC,QAAQJ,IAAAA,kBAAK,EAAC;YAACK,IAAAA,kBAAK,EAACC,iBAAU;YAAGC,IAAAA,mBAAM,EAACJ,IAAAA,mBAAM,KAAIG,iBAAU;SAAE;IACjE;CACD;AAIM,MAAMX,aAAa;AAmCnB,MAAMC,uBAIT,CAAC,EACHY,iBAAiB,IAAI,EACrBC,WAAW,EAC+B;IAC1C,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,gBAAgB;QAC/CC,YAAYlB;QACZa;QACAM,sBAAsBjB,6BAA6BY;QACnDM,cAAc;YAACC,iCAAW,CAACC,IAAI;SAAC;IAClC;AACF;AAWO,SAASpB,6BAA6B,EAC3CqB,cAAc,EACY;IAC1B,OAAO,eAAeC,eACpBC,OAAyC;QAEzC,MAAM,EACJC,SAAS,EAAEC,MAAM,EAAE,EACnBlB,MAAM,EACP,GAAGgB;QAEJG,IAAAA,mBAAM,EAACnB,QAAQL;QACf,MAAMyB,UAAU,MAAMN,eAAeI;QACrC,OAAO,MAAME,QAAQC,wBAAwB,CAACH,QAAQlB;IACxD;AACF;AAEO,MAAMN,wBAAwB4B,OAAOC,MAAM,CAAC;IACjDd,YAAYlB;IACZC;IACAa,aAAa;QACXS,gBAAgB;IAClB;AACF"}
1
+ {"version":3,"sources":["../../../src/restricted/manageAccounts.ts"],"sourcesContent":["import type {\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n PermissionSpecificationBuilder,\n} from '@metamask/permission-controller';\nimport { SubjectType, PermissionType } from '@metamask/permission-controller';\nimport type {\n ManageAccountsParams,\n ManageAccountsResult,\n} from '@metamask/snaps-sdk';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { JsonStruct } from '@metamask/utils';\nimport { assert, string, object, union, array, record } from 'superstruct';\n\nconst SnapMessageStruct = union([\n object({\n method: string(),\n }),\n object({\n method: string(),\n params: union([array(JsonStruct), record(string(), JsonStruct)]),\n }),\n]);\n\ntype Message = InferMatching<typeof SnapMessageStruct, ManageAccountsParams>;\n\nexport const methodName = 'snap_manageAccounts';\n\nexport type ManageAccountsMethodHooks = {\n /**\n * Gets the snap keyring implementation.\n */\n getSnapKeyring: (snapOrigin: string) => Promise<{\n handleKeyringSnapMessage: (\n snapId: string,\n message: Message,\n ) => Promise<Json>;\n }>;\n};\n\ntype ManageAccountsSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageAccountsMethodHooks;\n};\n\ntype ManageAccountsSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof manageAccountsImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageAccounts` permission.\n * `snap_manageAccounts` lets the Snap manage a set of accounts via a custom keyring.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageAccounts` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageAccountsSpecificationBuilderOptions,\n ManageAccountsSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageAccountsSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: manageAccountsImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\n/**\n * Builds the method implementation for `snap_manageAccounts`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnapKeyring - A function to get the snap keyring.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function manageAccountsImplementation({\n getSnapKeyring,\n}: ManageAccountsMethodHooks) {\n return async function manageAccounts(\n options: RestrictedMethodOptions<ManageAccountsParams>,\n ): Promise<ManageAccountsResult> {\n const {\n context: { origin },\n params,\n } = options;\n\n assert(params, SnapMessageStruct);\n const keyring = await getSnapKeyring(origin);\n return await keyring.handleKeyringSnapMessage(origin, params);\n };\n}\n\nexport const manageAccountsBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks: {\n getSnapKeyring: true,\n },\n} as const);\n"],"names":["methodName","specificationBuilder","manageAccountsImplementation","manageAccountsBuilder","SnapMessageStruct","union","object","method","string","params","array","JsonStruct","record","allowedCaveats","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","methodImplementation","subjectTypes","SubjectType","Snap","getSnapKeyring","manageAccounts","options","context","origin","assert","keyring","handleKeyringSnapMessage","Object","freeze"],"mappings":";;;;;;;;;;;IA2BaA,UAAU;eAAVA;;IAmCAC,oBAAoB;eAApBA;;IA0BGC,4BAA4B;eAA5BA;;IAiBHC,qBAAqB;eAArBA;;;sCApG+B;uBAOjB;6BACkC;AAE7D,MAAMC,oBAAoBC,IAAAA,kBAAK,EAAC;IAC9BC,IAAAA,mBAAM,EAAC;QACLC,QAAQC,IAAAA,mBAAM;IAChB;IACAF,IAAAA,mBAAM,EAAC;QACLC,QAAQC,IAAAA,mBAAM;QACdC,QAAQJ,IAAAA,kBAAK,EAAC;YAACK,IAAAA,kBAAK,EAACC,iBAAU;YAAGC,IAAAA,mBAAM,EAACJ,IAAAA,mBAAM,KAAIG,iBAAU;SAAE;IACjE;CACD;AAIM,MAAMX,aAAa;AAmCnB,MAAMC,uBAIT,CAAC,EACHY,iBAAiB,IAAI,EACrBC,WAAW,EAC+B;IAC1C,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,gBAAgB;QAC/CC,YAAYlB;QACZa;QACAM,sBAAsBjB,6BAA6BY;QACnDM,cAAc;YAACC,iCAAW,CAACC,IAAI;SAAC;IAClC;AACF;AAWO,SAASpB,6BAA6B,EAC3CqB,cAAc,EACY;IAC1B,OAAO,eAAeC,eACpBC,OAAsD;QAEtD,MAAM,EACJC,SAAS,EAAEC,MAAM,EAAE,EACnBlB,MAAM,EACP,GAAGgB;QAEJG,IAAAA,mBAAM,EAACnB,QAAQL;QACf,MAAMyB,UAAU,MAAMN,eAAeI;QACrC,OAAO,MAAME,QAAQC,wBAAwB,CAACH,QAAQlB;IACxD;AACF;AAEO,MAAMN,wBAAwB4B,OAAOC,MAAM,CAAC;IACjDd,YAAYlB;IACZC;IACAa,aAAa;QACXS,gBAAgB;IAClB;AACF"}
@@ -9,9 +9,6 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
- ManageStateOperation: function() {
13
- return ManageStateOperation;
14
- },
15
12
  STATE_ENCRYPTION_SALT: function() {
16
13
  return STATE_ENCRYPTION_SALT;
17
14
  },
@@ -33,6 +30,7 @@ _export(exports, {
33
30
  });
34
31
  const _permissioncontroller = require("@metamask/permission-controller");
35
32
  const _rpcerrors = require("@metamask/rpc-errors");
33
+ const _snapssdk = require("@metamask/snaps-sdk");
36
34
  const _snapsutils = require("@metamask/snaps-utils");
37
35
  const _utils = require("@metamask/utils");
38
36
  const _utils1 = require("../utils");
@@ -63,12 +61,6 @@ const manageStateBuilder = Object.freeze({
63
61
  specificationBuilder,
64
62
  methodHooks
65
63
  });
66
- var ManageStateOperation;
67
- (function(ManageStateOperation) {
68
- ManageStateOperation["ClearState"] = 'clear';
69
- ManageStateOperation["GetState"] = 'get';
70
- ManageStateOperation["UpdateState"] = 'update';
71
- })(ManageStateOperation || (ManageStateOperation = {}));
72
64
  const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)
73
65
  /**
74
66
  * Get a deterministic encryption key to use for encrypting and decrypting the
@@ -131,40 +123,44 @@ const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)
131
123
  function getManageStateImplementation({ getMnemonic, getUnlockPromise, clearSnapState, getSnapState, updateSnapState, encrypt, decrypt }) {
132
124
  return async function manageState(options) {
133
125
  const { params = {}, method, context: { origin } } = options;
134
- const { operation, newState } = getValidatedParams(params, method);
135
- await getUnlockPromise(true);
136
- const mnemonicPhrase = await getMnemonic();
137
- switch(operation){
138
- case ManageStateOperation.ClearState:
139
- await clearSnapState(origin);
126
+ const validatedParams = getValidatedParams(params, method);
127
+ // If the encrypted param is undefined or null we default to true.
128
+ const shouldEncrypt = validatedParams.encrypted ?? true;
129
+ // We only need to prompt the user when the mnemonic is needed
130
+ // which it isn't for the clear operation or unencrypted storage.
131
+ if (shouldEncrypt && validatedParams.operation !== _snapssdk.ManageStateOperation.ClearState) {
132
+ await getUnlockPromise(true);
133
+ }
134
+ switch(validatedParams.operation){
135
+ case _snapssdk.ManageStateOperation.ClearState:
136
+ clearSnapState(origin, shouldEncrypt);
140
137
  return null;
141
- case ManageStateOperation.GetState:
138
+ case _snapssdk.ManageStateOperation.GetState:
142
139
  {
143
- const state = await getSnapState(origin);
140
+ const state = getSnapState(origin, shouldEncrypt);
144
141
  if (state === null) {
145
142
  return state;
146
143
  }
147
- return await decryptState({
144
+ return shouldEncrypt ? await decryptState({
148
145
  state,
149
146
  decryptFunction: decrypt,
150
- mnemonicPhrase,
147
+ mnemonicPhrase: await getMnemonic(),
151
148
  snapId: origin
152
- });
149
+ }) : (0, _snapsutils.parseJson)(state);
153
150
  }
154
- case ManageStateOperation.UpdateState:
151
+ case _snapssdk.ManageStateOperation.UpdateState:
155
152
  {
156
- (0, _utils.assert)(newState);
157
- const encryptedState = await encryptState({
158
- state: newState,
153
+ const finalizedState = shouldEncrypt ? await encryptState({
154
+ state: validatedParams.newState,
159
155
  encryptFunction: encrypt,
160
- mnemonicPhrase,
156
+ mnemonicPhrase: await getMnemonic(),
161
157
  snapId: origin
162
- });
163
- await updateSnapState(origin, encryptedState);
158
+ }) : JSON.stringify(validatedParams.newState);
159
+ updateSnapState(origin, finalizedState, shouldEncrypt);
164
160
  return null;
165
161
  }
166
162
  default:
167
- throw _rpcerrors.rpcErrors.invalidParams(`Invalid ${method} operation: "${operation}"`);
163
+ throw _rpcerrors.rpcErrors.invalidParams(`Invalid ${method} operation: "${validatedParams.operation}"`);
168
164
  }
169
165
  };
170
166
  }
@@ -174,13 +170,18 @@ function getValidatedParams(params, method, storageSizeLimit = STORAGE_SIZE_LIMI
174
170
  message: 'Expected params to be a single object.'
175
171
  });
176
172
  }
177
- const { operation, newState } = params;
178
- if (!operation || typeof operation !== 'string' || !Object.values(ManageStateOperation).includes(operation)) {
173
+ const { operation, newState, encrypted } = params;
174
+ if (!operation || typeof operation !== 'string' || !Object.values(_snapssdk.ManageStateOperation).includes(operation)) {
179
175
  throw _rpcerrors.rpcErrors.invalidParams({
180
176
  message: 'Must specify a valid manage state "operation".'
181
177
  });
182
178
  }
183
- if (operation === ManageStateOperation.UpdateState) {
179
+ if (encrypted !== undefined && typeof encrypted !== 'boolean') {
180
+ throw _rpcerrors.rpcErrors.invalidParams({
181
+ message: '"encrypted" parameter must be a boolean if specified.'
182
+ });
183
+ }
184
+ if (operation === _snapssdk.ManageStateOperation.UpdateState) {
184
185
  if (!(0, _utils.isObject)(newState)) {
185
186
  throw _rpcerrors.rpcErrors.invalidParams({
186
187
  message: `Invalid ${method} "updateState" parameter: The new state must be a plain object.`,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/restricted/manageState.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { EnumToUnion } from '@metamask/snaps-utils';\nimport { STATE_ENCRYPTION_MAGIC_VALUE } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray, Hex } from '@metamask/utils';\nimport { isObject, getJsonSize, assert, isValidJson } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropy } from '../utils';\n\n// The salt used for SIP-6-based entropy derivation.\nexport const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';\n\nconst methodName = 'snap_manageState';\n\nexport type ManageStateMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n /**\n * A function that clears the state of the requesting Snap.\n */\n clearSnapState: (snapId: string) => Promise<void>;\n\n /**\n * A function that gets the encrypted state of the requesting Snap.\n *\n * @returns The current state of the Snap.\n */\n getSnapState: (snapId: string) => Promise<string>;\n\n /**\n * A function that updates the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n */\n updateSnapState: (snapId: string, newState: string) => Promise<void>;\n\n /**\n * Encrypts data with a key. This is assumed to perform symmetric encryption.\n *\n * @param key - The key to use for encryption, in hexadecimal format.\n * @param data - The JSON data to encrypt.\n * @returns The ciphertext as a string. The format for this string is\n * dependent on the implementation, but MUST be a string.\n */\n encrypt: (key: string, data: Json) => Promise<string>;\n\n /**\n * Decrypts data with a key. This is assumed to perform symmetric decryption.\n *\n * @param key - The key to use for decryption, in hexadecimal format.\n * @param cipherText - The ciphertext to decrypt. The format for this string\n * is dependent on the implementation, but MUST be a string.\n * @returns The decrypted data as a JSON object.\n */\n decrypt: (key: Hex, cipherText: string) => Promise<unknown>;\n};\n\ntype ManageStateSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageStateMethodHooks;\n};\n\ntype ManageStateSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getManageStateImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageState` permission.\n * `snap_manageState` lets the Snap store and manage some of its state on\n * your device.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageState` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageStateSpecificationBuilderOptions,\n ManageStateSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageStateSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getManageStateImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<ManageStateMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n encrypt: true,\n decrypt: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport enum ManageStateOperation {\n ClearState = 'clear',\n GetState = 'get',\n UpdateState = 'update',\n}\n\nexport type ManageStateArgs = {\n operation: EnumToUnion<ManageStateOperation>;\n newState?: Record<string, Json>;\n};\n\nexport const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n mnemonicPhrase: Uint8Array;\n};\n\n/**\n * Get a deterministic encryption key to use for encrypting and decrypting the\n * state.\n *\n * This key should only be used for state encryption using `snap_manageState`.\n * To get other encryption keys, a different salt can be used.\n *\n * @param args - The encryption key args.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The state encryption key.\n */\nasync function getEncryptionKey({\n mnemonicPhrase,\n snapId,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropy({\n mnemonicPhrase,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n });\n}\n\ntype EncryptStateArgs = GetEncryptionKeyArgs & {\n state: Json;\n encryptFunction: ManageStateMethodHooks['encrypt'];\n};\n\n/**\n * Encrypt the state using a deterministic encryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to encrypt.\n * @param args.encryptFunction - The function to use for encrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function encryptState({\n state,\n encryptFunction,\n ...keyArgs\n}: EncryptStateArgs) {\n const encryptionKey = await getEncryptionKey(keyArgs);\n return await encryptFunction(encryptionKey, state);\n}\n\ntype DecryptStateArgs = GetEncryptionKeyArgs & {\n state: string;\n decryptFunction: ManageStateMethodHooks['decrypt'];\n};\n\n/**\n * Decrypt the state using a deterministic decryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to decrypt.\n * @param args.decryptFunction - The function to use for decrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function decryptState({\n state,\n decryptFunction,\n ...keyArgs\n}: DecryptStateArgs) {\n try {\n const encryptionKey = await getEncryptionKey(keyArgs);\n const decryptedState = await decryptFunction(encryptionKey, state);\n\n assert(isValidJson(decryptedState));\n\n return decryptedState as Record<string, Json>;\n } catch {\n throw rpcErrors.internal({\n message: 'Failed to decrypt snap state, the state must be corrupted.',\n });\n }\n}\n\n/**\n * Builds the method implementation for `snap_manageState`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.clearSnapState - A function that clears the state stored for a\n * snap.\n * @param hooks.getSnapState - A function that fetches the persisted decrypted\n * state for a snap.\n * @param hooks.updateSnapState - A function that updates the state stored for a\n * snap.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase\n * of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @param hooks.encrypt - A function that encrypts the given state.\n * @param hooks.decrypt - A function that decrypts the given state.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function getManageStateImplementation({\n getMnemonic,\n getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n encrypt,\n decrypt,\n}: ManageStateMethodHooks) {\n return async function manageState(\n options: RestrictedMethodOptions<ManageStateArgs>,\n ): Promise<null | Record<string, Json>> {\n const {\n params = {},\n method,\n context: { origin },\n } = options;\n const { operation, newState } = getValidatedParams(params, method);\n\n await getUnlockPromise(true);\n const mnemonicPhrase = await getMnemonic();\n\n switch (operation) {\n case ManageStateOperation.ClearState:\n await clearSnapState(origin);\n return null;\n\n case ManageStateOperation.GetState: {\n const state = await getSnapState(origin);\n if (state === null) {\n return state;\n }\n return await decryptState({\n state,\n decryptFunction: decrypt,\n mnemonicPhrase,\n snapId: origin,\n });\n }\n\n case ManageStateOperation.UpdateState: {\n assert(newState);\n\n const encryptedState = await encryptState({\n state: newState,\n encryptFunction: encrypt,\n mnemonicPhrase,\n snapId: origin,\n });\n\n await updateSnapState(origin, encryptedState);\n return null;\n }\n\n default:\n throw rpcErrors.invalidParams(\n `Invalid ${method} operation: \"${operation as string}\"`,\n );\n }\n };\n}\n\n/**\n * Validates the manageState method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @param method - RPC method name used for debugging errors.\n * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\n storageSizeLimit = STORAGE_SIZE_LIMIT,\n): ManageStateArgs {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { operation, newState } = params;\n\n if (\n !operation ||\n typeof operation !== 'string' ||\n !(Object.values(ManageStateOperation) as string[]).includes(operation)\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid manage state \"operation\".',\n });\n }\n\n if (operation === ManageStateOperation.UpdateState) {\n if (!isObject(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be a plain object.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n let size;\n try {\n // `getJsonSize` will throw if the state is not JSON serializable.\n size = getJsonSize(newState);\n } catch {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be JSON serializable.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n if (size > storageSizeLimit) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must not exceed ${storageSizeLimit} bytes in size.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n }\n\n return params as ManageStateArgs;\n}\n"],"names":["STATE_ENCRYPTION_SALT","specificationBuilder","manageStateBuilder","STORAGE_SIZE_LIMIT","getManageStateImplementation","getValidatedParams","methodName","allowedCaveats","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","methodImplementation","subjectTypes","SubjectType","Snap","getMnemonic","getUnlockPromise","clearSnapState","getSnapState","updateSnapState","encrypt","decrypt","Object","freeze","ManageStateOperation","ClearState","GetState","UpdateState","getEncryptionKey","mnemonicPhrase","snapId","deriveEntropy","input","salt","magic","STATE_ENCRYPTION_MAGIC_VALUE","encryptState","state","encryptFunction","keyArgs","encryptionKey","decryptState","decryptFunction","decryptedState","assert","isValidJson","rpcErrors","internal","message","manageState","options","params","method","context","origin","operation","newState","encryptedState","invalidParams","storageSizeLimit","isObject","values","includes","data","receivedNewState","size","getJsonSize"],"mappings":"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"}
1
+ {"version":3,"sources":["../../../src/restricted/manageState.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { ManageStateParams, ManageStateResult } from '@metamask/snaps-sdk';\nimport { ManageStateOperation } from '@metamask/snaps-sdk';\nimport { STATE_ENCRYPTION_MAGIC_VALUE, parseJson } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray, Hex } from '@metamask/utils';\nimport { isObject, getJsonSize, assert, isValidJson } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropy } from '../utils';\n\n// The salt used for SIP-6-based entropy derivation.\nexport const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';\n\nconst methodName = 'snap_manageState';\n\nexport type ManageStateMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n /**\n * A function that clears the state of the requesting Snap.\n */\n clearSnapState: (snapId: string, encrypted: boolean) => void;\n\n /**\n * A function that gets the encrypted state of the requesting Snap.\n *\n * @returns The current state of the Snap.\n */\n getSnapState: (snapId: string, encrypted: boolean) => string;\n\n /**\n * A function that updates the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n */\n updateSnapState: (\n snapId: string,\n newState: string,\n encrypted: boolean,\n ) => void;\n\n /**\n * Encrypts data with a key. This is assumed to perform symmetric encryption.\n *\n * @param key - The key to use for encryption, in hexadecimal format.\n * @param data - The JSON data to encrypt.\n * @returns The ciphertext as a string. The format for this string is\n * dependent on the implementation, but MUST be a string.\n */\n encrypt: (key: string, data: Json) => Promise<string>;\n\n /**\n * Decrypts data with a key. This is assumed to perform symmetric decryption.\n *\n * @param key - The key to use for decryption, in hexadecimal format.\n * @param cipherText - The ciphertext to decrypt. The format for this string\n * is dependent on the implementation, but MUST be a string.\n * @returns The decrypted data as a JSON object.\n */\n decrypt: (key: Hex, cipherText: string) => Promise<unknown>;\n};\n\ntype ManageStateSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageStateMethodHooks;\n};\n\ntype ManageStateSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getManageStateImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageState` permission.\n * `snap_manageState` lets the Snap store and manage some of its state on\n * your device.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageState` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageStateSpecificationBuilderOptions,\n ManageStateSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageStateSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getManageStateImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<ManageStateMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n encrypt: true,\n decrypt: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n mnemonicPhrase: Uint8Array;\n};\n\n/**\n * Get a deterministic encryption key to use for encrypting and decrypting the\n * state.\n *\n * This key should only be used for state encryption using `snap_manageState`.\n * To get other encryption keys, a different salt can be used.\n *\n * @param args - The encryption key args.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The state encryption key.\n */\nasync function getEncryptionKey({\n mnemonicPhrase,\n snapId,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropy({\n mnemonicPhrase,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n });\n}\n\ntype EncryptStateArgs = GetEncryptionKeyArgs & {\n state: Json;\n encryptFunction: ManageStateMethodHooks['encrypt'];\n};\n\n/**\n * Encrypt the state using a deterministic encryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to encrypt.\n * @param args.encryptFunction - The function to use for encrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function encryptState({\n state,\n encryptFunction,\n ...keyArgs\n}: EncryptStateArgs) {\n const encryptionKey = await getEncryptionKey(keyArgs);\n return await encryptFunction(encryptionKey, state);\n}\n\ntype DecryptStateArgs = GetEncryptionKeyArgs & {\n state: string;\n decryptFunction: ManageStateMethodHooks['decrypt'];\n};\n\n/**\n * Decrypt the state using a deterministic decryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to decrypt.\n * @param args.decryptFunction - The function to use for decrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function decryptState({\n state,\n decryptFunction,\n ...keyArgs\n}: DecryptStateArgs) {\n try {\n const encryptionKey = await getEncryptionKey(keyArgs);\n const decryptedState = await decryptFunction(encryptionKey, state);\n\n assert(isValidJson(decryptedState));\n\n return decryptedState as Record<string, Json>;\n } catch {\n throw rpcErrors.internal({\n message: 'Failed to decrypt snap state, the state must be corrupted.',\n });\n }\n}\n\n/**\n * Builds the method implementation for `snap_manageState`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.clearSnapState - A function that clears the state stored for a\n * snap.\n * @param hooks.getSnapState - A function that fetches the persisted decrypted\n * state for a snap.\n * @param hooks.updateSnapState - A function that updates the state stored for a\n * snap.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase\n * of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @param hooks.encrypt - A function that encrypts the given state.\n * @param hooks.decrypt - A function that decrypts the given state.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function getManageStateImplementation({\n getMnemonic,\n getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n encrypt,\n decrypt,\n}: ManageStateMethodHooks) {\n return async function manageState(\n options: RestrictedMethodOptions<ManageStateParams>,\n ): Promise<ManageStateResult> {\n const {\n params = {},\n method,\n context: { origin },\n } = options;\n const validatedParams = getValidatedParams(params, method);\n\n // If the encrypted param is undefined or null we default to true.\n const shouldEncrypt = validatedParams.encrypted ?? true;\n\n // We only need to prompt the user when the mnemonic is needed\n // which it isn't for the clear operation or unencrypted storage.\n if (\n shouldEncrypt &&\n validatedParams.operation !== ManageStateOperation.ClearState\n ) {\n await getUnlockPromise(true);\n }\n\n switch (validatedParams.operation) {\n case ManageStateOperation.ClearState:\n clearSnapState(origin, shouldEncrypt);\n return null;\n\n case ManageStateOperation.GetState: {\n const state = getSnapState(origin, shouldEncrypt);\n if (state === null) {\n return state;\n }\n return shouldEncrypt\n ? await decryptState({\n state,\n decryptFunction: decrypt,\n mnemonicPhrase: await getMnemonic(),\n snapId: origin,\n })\n : parseJson<Record<string, Json>>(state);\n }\n\n case ManageStateOperation.UpdateState: {\n const finalizedState = shouldEncrypt\n ? await encryptState({\n state: validatedParams.newState,\n encryptFunction: encrypt,\n mnemonicPhrase: await getMnemonic(),\n snapId: origin,\n })\n : JSON.stringify(validatedParams.newState);\n\n updateSnapState(origin, finalizedState, shouldEncrypt);\n return null;\n }\n\n default:\n throw rpcErrors.invalidParams(\n `Invalid ${method} operation: \"${\n validatedParams.operation as string\n }\"`,\n );\n }\n };\n}\n\n/**\n * Validates the manageState method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @param method - RPC method name used for debugging errors.\n * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\n storageSizeLimit = STORAGE_SIZE_LIMIT,\n): ManageStateParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { operation, newState, encrypted } = params;\n\n if (\n !operation ||\n typeof operation !== 'string' ||\n !Object.values(ManageStateOperation).includes(\n operation as ManageStateOperation,\n )\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid manage state \"operation\".',\n });\n }\n\n if (encrypted !== undefined && typeof encrypted !== 'boolean') {\n throw rpcErrors.invalidParams({\n message: '\"encrypted\" parameter must be a boolean if specified.',\n });\n }\n\n if (operation === ManageStateOperation.UpdateState) {\n if (!isObject(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be a plain object.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n let size;\n try {\n // `getJsonSize` will throw if the state is not JSON serializable.\n size = getJsonSize(newState);\n } catch {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be JSON serializable.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n if (size > storageSizeLimit) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must not exceed ${storageSizeLimit} bytes in size.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"],"names":["STATE_ENCRYPTION_SALT","specificationBuilder","manageStateBuilder","STORAGE_SIZE_LIMIT","getManageStateImplementation","getValidatedParams","methodName","allowedCaveats","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","methodImplementation","subjectTypes","SubjectType","Snap","getMnemonic","getUnlockPromise","clearSnapState","getSnapState","updateSnapState","encrypt","decrypt","Object","freeze","getEncryptionKey","mnemonicPhrase","snapId","deriveEntropy","input","salt","magic","STATE_ENCRYPTION_MAGIC_VALUE","encryptState","state","encryptFunction","keyArgs","encryptionKey","decryptState","decryptFunction","decryptedState","assert","isValidJson","rpcErrors","internal","message","manageState","options","params","method","context","origin","validatedParams","shouldEncrypt","encrypted","operation","ManageStateOperation","ClearState","GetState","parseJson","UpdateState","finalizedState","newState","JSON","stringify","invalidParams","storageSizeLimit","isObject","values","includes","undefined","data","receivedNewState","size","getJsonSize"],"mappings":"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"}
@@ -9,9 +9,6 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
- NotificationType: function() {
13
- return NotificationType;
14
- },
15
12
  specificationBuilder: function() {
16
13
  return specificationBuilder;
17
14
  },
@@ -27,14 +24,10 @@ _export(exports, {
27
24
  });
28
25
  const _permissioncontroller = require("@metamask/permission-controller");
29
26
  const _rpcerrors = require("@metamask/rpc-errors");
30
- const _snapsui = require("@metamask/snaps-ui");
27
+ const _snapssdk = require("@metamask/snaps-sdk");
28
+ const _snapsutils = require("@metamask/snaps-utils");
31
29
  const _utils = require("@metamask/utils");
32
30
  const methodName = 'snap_notify';
33
- var NotificationType;
34
- (function(NotificationType) {
35
- NotificationType["InApp"] = 'inApp';
36
- NotificationType["Native"] = 'native';
37
- })(NotificationType || (NotificationType = {}));
38
31
  const specificationBuilder = ({ allowedCaveats = null, methodHooks })=>{
39
32
  return {
40
33
  permissionType: _permissioncontroller.PermissionType.RestrictedMethod,
@@ -62,11 +55,11 @@ function getImplementation({ showNativeNotification, showInAppNotification, isOn
62
55
  const { params, context: { origin } } = args;
63
56
  const validatedParams = getValidatedParams(params);
64
57
  await maybeUpdatePhishingList();
65
- (0, _snapsui.assertLinksAreSafe)(validatedParams.message, isOnPhishingList);
58
+ (0, _snapsutils.validateTextLinks)(validatedParams.message, isOnPhishingList);
66
59
  switch(validatedParams.type){
67
- case NotificationType.Native:
60
+ case _snapssdk.NotificationType.Native:
68
61
  return await showNativeNotification(origin, validatedParams);
69
- case NotificationType.InApp:
62
+ case _snapssdk.NotificationType.InApp:
70
63
  return await showInAppNotification(origin, validatedParams);
71
64
  default:
72
65
  throw _rpcerrors.rpcErrors.invalidParams({
@@ -82,7 +75,7 @@ function getValidatedParams(params) {
82
75
  });
83
76
  }
84
77
  const { type, message } = params;
85
- if (!type || typeof type !== 'string' || !Object.values(NotificationType).includes(type)) {
78
+ if (!type || typeof type !== 'string' || !Object.values(_snapssdk.NotificationType).includes(type)) {
86
79
  throw _rpcerrors.rpcErrors.invalidParams({
87
80
  message: 'Must specify a valid notification "type".'
88
81
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/restricted/notify.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { assertLinksAreSafe } from '@metamask/snaps-ui';\nimport type { EnumToUnion } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { isObject } from '@metamask/utils';\n\nimport { type MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_notify';\n\n// TODO: Move all the types to a shared place when implementing more\n// notifications.\nexport enum NotificationType {\n InApp = 'inApp',\n Native = 'native',\n}\n\nexport type NotificationArgs = {\n /**\n * Enum type to determine notification type.\n */\n type: EnumToUnion<NotificationType>;\n\n /**\n * A message to show on the notification.\n */\n message: string;\n};\n\nexport type NotifyMethodHooks = {\n /**\n * @param snapId - The ID of the Snap that created the notification.\n * @param args - The notification arguments.\n */\n showNativeNotification: (\n snapId: string,\n args: NotificationArgs,\n ) => Promise<null>;\n\n /**\n * @param snapId - The ID of the Snap that created the notification.\n * @param args - The notification arguments.\n */\n showInAppNotification: (\n snapId: string,\n args: NotificationArgs,\n ) => Promise<null>;\n\n isOnPhishingList: (url: string) => boolean;\n\n maybeUpdatePhishingList: () => Promise<void>;\n};\n\ntype SpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: NotifyMethodHooks;\n};\n\ntype Specification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_notify` permission.\n * `snap_notify` allows snaps to send multiple types of notifications to its users.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_notify` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n SpecificationBuilderOptions,\n Specification\n> = ({ allowedCaveats = null, methodHooks }: SpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<NotifyMethodHooks> = {\n showNativeNotification: true,\n showInAppNotification: true,\n isOnPhishingList: true,\n maybeUpdatePhishingList: true,\n};\n\nexport const notifyBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_notify`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.showNativeNotification - A function that shows a native browser notification.\n * @param hooks.showInAppNotification - A function that shows a notification in the MetaMask UI.\n * @param hooks.isOnPhishingList - A function that checks for links against the phishing list.\n * @param hooks.maybeUpdatePhishingList - A function that updates the phishing list if needed.\n * @returns The method implementation which returns `null` on success.\n * @throws If the params are invalid.\n */\nexport function getImplementation({\n showNativeNotification,\n showInAppNotification,\n isOnPhishingList,\n maybeUpdatePhishingList,\n}: NotifyMethodHooks) {\n return async function implementation(\n args: RestrictedMethodOptions<NotificationArgs>,\n ): Promise<null> {\n const {\n params,\n context: { origin },\n } = args;\n\n const validatedParams = getValidatedParams(params);\n\n await maybeUpdatePhishingList();\n\n assertLinksAreSafe(validatedParams.message, isOnPhishingList);\n\n switch (validatedParams.type) {\n case NotificationType.Native:\n return await showNativeNotification(origin, validatedParams);\n case NotificationType.InApp:\n return await showInAppNotification(origin, validatedParams);\n default:\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid notification \"type\".',\n });\n }\n };\n}\n\n/**\n * Validates the notify method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(params: unknown): NotificationArgs {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { type, message } = params;\n\n if (\n !type ||\n typeof type !== 'string' ||\n !Object.values(NotificationType).includes(type as NotificationType)\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid notification \"type\".',\n });\n }\n\n // Set to the max message length on a Mac notification for now.\n if (!message || typeof message !== 'string' || message.length >= 50) {\n throw rpcErrors.invalidParams({\n message:\n 'Must specify a non-empty string \"message\" less than 50 characters long.',\n });\n }\n\n return params as NotificationArgs;\n}\n"],"names":["specificationBuilder","notifyBuilder","getImplementation","getValidatedParams","methodName","NotificationType","InApp","Native","allowedCaveats","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","methodImplementation","subjectTypes","SubjectType","Snap","showNativeNotification","showInAppNotification","isOnPhishingList","maybeUpdatePhishingList","Object","freeze","implementation","args","params","context","origin","validatedParams","assertLinksAreSafe","message","type","rpcErrors","invalidParams","isObject","values","includes","length"],"mappings":";;;;;;;;;;;;;;IAgFaA,oBAAoB;eAApBA;;IAqBAC,aAAa;eAAbA;;IAiBGC,iBAAiB;eAAjBA;;IAwCAC,kBAAkB;eAAlBA;;;sCAzJ4B;2BAClB;yBACS;uBAGV;AAIzB,MAAMC,aAAa;IAIZ;UAAKC,gBAAgB;IAAhBA,iBACVC,WAAQ;IADED,iBAEVE,YAAS;GAFCF,qBAAAA;AA8DL,MAAML,uBAIT,CAAC,EAAEQ,iBAAiB,IAAI,EAAEC,WAAW,EAA+B;IACtE,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,gBAAgB;QAC/CC,YAAYT;QACZI;QACAM,sBAAsBZ,kBAAkBO;QACxCM,cAAc;YAACC,iCAAW,CAACC,IAAI;SAAC;IAClC;AACF;AAEA,MAAMR,cAAoD;IACxDS,wBAAwB;IACxBC,uBAAuB;IACvBC,kBAAkB;IAClBC,yBAAyB;AAC3B;AAEO,MAAMpB,gBAAgBqB,OAAOC,MAAM,CAAC;IACzCV,YAAYT;IACZJ;IACAS;AACF;AAaO,SAASP,kBAAkB,EAChCgB,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,uBAAuB,EACL;IAClB,OAAO,eAAeG,eACpBC,IAA+C;QAE/C,MAAM,EACJC,MAAM,EACNC,SAAS,EAAEC,MAAM,EAAE,EACpB,GAAGH;QAEJ,MAAMI,kBAAkB1B,mBAAmBuB;QAE3C,MAAML;QAENS,IAAAA,2BAAkB,EAACD,gBAAgBE,OAAO,EAAEX;QAE5C,OAAQS,gBAAgBG,IAAI;YAC1B,KAAK3B,iBAAiBE,MAAM;gBAC1B,OAAO,MAAMW,uBAAuBU,QAAQC;YAC9C,KAAKxB,iBAAiBC,KAAK;gBACzB,OAAO,MAAMa,sBAAsBS,QAAQC;YAC7C;gBACE,MAAMI,oBAAS,CAACC,aAAa,CAAC;oBAC5BH,SAAS;gBACX;QACJ;IACF;AACF;AASO,SAAS5B,mBAAmBuB,MAAe;IAChD,IAAI,CAACS,IAAAA,eAAQ,EAACT,SAAS;QACrB,MAAMO,oBAAS,CAACC,aAAa,CAAC;YAC5BH,SAAS;QACX;IACF;IAEA,MAAM,EAAEC,IAAI,EAAED,OAAO,EAAE,GAAGL;IAE1B,IACE,CAACM,QACD,OAAOA,SAAS,YAChB,CAACV,OAAOc,MAAM,CAAC/B,kBAAkBgC,QAAQ,CAACL,OAC1C;QACA,MAAMC,oBAAS,CAACC,aAAa,CAAC;YAC5BH,SAAS;QACX;IACF;IAEA,+DAA+D;IAC/D,IAAI,CAACA,WAAW,OAAOA,YAAY,YAAYA,QAAQO,MAAM,IAAI,IAAI;QACnE,MAAML,oBAAS,CAACC,aAAa,CAAC;YAC5BH,SACE;QACJ;IACF;IAEA,OAAOL;AACT"}
1
+ {"version":3,"sources":["../../../src/restricted/notify.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { NotificationType } from '@metamask/snaps-sdk';\nimport type {\n NotifyParams,\n NotifyResult,\n EnumToUnion,\n} from '@metamask/snaps-sdk';\nimport { validateTextLinks } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { isObject } from '@metamask/utils';\n\nimport { type MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_notify';\n\nexport type NotificationArgs = {\n /**\n * Enum type to determine notification type.\n */\n type: EnumToUnion<NotificationType>;\n\n /**\n * A message to show on the notification.\n */\n message: string;\n};\n\nexport type NotifyMethodHooks = {\n /**\n * @param snapId - The ID of the Snap that created the notification.\n * @param args - The notification arguments.\n */\n showNativeNotification: (\n snapId: string,\n args: NotificationArgs,\n ) => Promise<null>;\n\n /**\n * @param snapId - The ID of the Snap that created the notification.\n * @param args - The notification arguments.\n */\n showInAppNotification: (\n snapId: string,\n args: NotificationArgs,\n ) => Promise<null>;\n\n isOnPhishingList: (url: string) => boolean;\n\n maybeUpdatePhishingList: () => Promise<void>;\n};\n\ntype SpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: NotifyMethodHooks;\n};\n\ntype Specification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_notify` permission.\n * `snap_notify` allows snaps to send multiple types of notifications to its users.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_notify` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n SpecificationBuilderOptions,\n Specification\n> = ({ allowedCaveats = null, methodHooks }: SpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<NotifyMethodHooks> = {\n showNativeNotification: true,\n showInAppNotification: true,\n isOnPhishingList: true,\n maybeUpdatePhishingList: true,\n};\n\nexport const notifyBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_notify`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.showNativeNotification - A function that shows a native browser notification.\n * @param hooks.showInAppNotification - A function that shows a notification in the MetaMask UI.\n * @param hooks.isOnPhishingList - A function that checks for links against the phishing list.\n * @param hooks.maybeUpdatePhishingList - A function that updates the phishing list if needed.\n * @returns The method implementation which returns `null` on success.\n * @throws If the params are invalid.\n */\nexport function getImplementation({\n showNativeNotification,\n showInAppNotification,\n isOnPhishingList,\n maybeUpdatePhishingList,\n}: NotifyMethodHooks) {\n return async function implementation(\n args: RestrictedMethodOptions<NotifyParams>,\n ): Promise<NotifyResult> {\n const {\n params,\n context: { origin },\n } = args;\n\n const validatedParams = getValidatedParams(params);\n\n await maybeUpdatePhishingList();\n\n validateTextLinks(validatedParams.message, isOnPhishingList);\n\n switch (validatedParams.type) {\n case NotificationType.Native:\n return await showNativeNotification(origin, validatedParams);\n case NotificationType.InApp:\n return await showInAppNotification(origin, validatedParams);\n default:\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid notification \"type\".',\n });\n }\n };\n}\n\n/**\n * Validates the notify method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(params: unknown): NotifyParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { type, message } = params;\n\n if (\n !type ||\n typeof type !== 'string' ||\n !Object.values(NotificationType).includes(type as NotificationType)\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid notification \"type\".',\n });\n }\n\n // Set to the max message length on a Mac notification for now.\n if (!message || typeof message !== 'string' || message.length >= 50) {\n throw rpcErrors.invalidParams({\n message:\n 'Must specify a non-empty string \"message\" less than 50 characters long.',\n });\n }\n\n return params as NotificationArgs;\n}\n"],"names":["specificationBuilder","notifyBuilder","getImplementation","getValidatedParams","methodName","allowedCaveats","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","methodImplementation","subjectTypes","SubjectType","Snap","showNativeNotification","showInAppNotification","isOnPhishingList","maybeUpdatePhishingList","Object","freeze","implementation","args","params","context","origin","validatedParams","validateTextLinks","message","type","NotificationType","Native","InApp","rpcErrors","invalidParams","isObject","values","includes","length"],"mappings":";;;;;;;;;;;IA8EaA,oBAAoB;eAApBA;;IAqBAC,aAAa;eAAbA;;IAiBGC,iBAAiB;eAAjBA;;IAwCAC,kBAAkB;eAAlBA;;;sCAvJ4B;2BAClB;0BACO;4BAMC;uBAET;AAIzB,MAAMC,aAAa;AA2DZ,MAAMJ,uBAIT,CAAC,EAAEK,iBAAiB,IAAI,EAAEC,WAAW,EAA+B;IACtE,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,gBAAgB;QAC/CC,YAAYN;QACZC;QACAM,sBAAsBT,kBAAkBI;QACxCM,cAAc;YAACC,iCAAW,CAACC,IAAI;SAAC;IAClC;AACF;AAEA,MAAMR,cAAoD;IACxDS,wBAAwB;IACxBC,uBAAuB;IACvBC,kBAAkB;IAClBC,yBAAyB;AAC3B;AAEO,MAAMjB,gBAAgBkB,OAAOC,MAAM,CAAC;IACzCV,YAAYN;IACZJ;IACAM;AACF;AAaO,SAASJ,kBAAkB,EAChCa,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,uBAAuB,EACL;IAClB,OAAO,eAAeG,eACpBC,IAA2C;QAE3C,MAAM,EACJC,MAAM,EACNC,SAAS,EAAEC,MAAM,EAAE,EACpB,GAAGH;QAEJ,MAAMI,kBAAkBvB,mBAAmBoB;QAE3C,MAAML;QAENS,IAAAA,6BAAiB,EAACD,gBAAgBE,OAAO,EAAEX;QAE3C,OAAQS,gBAAgBG,IAAI;YAC1B,KAAKC,0BAAgB,CAACC,MAAM;gBAC1B,OAAO,MAAMhB,uBAAuBU,QAAQC;YAC9C,KAAKI,0BAAgB,CAACE,KAAK;gBACzB,OAAO,MAAMhB,sBAAsBS,QAAQC;YAC7C;gBACE,MAAMO,oBAAS,CAACC,aAAa,CAAC;oBAC5BN,SAAS;gBACX;QACJ;IACF;AACF;AASO,SAASzB,mBAAmBoB,MAAe;IAChD,IAAI,CAACY,IAAAA,eAAQ,EAACZ,SAAS;QACrB,MAAMU,oBAAS,CAACC,aAAa,CAAC;YAC5BN,SAAS;QACX;IACF;IAEA,MAAM,EAAEC,IAAI,EAAED,OAAO,EAAE,GAAGL;IAE1B,IACE,CAACM,QACD,OAAOA,SAAS,YAChB,CAACV,OAAOiB,MAAM,CAACN,0BAAgB,EAAEO,QAAQ,CAACR,OAC1C;QACA,MAAMI,oBAAS,CAACC,aAAa,CAAC;YAC5BN,SAAS;QACX;IACF;IAEA,+DAA+D;IAC/D,IAAI,CAACA,WAAW,OAAOA,YAAY,YAAYA,QAAQU,MAAM,IAAI,IAAI;QACnE,MAAML,oBAAS,CAACC,aAAa,CAAC;YAC5BN,SACE;QACJ;IACF;IAEA,OAAOL;AACT"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export type { PermittedRpcMethodHooks } from './permitted';\nexport {\n handlers as permittedMethods,\n createSnapsMethodMiddleware,\n} from './permitted';\nexport * from './restricted';\nexport { SnapCaveatType } from '@metamask/snaps-utils';\nexport { selectHooks } from './utils';\nexport type { RequestFunction, SnapsGlobalObject } from './request';\n"],"names":["handlers","permittedMethods","createSnapsMethodMiddleware","SnapCaveatType","selectHooks"],"mappings":"AACA,SACEA,YAAYC,gBAAgB,EAC5BC,2BAA2B,QACtB,cAAc;AACrB,cAAc,eAAe;AAC7B,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,WAAW,QAAQ,UAAU"}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export type { PermittedRpcMethodHooks } from './permitted';\nexport {\n handlers as permittedMethods,\n createSnapsMethodMiddleware,\n} from './permitted';\nexport * from './restricted';\nexport { SnapCaveatType } from '@metamask/snaps-utils';\nexport { selectHooks } from './utils';\n"],"names":["handlers","permittedMethods","createSnapsMethodMiddleware","SnapCaveatType","selectHooks"],"mappings":"AACA,SACEA,YAAYC,gBAAgB,EAC5BC,2BAA2B,QACtB,cAAc;AACrB,cAAc,eAAe;AAC7B,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,WAAW,QAAQ,UAAU"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/permitted/common/snapInstallation.ts"],"sourcesContent":["import type { RequestedPermissions } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { InstallSnapsResult } from '@metamask/snaps-utils';\nimport { isObject } from '@metamask/utils';\n\nexport type { InstallSnapsResult } from '@metamask/snaps-utils';\n\nexport type InstallSnapsHook = (\n requestedSnaps: RequestedPermissions,\n) => Promise<InstallSnapsResult>;\n\n/**\n * Typechecks the requested snaps and passes them to the permissions\n * controller for installation.\n *\n * @param requestedSnaps - An object containing the requested snaps to be installed. The key of the\n * object is the snap id and the value is potential extra data, i.e. version.\n * @param installSnaps - A function that tries to install a given snap, prompting the user if\n * necessary.\n * @returns An object containing the installed snaps.\n * @throws If the params are invalid or the snap installation fails.\n */\nexport async function handleInstallSnaps(\n requestedSnaps: RequestedPermissions,\n installSnaps: InstallSnapsHook,\n): Promise<InstallSnapsResult> {\n if (!isObject(requestedSnaps)) {\n throw rpcErrors.invalidParams({\n message: `Invalid snap installation params.`,\n data: { requestedSnaps },\n });\n } else if (Object.keys(requestedSnaps).length === 0) {\n throw rpcErrors.invalidParams({\n message: `Must specify at least one snap to install.`,\n data: { requestedSnaps },\n });\n }\n\n // installSnaps is bound to the origin\n return await installSnaps(requestedSnaps);\n}\n"],"names":["rpcErrors","isObject","handleInstallSnaps","requestedSnaps","installSnaps","invalidParams","message","data","Object","keys","length"],"mappings":"AACA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,QAAQ,QAAQ,kBAAkB;AAQ3C;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,mBACpBC,cAAoC,EACpCC,YAA8B;IAE9B,IAAI,CAACH,SAASE,iBAAiB;QAC7B,MAAMH,UAAUK,aAAa,CAAC;YAC5BC,SAAS,CAAC,iCAAiC,CAAC;YAC5CC,MAAM;gBAAEJ;YAAe;QACzB;IACF,OAAO,IAAIK,OAAOC,IAAI,CAACN,gBAAgBO,MAAM,KAAK,GAAG;QACnD,MAAMV,UAAUK,aAAa,CAAC;YAC5BC,SAAS,CAAC,0CAA0C,CAAC;YACrDC,MAAM;gBAAEJ;YAAe;QACzB;IACF;IAEA,sCAAsC;IACtC,OAAO,MAAMC,aAAaD;AAC5B"}
1
+ {"version":3,"sources":["../../../../src/permitted/common/snapInstallation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n RequestSnapsParams,\n RequestSnapsResult,\n} from '@metamask/snaps-sdk';\nimport { isObject } from '@metamask/utils';\n\nexport type InstallSnapsHook = (\n requestedSnaps: RequestSnapsParams,\n) => Promise<RequestSnapsResult>;\n\n/**\n * Typechecks the requested snaps and passes them to the permissions\n * controller for installation.\n *\n * @param requestedSnaps - An object containing the requested snaps to be installed. The key of the\n * object is the snap id and the value is potential extra data, i.e. version.\n * @param installSnaps - A function that tries to install a given snap, prompting the user if\n * necessary.\n * @returns An object containing the installed snaps.\n * @throws If the params are invalid or the snap installation fails.\n */\nexport async function handleInstallSnaps(\n requestedSnaps: RequestSnapsParams,\n installSnaps: InstallSnapsHook,\n): Promise<RequestSnapsResult> {\n if (!isObject(requestedSnaps)) {\n throw rpcErrors.invalidParams({\n message: `Invalid snap installation params.`,\n data: { requestedSnaps },\n });\n } else if (Object.keys(requestedSnaps).length === 0) {\n throw rpcErrors.invalidParams({\n message: `Must specify at least one snap to install.`,\n data: { requestedSnaps },\n });\n }\n\n // installSnaps is bound to the origin\n return await installSnaps(requestedSnaps);\n}\n"],"names":["rpcErrors","isObject","handleInstallSnaps","requestedSnaps","installSnaps","invalidParams","message","data","Object","keys","length"],"mappings":"AAAA,SAASA,SAAS,QAAQ,uBAAuB;AAKjD,SAASC,QAAQ,QAAQ,kBAAkB;AAM3C;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,mBACpBC,cAAkC,EAClCC,YAA8B;IAE9B,IAAI,CAACH,SAASE,iBAAiB;QAC7B,MAAMH,UAAUK,aAAa,CAAC;YAC5BC,SAAS,CAAC,iCAAiC,CAAC;YAC5CC,MAAM;gBAAEJ;YAAe;QACzB;IACF,OAAO,IAAIK,OAAOC,IAAI,CAACN,gBAAgBO,MAAM,KAAK,GAAG;QACnD,MAAMV,UAAUK,aAAa,CAAC;YAC5BC,SAAS,CAAC,0CAA0C,CAAC;YACrDC,MAAM;gBAAEJ;YAAe;QACzB;IACF;IAEA,sCAAsC;IACtC,OAAO,MAAMC,aAAaD;AAC5B"}
@@ -1,5 +1,6 @@
1
1
  import { rpcErrors } from '@metamask/rpc-errors';
2
- import { enumValue, AuxiliaryFileEncoding } from '@metamask/snaps-utils';
2
+ import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';
3
+ import { enumValue } from '@metamask/snaps-utils';
3
4
  import { assertStruct } from '@metamask/utils';
4
5
  import { object, optional, string, union } from 'superstruct';
5
6
  export const GetFileArgsStruct = object({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/permitted/getFile.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { enumValue, AuxiliaryFileEncoding } from '@metamask/snaps-utils';\nimport type {\n PendingJsonRpcResponse,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { object, optional, string, union } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nexport const GetFileArgsStruct = object({\n path: string(),\n encoding: optional(\n union([\n enumValue(AuxiliaryFileEncoding.Base64),\n enumValue(AuxiliaryFileEncoding.Hex),\n enumValue(AuxiliaryFileEncoding.Utf8),\n ]),\n ),\n});\n\nexport type GetFileArgs = Infer<typeof GetFileArgsStruct>;\n\nconst hookNames: MethodHooksObject<GetFileHooks> = {\n getSnapFile: true,\n};\n\nexport const getFileHandler: PermittedHandlerExport<\n GetFileHooks,\n GetFileArgs,\n string\n> = {\n methodNames: ['snap_getFile'],\n implementation,\n hookNames,\n};\n\nexport type GetFileHooks = {\n getSnapFile: (\n path: GetFileArgs['path'],\n encoding: GetFileArgs['encoding'],\n ) => Promise<string>;\n};\n\n/**\n * The `snap_getFile` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnapFile - The funnction to load a static snap file.\n * @returns Nothing.\n */\nasync function implementation(\n req: JsonRpcRequest<GetFileArgs>,\n res: PendingJsonRpcResponse<Json>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { getSnapFile }: GetFileHooks,\n): Promise<void> {\n const { params } = req;\n\n assertStruct(\n params,\n GetFileArgsStruct,\n 'Invalid \"snap_getFile\" parameters',\n rpcErrors.invalidParams,\n );\n\n try {\n res.result = await getSnapFile(\n params.path,\n params.encoding ?? AuxiliaryFileEncoding.Base64,\n );\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"],"names":["rpcErrors","enumValue","AuxiliaryFileEncoding","assertStruct","object","optional","string","union","GetFileArgsStruct","path","encoding","Base64","Hex","Utf8","hookNames","getSnapFile","getFileHandler","methodNames","implementation","req","res","_next","end","params","invalidParams","result","error"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AACjD,SAASC,SAAS,EAAEC,qBAAqB,QAAQ,wBAAwB;AAMzE,SAASC,YAAY,QAAQ,kBAAkB;AAE/C,SAASC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,QAAQ,cAAc;AAI9D,OAAO,MAAMC,oBAAoBJ,OAAO;IACtCK,MAAMH;IACNI,UAAUL,SACRE,MAAM;QACJN,UAAUC,sBAAsBS,MAAM;QACtCV,UAAUC,sBAAsBU,GAAG;QACnCX,UAAUC,sBAAsBW,IAAI;KACrC;AAEL,GAAG;AAIH,MAAMC,YAA6C;IACjDC,aAAa;AACf;AAEA,OAAO,MAAMC,iBAIT;IACFC,aAAa;QAAC;KAAe;IAC7BC;IACAJ;AACF,EAAE;AASF;;;;;;;;;;;CAWC,GACD,eAAeI,eACbC,GAAgC,EAChCC,GAAiC,EACjCC,KAAc,EACdC,GAA6B,EAC7B,EAAEP,WAAW,EAAgB;IAE7B,MAAM,EAAEQ,MAAM,EAAE,GAAGJ;IAEnBhB,aACEoB,QACAf,mBACA,qCACAR,UAAUwB,aAAa;IAGzB,IAAI;QACFJ,IAAIK,MAAM,GAAG,MAAMV,YACjBQ,OAAOd,IAAI,EACXc,OAAOb,QAAQ,IAAIR,sBAAsBS,MAAM;IAEnD,EAAE,OAAOe,OAAO;QACd,OAAOJ,IAAII;IACb;IAEA,OAAOJ;AACT"}
1
+ {"version":3,"sources":["../../../src/permitted/getFile.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { GetFileParams, GetFileResult } from '@metamask/snaps-sdk';\nimport { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport { enumValue } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse, JsonRpcRequest } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport { object, optional, string, union } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nexport const GetFileArgsStruct = object({\n path: string(),\n encoding: optional(\n union([\n enumValue(AuxiliaryFileEncoding.Base64),\n enumValue(AuxiliaryFileEncoding.Hex),\n enumValue(AuxiliaryFileEncoding.Utf8),\n ]),\n ),\n});\n\nexport type InferredGetFileParams = InferMatching<\n typeof GetFileArgsStruct,\n GetFileParams\n>;\n\nconst hookNames: MethodHooksObject<GetFileHooks> = {\n getSnapFile: true,\n};\n\nexport const getFileHandler: PermittedHandlerExport<\n GetFileHooks,\n InferredGetFileParams,\n string\n> = {\n methodNames: ['snap_getFile'],\n implementation,\n hookNames,\n};\n\nexport type GetFileHooks = {\n getSnapFile: (\n path: InferredGetFileParams['path'],\n encoding: InferredGetFileParams['encoding'],\n ) => Promise<string>;\n};\n\n/**\n * The `snap_getFile` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnapFile - The funnction to load a static snap file.\n * @returns Nothing.\n */\nasync function implementation(\n req: JsonRpcRequest<InferredGetFileParams>,\n res: PendingJsonRpcResponse<GetFileResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { getSnapFile }: GetFileHooks,\n): Promise<void> {\n const { params } = req;\n\n assertStruct(\n params,\n GetFileArgsStruct,\n 'Invalid \"snap_getFile\" parameters',\n rpcErrors.invalidParams,\n );\n\n try {\n res.result = await getSnapFile(\n params.path,\n params.encoding ?? AuxiliaryFileEncoding.Base64,\n );\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"],"names":["rpcErrors","AuxiliaryFileEncoding","enumValue","assertStruct","object","optional","string","union","GetFileArgsStruct","path","encoding","Base64","Hex","Utf8","hookNames","getSnapFile","getFileHandler","methodNames","implementation","req","res","_next","end","params","invalidParams","result","error"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,qBAAqB,QAAQ,sBAAsB;AAE5D,SAASC,SAAS,QAAQ,wBAAwB;AAElD,SAASC,YAAY,QAAQ,kBAAkB;AAC/C,SAASC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,QAAQ,cAAc;AAI9D,OAAO,MAAMC,oBAAoBJ,OAAO;IACtCK,MAAMH;IACNI,UAAUL,SACRE,MAAM;QACJL,UAAUD,sBAAsBU,MAAM;QACtCT,UAAUD,sBAAsBW,GAAG;QACnCV,UAAUD,sBAAsBY,IAAI;KACrC;AAEL,GAAG;AAOH,MAAMC,YAA6C;IACjDC,aAAa;AACf;AAEA,OAAO,MAAMC,iBAIT;IACFC,aAAa;QAAC;KAAe;IAC7BC;IACAJ;AACF,EAAE;AASF;;;;;;;;;;;CAWC,GACD,eAAeI,eACbC,GAA0C,EAC1CC,GAA0C,EAC1CC,KAAc,EACdC,GAA6B,EAC7B,EAAEP,WAAW,EAAgB;IAE7B,MAAM,EAAEQ,MAAM,EAAE,GAAGJ;IAEnBhB,aACEoB,QACAf,mBACA,qCACAR,UAAUwB,aAAa;IAGzB,IAAI;QACFJ,IAAIK,MAAM,GAAG,MAAMV,YACjBQ,OAAOd,IAAI,EACXc,OAAOb,QAAQ,IAAIT,sBAAsBU,MAAM;IAEnD,EAAE,OAAOe,OAAO;QACd,OAAOJ,IAAII;IACb;IAEA,OAAOJ;AACT"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/permitted/getSnaps.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport type { InstallSnapsResult } from '@metamask/snaps-utils';\nimport type { JsonRpcParams, PendingJsonRpcResponse } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<GetSnapsHooks> = {\n getSnaps: true,\n};\n\n/**\n * `wallet_getSnaps` gets the requester's permitted and installed Snaps.\n */\nexport const getSnapsHandler: PermittedHandlerExport<\n GetSnapsHooks,\n JsonRpcParams,\n InstallSnapsResult\n> = {\n methodNames: ['wallet_getSnaps'],\n implementation: getSnapsImplementation,\n hookNames,\n};\n\nexport type GetSnapsHooks = {\n /**\n * @returns The permitted and installed snaps for the requesting origin.\n */\n getSnaps: () => Promise<InstallSnapsResult>;\n};\n\n/**\n * The `wallet_getSnaps` method implementation.\n * Fetches available snaps for the requesting origin and adds them to the JSON-RPC response.\n *\n * @param _req - The JSON-RPC request object. Not used by this function.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnaps - A function that returns the snaps available for the requesting origin.\n * @returns Nothing.\n */\nasync function getSnapsImplementation(\n _req: unknown,\n res: PendingJsonRpcResponse<InstallSnapsResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { getSnaps }: GetSnapsHooks,\n): Promise<void> {\n // getSnaps is already bound to the origin\n res.result = await getSnaps();\n return end();\n}\n"],"names":["hookNames","getSnaps","getSnapsHandler","methodNames","implementation","getSnapsImplementation","_req","res","_next","end","result"],"mappings":"AAOA,MAAMA,YAA8C;IAClDC,UAAU;AACZ;AAEA;;CAEC,GACD,OAAO,MAAMC,kBAIT;IACFC,aAAa;QAAC;KAAkB;IAChCC,gBAAgBC;IAChBL;AACF,EAAE;AASF;;;;;;;;;;;;CAYC,GACD,eAAeK,uBACbC,IAAa,EACbC,GAA+C,EAC/CC,KAAc,EACdC,GAA6B,EAC7B,EAAER,QAAQ,EAAiB;IAE3B,0CAA0C;IAC1CM,IAAIG,MAAM,GAAG,MAAMT;IACnB,OAAOQ;AACT"}
1
+ {"version":3,"sources":["../../../src/permitted/getSnaps.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport type { GetSnapsResult } from '@metamask/snaps-sdk';\nimport type { JsonRpcParams, PendingJsonRpcResponse } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<GetSnapsHooks> = {\n getSnaps: true,\n};\n\n/**\n * `wallet_getSnaps` gets the requester's permitted and installed Snaps.\n */\nexport const getSnapsHandler: PermittedHandlerExport<\n GetSnapsHooks,\n JsonRpcParams,\n GetSnapsResult\n> = {\n methodNames: ['wallet_getSnaps'],\n implementation: getSnapsImplementation,\n hookNames,\n};\n\nexport type GetSnapsHooks = {\n /**\n * @returns The permitted and installed snaps for the requesting origin.\n */\n getSnaps: () => Promise<GetSnapsResult>;\n};\n\n/**\n * The `wallet_getSnaps` method implementation.\n * Fetches available snaps for the requesting origin and adds them to the JSON-RPC response.\n *\n * @param _req - The JSON-RPC request object. Not used by this function.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnaps - A function that returns the snaps available for the requesting origin.\n * @returns Nothing.\n */\nasync function getSnapsImplementation(\n _req: unknown,\n res: PendingJsonRpcResponse<GetSnapsResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { getSnaps }: GetSnapsHooks,\n): Promise<void> {\n // getSnaps is already bound to the origin\n res.result = await getSnaps();\n return end();\n}\n"],"names":["hookNames","getSnaps","getSnapsHandler","methodNames","implementation","getSnapsImplementation","_req","res","_next","end","result"],"mappings":"AAOA,MAAMA,YAA8C;IAClDC,UAAU;AACZ;AAEA;;CAEC,GACD,OAAO,MAAMC,kBAIT;IACFC,aAAa;QAAC;KAAkB;IAChCC,gBAAgBC;IAChBL;AACF,EAAE;AASF;;;;;;;;;;;;CAYC,GACD,eAAeK,uBACbC,IAAa,EACbC,GAA2C,EAC3CC,KAAc,EACdC,GAA6B,EAC7B,EAAER,QAAQ,EAAiB;IAE3B,0CAA0C;IAC1CM,IAAIG,MAAM,GAAG,MAAMT;IACnB,OAAOQ;AACT"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/permitted/invokeKeyring.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Snap } from '@metamask/snaps-utils';\nimport {\n HandlerType,\n WALLET_SNAP_PERMISSION_KEY,\n type SnapId,\n type SnapRpcHookArgs,\n} from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse, JsonRpcRequest } from '@metamask/utils';\nimport { hasProperty, type Json } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport type { InvokeSnapSugarArgs } from './invokeSnapSugar';\nimport { getValidatedParams } from './invokeSnapSugar';\n\nconst hookNames: MethodHooksObject<InvokeKeyringHooks> = {\n hasPermission: true,\n handleSnapRpcRequest: true,\n getSnap: true,\n getAllowedKeyringMethods: true,\n};\n\n/**\n * `wallet_invokeKeyring` gets the requester's permitted and installed Snaps.\n */\nexport const invokeKeyringHandler: PermittedHandlerExport<\n InvokeKeyringHooks,\n JsonRpcRequest,\n Json\n> = {\n methodNames: ['wallet_invokeKeyring'],\n implementation: invokeKeyringImplementation,\n hookNames,\n};\n\nexport type InvokeKeyringHooks = {\n hasPermission: (origin: string, permissionName: string) => boolean;\n\n handleSnapRpcRequest: ({\n snapId,\n origin,\n handler,\n request,\n }: SnapRpcHookArgs & { snapId: SnapId }) => Promise<unknown>;\n\n getSnap: (snapId: SnapId) => Snap | undefined;\n\n getAllowedKeyringMethods: (origin: string) => string[];\n};\n\n/**\n * The `wallet_invokeKeyring` method implementation.\n * Invokes onKeyringRequest if the snap requested is installed and connected to the dapp.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.handleSnapRpcRequest - Invokes a snap with a given RPC request.\n * @param hooks.hasPermission - Checks whether a given origin has a given permission.\n * @param hooks.getSnap - Gets information about a given snap.\n * @param hooks.getAllowedKeyringMethods - Get the list of allowed Keyring\n * methods for a given origin.\n * @returns Nothing.\n */\nasync function invokeKeyringImplementation(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse<Json>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n handleSnapRpcRequest,\n hasPermission,\n getSnap,\n getAllowedKeyringMethods,\n }: InvokeKeyringHooks,\n): Promise<void> {\n let params: InvokeSnapSugarArgs;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n // We expect the MM middleware stack to always add the origin to requests\n const { origin } = req as JsonRpcRequest & { origin: string };\n const { snapId, request } = params;\n\n if (!origin || !hasPermission(origin, WALLET_SNAP_PERMISSION_KEY)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not connected to \"${origin}\". Please connect before invoking the snap.`,\n }),\n );\n }\n\n if (!getSnap(snapId)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not installed. Please install it first, before invoking the snap.`,\n }),\n );\n }\n\n if (!hasProperty(request, 'method') || typeof request.method !== 'string') {\n return end(\n rpcErrors.invalidRequest({\n message: 'The request must have a method.',\n }),\n );\n }\n\n const allowedMethods = getAllowedKeyringMethods(origin);\n if (!allowedMethods.includes(request.method)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The origin \"${origin}\" is not allowed to invoke the method \"${request.method}\".`,\n }),\n );\n }\n\n try {\n res.result = (await handleSnapRpcRequest({\n snapId,\n origin,\n request,\n handler: HandlerType.OnKeyringRequest,\n })) as Json;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"],"names":["rpcErrors","HandlerType","WALLET_SNAP_PERMISSION_KEY","hasProperty","getValidatedParams","hookNames","hasPermission","handleSnapRpcRequest","getSnap","getAllowedKeyringMethods","invokeKeyringHandler","methodNames","implementation","invokeKeyringImplementation","req","res","_next","end","params","error","origin","snapId","request","invalidRequest","message","method","allowedMethods","includes","result","handler","OnKeyringRequest"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SACEC,WAAW,EACXC,0BAA0B,QAGrB,wBAAwB;AAE/B,SAASC,WAAW,QAAmB,kBAAkB;AAIzD,SAASC,kBAAkB,QAAQ,oBAAoB;AAEvD,MAAMC,YAAmD;IACvDC,eAAe;IACfC,sBAAsB;IACtBC,SAAS;IACTC,0BAA0B;AAC5B;AAEA;;CAEC,GACD,OAAO,MAAMC,uBAIT;IACFC,aAAa;QAAC;KAAuB;IACrCC,gBAAgBC;IAChBR;AACF,EAAE;AAiBF;;;;;;;;;;;;;;;;CAgBC,GACD,eAAeQ,4BACbC,GAAmB,EACnBC,GAAiC,EACjCC,KAAc,EACdC,GAA6B,EAC7B,EACEV,oBAAoB,EACpBD,aAAa,EACbE,OAAO,EACPC,wBAAwB,EACL;IAErB,IAAIS;IACJ,IAAI;QACFA,SAASd,mBAAmBU,IAAII,MAAM;IACxC,EAAE,OAAOC,OAAO;QACd,OAAOF,IAAIE;IACb;IAEA,yEAAyE;IACzE,MAAM,EAAEC,MAAM,EAAE,GAAGN;IACnB,MAAM,EAAEO,MAAM,EAAEC,OAAO,EAAE,GAAGJ;IAE5B,IAAI,CAACE,UAAU,CAACd,cAAcc,QAAQlB,6BAA6B;QACjE,OAAOe,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS,CAAC,UAAU,EAAEH,OAAO,uBAAuB,EAAED,OAAO,2CAA2C,CAAC;QAC3G;IAEJ;IAEA,IAAI,CAACZ,QAAQa,SAAS;QACpB,OAAOJ,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS,CAAC,UAAU,EAAEH,OAAO,sEAAsE,CAAC;QACtG;IAEJ;IAEA,IAAI,CAAClB,YAAYmB,SAAS,aAAa,OAAOA,QAAQG,MAAM,KAAK,UAAU;QACzE,OAAOR,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS;QACX;IAEJ;IAEA,MAAME,iBAAiBjB,yBAAyBW;IAChD,IAAI,CAACM,eAAeC,QAAQ,CAACL,QAAQG,MAAM,GAAG;QAC5C,OAAOR,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS,CAAC,YAAY,EAAEJ,OAAO,uCAAuC,EAAEE,QAAQG,MAAM,CAAC,EAAE,CAAC;QAC5F;IAEJ;IAEA,IAAI;QACFV,IAAIa,MAAM,GAAI,MAAMrB,qBAAqB;YACvCc;YACAD;YACAE;YACAO,SAAS5B,YAAY6B,gBAAgB;QACvC;IACF,EAAE,OAAOX,OAAO;QACd,OAAOF,IAAIE;IACb;IAEA,OAAOF;AACT"}
1
+ {"version":3,"sources":["../../../src/permitted/invokeKeyring.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n InvokeKeyringParams,\n InvokeKeyringResult,\n InvokeSnapParams,\n} from '@metamask/snaps-sdk';\nimport type { Snap, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { HandlerType, WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse, JsonRpcRequest } from '@metamask/utils';\nimport { hasProperty, type Json } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getValidatedParams } from './invokeSnapSugar';\n\nconst hookNames: MethodHooksObject<InvokeKeyringHooks> = {\n hasPermission: true,\n handleSnapRpcRequest: true,\n getSnap: true,\n getAllowedKeyringMethods: true,\n};\n\n/**\n * `wallet_invokeKeyring` gets the requester's permitted and installed Snaps.\n */\nexport const invokeKeyringHandler: PermittedHandlerExport<\n InvokeKeyringHooks,\n InvokeSnapParams,\n InvokeKeyringResult\n> = {\n methodNames: ['wallet_invokeKeyring'],\n implementation: invokeKeyringImplementation,\n hookNames,\n};\n\nexport type InvokeKeyringHooks = {\n hasPermission: (origin: string, permissionName: string) => boolean;\n\n handleSnapRpcRequest: ({\n snapId,\n origin,\n handler,\n request,\n }: SnapRpcHookArgs & { snapId: string }) => Promise<unknown>;\n\n getSnap: (snapId: string) => Snap | undefined;\n\n getAllowedKeyringMethods: (origin: string) => string[];\n};\n\n/**\n * The `wallet_invokeKeyring` method implementation.\n * Invokes onKeyringRequest if the snap requested is installed and connected to the dapp.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.handleSnapRpcRequest - Invokes a snap with a given RPC request.\n * @param hooks.hasPermission - Checks whether a given origin has a given permission.\n * @param hooks.getSnap - Gets information about a given snap.\n * @param hooks.getAllowedKeyringMethods - Get the list of allowed Keyring\n * methods for a given origin.\n * @returns Nothing.\n */\nasync function invokeKeyringImplementation(\n req: JsonRpcRequest<InvokeKeyringParams>,\n res: PendingJsonRpcResponse<InvokeKeyringResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n handleSnapRpcRequest,\n hasPermission,\n getSnap,\n getAllowedKeyringMethods,\n }: InvokeKeyringHooks,\n): Promise<void> {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n // We expect the MM middleware stack to always add the origin to requests\n const { origin } = req as JsonRpcRequest & { origin: string };\n const { snapId, request } = params;\n\n if (!origin || !hasPermission(origin, WALLET_SNAP_PERMISSION_KEY)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not connected to \"${origin}\". Please connect before invoking the snap.`,\n }),\n );\n }\n\n if (!getSnap(snapId)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not installed. Please install it first, before invoking the snap.`,\n }),\n );\n }\n\n if (!hasProperty(request, 'method') || typeof request.method !== 'string') {\n return end(\n rpcErrors.invalidRequest({\n message: 'The request must have a method.',\n }),\n );\n }\n\n const allowedMethods = getAllowedKeyringMethods(origin);\n if (!allowedMethods.includes(request.method)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The origin \"${origin}\" is not allowed to invoke the method \"${request.method}\".`,\n }),\n );\n }\n\n try {\n res.result = (await handleSnapRpcRequest({\n snapId,\n origin,\n request,\n handler: HandlerType.OnKeyringRequest,\n })) as Json;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"],"names":["rpcErrors","HandlerType","WALLET_SNAP_PERMISSION_KEY","hasProperty","getValidatedParams","hookNames","hasPermission","handleSnapRpcRequest","getSnap","getAllowedKeyringMethods","invokeKeyringHandler","methodNames","implementation","invokeKeyringImplementation","req","res","_next","end","params","error","origin","snapId","request","invalidRequest","message","method","allowedMethods","includes","result","handler","OnKeyringRequest"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AAOjD,SAASC,WAAW,EAAEC,0BAA0B,QAAQ,wBAAwB;AAEhF,SAASC,WAAW,QAAmB,kBAAkB;AAGzD,SAASC,kBAAkB,QAAQ,oBAAoB;AAEvD,MAAMC,YAAmD;IACvDC,eAAe;IACfC,sBAAsB;IACtBC,SAAS;IACTC,0BAA0B;AAC5B;AAEA;;CAEC,GACD,OAAO,MAAMC,uBAIT;IACFC,aAAa;QAAC;KAAuB;IACrCC,gBAAgBC;IAChBR;AACF,EAAE;AAiBF;;;;;;;;;;;;;;;;CAgBC,GACD,eAAeQ,4BACbC,GAAwC,EACxCC,GAAgD,EAChDC,KAAc,EACdC,GAA6B,EAC7B,EACEV,oBAAoB,EACpBD,aAAa,EACbE,OAAO,EACPC,wBAAwB,EACL;IAErB,IAAIS;IACJ,IAAI;QACFA,SAASd,mBAAmBU,IAAII,MAAM;IACxC,EAAE,OAAOC,OAAO;QACd,OAAOF,IAAIE;IACb;IAEA,yEAAyE;IACzE,MAAM,EAAEC,MAAM,EAAE,GAAGN;IACnB,MAAM,EAAEO,MAAM,EAAEC,OAAO,EAAE,GAAGJ;IAE5B,IAAI,CAACE,UAAU,CAACd,cAAcc,QAAQlB,6BAA6B;QACjE,OAAOe,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS,CAAC,UAAU,EAAEH,OAAO,uBAAuB,EAAED,OAAO,2CAA2C,CAAC;QAC3G;IAEJ;IAEA,IAAI,CAACZ,QAAQa,SAAS;QACpB,OAAOJ,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS,CAAC,UAAU,EAAEH,OAAO,sEAAsE,CAAC;QACtG;IAEJ;IAEA,IAAI,CAAClB,YAAYmB,SAAS,aAAa,OAAOA,QAAQG,MAAM,KAAK,UAAU;QACzE,OAAOR,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS;QACX;IAEJ;IAEA,MAAME,iBAAiBjB,yBAAyBW;IAChD,IAAI,CAACM,eAAeC,QAAQ,CAACL,QAAQG,MAAM,GAAG;QAC5C,OAAOR,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS,CAAC,YAAY,EAAEJ,OAAO,uCAAuC,EAAEE,QAAQG,MAAM,CAAC,EAAE,CAAC;QAC5F;IAEJ;IAEA,IAAI;QACFV,IAAIa,MAAM,GAAI,MAAMrB,qBAAqB;YACvCc;YACAD;YACAE;YACAO,SAAS5B,YAAY6B,gBAAgB;QACvC;IACF,EAAE,OAAOX,OAAO;QACd,OAAOF,IAAIE;IACb;IAEA,OAAOF;AACT"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/permitted/invokeSnapSugar.ts"],"sourcesContent":["import type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport { isObject } from '@metamask/utils';\n\nexport type InvokeSnapSugarArgs = {\n snapId: string;\n request: Record<string, Json>;\n};\n\n/**\n * `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap.\n */\nexport const invokeSnapSugarHandler: PermittedHandlerExport<\n void,\n InvokeSnapSugarArgs,\n Json\n> = {\n methodNames: ['wallet_invokeSnap'],\n implementation: invokeSnapSugar,\n hookNames: undefined,\n};\n\n/**\n * The `wallet_invokeSnap` method implementation.\n * Reroutes incoming JSON-RPC requests that are targeting snaps, by modifying the method and params.\n *\n * @param req - The JSON-RPC request object.\n * @param _res - The JSON-RPC response object. Not used by this\n * function.\n * @param next - The `json-rpc-engine` \"next\" callback.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @returns Nothing.\n * @throws If the params are invalid.\n */\nexport function invokeSnapSugar(\n req: JsonRpcRequest<InvokeSnapSugarArgs>,\n _res: unknown,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n): void {\n let params: InvokeSnapSugarArgs;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n req.method = 'wallet_snap';\n req.params = params;\n return next();\n}\n\n/**\n * Validates the wallet_invokeSnap method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(params: unknown): InvokeSnapSugarArgs {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { snapId, request } = params;\n\n if (!snapId || typeof snapId !== 'string' || snapId === '') {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid snap ID.',\n });\n }\n\n if (!isObject(request)) {\n throw rpcErrors.invalidParams({\n message: 'Expected request to be a single object.',\n });\n }\n\n return params as InvokeSnapSugarArgs;\n}\n"],"names":["rpcErrors","isObject","invokeSnapSugarHandler","methodNames","implementation","invokeSnapSugar","hookNames","undefined","req","_res","next","end","params","getValidatedParams","error","method","invalidParams","message","snapId","request"],"mappings":"AAKA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,QAAQ,QAAQ,kBAAkB;AAO3C;;CAEC,GACD,OAAO,MAAMC,yBAIT;IACFC,aAAa;QAAC;KAAoB;IAClCC,gBAAgBC;IAChBC,WAAWC;AACb,EAAE;AAEF;;;;;;;;;;;CAWC,GACD,OAAO,SAASF,gBACdG,GAAwC,EACxCC,IAAa,EACbC,IAA+B,EAC/BC,GAA6B;IAE7B,IAAIC;IACJ,IAAI;QACFA,SAASC,mBAAmBL,IAAII,MAAM;IACxC,EAAE,OAAOE,OAAO;QACd,OAAOH,IAAIG;IACb;IAEAN,IAAIO,MAAM,GAAG;IACbP,IAAII,MAAM,GAAGA;IACb,OAAOF;AACT;AAEA;;;;;;CAMC,GACD,OAAO,SAASG,mBAAmBD,MAAe;IAChD,IAAI,CAACX,SAASW,SAAS;QACrB,MAAMZ,UAAUgB,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAE,GAAGP;IAE5B,IAAI,CAACM,UAAU,OAAOA,WAAW,YAAYA,WAAW,IAAI;QAC1D,MAAMlB,UAAUgB,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,IAAI,CAAChB,SAASkB,UAAU;QACtB,MAAMnB,UAAUgB,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,OAAOL;AACT"}
1
+ {"version":3,"sources":["../../../src/permitted/invokeSnapSugar.ts"],"sourcesContent":["import type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { InvokeSnapParams, InvokeSnapResult } from '@metamask/snaps-sdk';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { isObject } from '@metamask/utils';\n\n/**\n * `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap.\n */\nexport const invokeSnapSugarHandler: PermittedHandlerExport<\n void,\n InvokeSnapParams,\n InvokeSnapResult\n> = {\n methodNames: ['wallet_invokeSnap'],\n implementation: invokeSnapSugar,\n hookNames: undefined,\n};\n\n/**\n * The `wallet_invokeSnap` method implementation.\n * Reroutes incoming JSON-RPC requests that are targeting snaps, by modifying the method and params.\n *\n * @param req - The JSON-RPC request object.\n * @param _res - The JSON-RPC response object. Not used by this\n * function.\n * @param next - The `json-rpc-engine` \"next\" callback.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @returns Nothing.\n * @throws If the params are invalid.\n */\nexport function invokeSnapSugar(\n req: JsonRpcRequest<InvokeSnapParams>,\n _res: unknown,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n): void {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n req.method = 'wallet_snap';\n req.params = params;\n return next();\n}\n\n/**\n * Validates the wallet_invokeSnap method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(params: unknown): InvokeSnapParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { snapId, request } = params;\n\n if (!snapId || typeof snapId !== 'string' || snapId === '') {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid snap ID.',\n });\n }\n\n if (!isObject(request)) {\n throw rpcErrors.invalidParams({\n message: 'Expected request to be a single object.',\n });\n }\n\n return params as InvokeSnapParams;\n}\n"],"names":["rpcErrors","isObject","invokeSnapSugarHandler","methodNames","implementation","invokeSnapSugar","hookNames","undefined","req","_res","next","end","params","getValidatedParams","error","method","invalidParams","message","snapId","request"],"mappings":"AAKA,SAASA,SAAS,QAAQ,uBAAuB;AAGjD,SAASC,QAAQ,QAAQ,kBAAkB;AAE3C;;CAEC,GACD,OAAO,MAAMC,yBAIT;IACFC,aAAa;QAAC;KAAoB;IAClCC,gBAAgBC;IAChBC,WAAWC;AACb,EAAE;AAEF;;;;;;;;;;;CAWC,GACD,OAAO,SAASF,gBACdG,GAAqC,EACrCC,IAAa,EACbC,IAA+B,EAC/BC,GAA6B;IAE7B,IAAIC;IACJ,IAAI;QACFA,SAASC,mBAAmBL,IAAII,MAAM;IACxC,EAAE,OAAOE,OAAO;QACd,OAAOH,IAAIG;IACb;IAEAN,IAAIO,MAAM,GAAG;IACbP,IAAII,MAAM,GAAGA;IACb,OAAOF;AACT;AAEA;;;;;;CAMC,GACD,OAAO,SAASG,mBAAmBD,MAAe;IAChD,IAAI,CAACX,SAASW,SAAS;QACrB,MAAMZ,UAAUgB,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAE,GAAGP;IAE5B,IAAI,CAACM,UAAU,OAAOA,WAAW,YAAYA,WAAW,IAAI;QAC1D,MAAMlB,UAAUgB,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,IAAI,CAAChB,SAASkB,UAAU;QACtB,MAAMnB,UAAUgB,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,OAAOL;AACT"}